@threenative/runtime-native 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/NOTICE +1 -1
  2. package/android/README.md +10 -0
  3. package/android/app/build.gradle.kts +23 -0
  4. package/android/app/src/main/java/com/mystral/engine/MystralActivity.java +87 -2
  5. package/android/app/src/main/java/com/mystral/engine/TnUiOverlay.java +170 -8
  6. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  7. package/build/web/tn-native-engine-web.mjs +2 -0
  8. package/build/web/tn-native-engine-web.wasm +0 -0
  9. package/package.json +20 -6
  10. package/scripts/asset-manifest.mjs +38 -19
  11. package/scripts/bundle-native-engine.mjs +303 -0
  12. package/scripts/bundle.mjs +38 -41
  13. package/scripts/check-source-list.mjs +11 -5
  14. package/scripts/desktop-distribution.mjs +19 -5
  15. package/scripts/inspect-macos-icon.mjs +169 -0
  16. package/scripts/install-prebuilt.mjs +33 -21
  17. package/scripts/package-android.mjs +64 -6
  18. package/scripts/package-desktop.mjs +51 -14
  19. package/scripts/package-engine-desktop.mjs +102 -0
  20. package/scripts/package-ios.mjs +36 -32
  21. package/scripts/physical-device-evidence.mjs +135 -1
  22. package/scripts/production-evidence.mjs +36 -9
  23. package/scripts/profile-production.mjs +696 -146
  24. package/scripts/qualify-physical-mobile.mjs +286 -69
  25. package/scripts/verify-starter-consumer.mjs +58 -8
  26. package/scripts/verify-starter-desktop-base.mjs +12 -2
  27. package/scripts/windows-installer.mjs +12 -5
  28. package/scripts/xvfb.sh +15 -0
  29. package/src/engine/player/core-addons.mjs +15 -0
  30. package/src/engine/player/core-assets.mjs +59 -0
  31. package/src/engine/player/core-audio.mjs +11 -0
  32. package/src/engine/player/core-hdr.mjs +29 -0
  33. package/src/engine/player/core-host.mjs +148 -0
  34. package/src/engine/player/core-lut.mjs +7 -0
  35. package/src/engine/player/core-textures.mjs +167 -0
  36. package/src/engine/player/core-three.mjs +294 -0
  37. package/src/engine/player/core-tsl.mjs +80 -0
  38. package/src/engine/player/core-unused.mjs +21 -0
  39. package/src/engine/player/core-webgpu.mjs +207 -0
@@ -3,10 +3,10 @@
3
3
  import { createServer } from 'node:http';
4
4
  import { execFile, execFileSync, spawn } from 'node:child_process';
5
5
  import { existsSync } from 'node:fs';
6
- import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
6
+ import { cp, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile } from 'node:fs/promises';
7
7
  import { createRequire } from 'node:module';
8
8
  import { tmpdir } from 'node:os';
9
- import { basename, dirname, join, relative, resolve } from 'node:path';
9
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
10
10
  import { fileURLToPath, pathToFileURL } from 'node:url';
11
11
  import { promisify } from 'node:util';
12
12
  import { PNG } from 'pngjs';
@@ -19,6 +19,8 @@ import {
19
19
  REGRESSION_COLLECTION_PROFILE,
20
20
  meanFps,
21
21
  nearestRank,
22
+ oneSecondFrameFloors,
23
+ unmeasurableIntervalCount,
22
24
  sha256,
23
25
  writeProductionEvidence,
24
26
  sanitizeManifest,
@@ -59,6 +61,25 @@ const PRODUCTION_TICK_INTERVAL_MS = 1_000 / 60;
59
61
  const DESKTOP_SCREENSHOT_TIMEOUT_MS = 5_000;
60
62
  const PRODUCTION_PROFILE = 'production';
61
63
  const REGRESSION_PROFILE = 'regression';
64
+ // A selected scenario can be longer than the old fixed 30 s cap: the default scaffold alone runs
65
+ // a 60 s warmup plus a 60 s window. The budget grows with the frames the written workload asks
66
+ // for at the playtest runner's own per-tick allowance, and a base covers browser/host startup and
67
+ // first-use compilation instead of capping the run at an arbitrary 30 s.
68
+ const PLAYTEST_TIMEOUT_BASE_MS = 60_000;
69
+ const PLAYTEST_FRAME_BUDGET_MS = 250;
70
+ export function playtestTimeoutMs(scenario) {
71
+ const frameCount = (value) => (Number.isFinite(value) && value > 0 ? value : 0);
72
+ const warmupFrames = frameCount(scenario?.warmupFrames);
73
+ const frames = (Array.isArray(scenario?.steps) ? scenario.steps : []).reduce(
74
+ (total, step) => total
75
+ + frameCount(step?.holdFrames)
76
+ + frameCount(step?.waitFrames)
77
+ + frameCount(step?.holdTicks)
78
+ + frameCount(step?.waitTicks),
79
+ 0,
80
+ );
81
+ return PLAYTEST_TIMEOUT_BASE_MS + (warmupFrames + frames) * PLAYTEST_FRAME_BUDGET_MS;
82
+ }
62
83
 
63
84
  function installedPackageFile(packageName, file) {
64
85
  try {
@@ -85,6 +106,33 @@ export function resolveProductionTools() {
85
106
  };
86
107
  }
87
108
 
109
+ // The primary checkout that owns a checkout or linked worktree at `cwd`. Git's common directory is
110
+ // the one answer a linked worktree gives without being asked for a worktree: it names the primary
111
+ // `.git`, while the worktree's own parent directory is still inside the primary repository.
112
+ export function owningCheckout(cwd) {
113
+ try {
114
+ const common = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
115
+ cwd,
116
+ encoding: 'utf8',
117
+ stdio: ['ignore', 'pipe', 'ignore'],
118
+ }).trim();
119
+ return common.length > 0 ? dirname(common) : cwd;
120
+ } catch {
121
+ return cwd;
122
+ }
123
+ }
124
+
125
+ // Beside the owning primary checkout, so the staged game shares its volume and inherits no
126
+ // pnpm-workspace.yaml; an ancestor that is itself a workspace is climbed past, because pnpm reads
127
+ // the nearest one upwards and would install the staged game into it.
128
+ export function stagingParentDirectory(primaryCheckout, workspaceExists = existsSync) {
129
+ let parent = dirname(primaryCheckout);
130
+ while (parent !== dirname(parent) && workspaceExists(join(parent, 'pnpm-workspace.yaml'))) {
131
+ parent = dirname(parent);
132
+ }
133
+ return join(parent, '.threenative-profile-production');
134
+ }
135
+
88
136
  export function parseProductionArgs(argv = process.argv.slice(2)) {
89
137
  const options = {
90
138
  audioEvidence: undefined,
@@ -94,12 +142,15 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
94
142
  device: undefined,
95
143
  duration: 60,
96
144
  hostedSoftware: false,
145
+ liveClock: false,
97
146
  out: '.runtime/prd064/production',
98
147
  prebuiltArtifact: undefined,
99
148
  physicalEvidence: undefined,
100
149
  profile: PRODUCTION_PROFILE,
150
+ project: undefined,
101
151
  renderSize: undefined,
102
152
  repetitions: 3,
153
+ scenario: undefined,
103
154
  sourceSha: undefined,
104
155
  target: undefined,
105
156
  warmup: 60,
@@ -115,13 +166,16 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
115
166
  else if (flag === '--device') { explicit.add('device'); options.device = nextValue(argv, ++index, flag); }
116
167
  else if (flag === '--duration') { explicit.add('duration'); options.duration = positiveNumber(nextValue(argv, ++index, flag), flag); }
117
168
  else if (flag === '--hosted-software') { options.hostedSoftware = true; }
169
+ else if (flag === '--live-clock') { options.liveClock = true; }
118
170
  else if (flag === '--out') { explicit.add('out'); options.out = nextValue(argv, ++index, flag); }
119
171
  else if (flag === '--prebuilt-artifact') { explicit.add('prebuiltArtifact'); options.prebuiltArtifact = nextValue(argv, ++index, flag); }
120
172
  else if (flag === '--physical-evidence') { explicit.add('physicalEvidence'); options.physicalEvidence = nextValue(argv, ++index, flag); }
121
173
  else if (flag === '--profile') options.profile = nextValue(argv, ++index, flag);
174
+ else if (flag === '--project') { explicit.add('project'); options.project = nextValue(argv, ++index, flag); }
122
175
  else if (flag === '--regression') options.profile = REGRESSION_PROFILE;
123
176
  else if (flag === '--render-size') { explicit.add('renderSize'); options.renderSize = parseRenderSize(nextValue(argv, ++index, flag)); }
124
177
  else if (flag === '--repetitions') { explicit.add('repetitions'); options.repetitions = positiveInteger(nextValue(argv, ++index, flag), flag); }
178
+ else if (flag === '--scenario') { explicit.add('scenario'); options.scenario = nextValue(argv, ++index, flag); }
125
179
  else if (flag === '--source-sha') { explicit.add('sourceSha'); options.sourceSha = nextValue(argv, ++index, flag); }
126
180
  else if (flag === '--target') { explicit.add('target'); options.target = nextValue(argv, ++index, flag); }
127
181
  else if (flag === '--warmup') { explicit.add('warmup'); options.warmup = positiveNumber(nextValue(argv, ++index, flag), flag); }
@@ -139,6 +193,15 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
139
193
  return validateProductionOptions(options);
140
194
  }
141
195
 
196
+ // Lexical containment: both paths were resolved from the same --project root in normalizeOptions,
197
+ // so a symlinked project still passes and the staging re-anchor stays inside the copy. A scenario
198
+ // that escapes (../outside.json or an absolute outside path) is refused before it can be read
199
+ // outside staging or overwrite a generated scenario path.
200
+ function scenarioInsideProject(project, scenario) {
201
+ const rel = relative(project, scenario);
202
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
203
+ }
204
+
142
205
  export function validateProductionOptions(input) {
143
206
  const options = normalizeOptions(input);
144
207
  if (options.help) return options;
@@ -154,6 +217,15 @@ export function validateProductionOptions(input) {
154
217
  if (options.control !== undefined && !supportedControls.has(options.control)) {
155
218
  throw new ProductionEvidenceError('TN_PROD_CONTROL_UNSUPPORTED', `Production control '${options.control}' is not supported.`);
156
219
  }
220
+ if (options.scenario !== undefined && options.project === undefined) {
221
+ throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', '--scenario requires --project so an existing project is measured against its own scenario.');
222
+ }
223
+ if (options.scenario !== undefined && !scenarioInsideProject(options.project, options.scenario)) {
224
+ throw new ProductionEvidenceError('TN_PROD_SCENARIO_OUTSIDE_PROJECT', `--scenario '${basename(options.scenario)}' must live inside --project '${basename(options.project)}'.`);
225
+ }
226
+ if (options.target === 'fixture' && options.project !== undefined) {
227
+ throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', '--project is not valid for the fixture negative control.');
228
+ }
157
229
  if (options.target === 'fixture' && options.control === undefined) {
158
230
  throw new ProductionEvidenceError('TN_PROD_FIXTURE_CONTROL_REQUIRED', 'The fixture target is available only as an explicit negative control.');
159
231
  }
@@ -204,7 +276,7 @@ export async function runProductionProfile(input, dependencies = {}) {
204
276
 
205
277
  export async function collectProduction(options, context, runId) {
206
278
  const tools = resolveProductionTools();
207
- if (tools.scaffoldCli === undefined || !await fileExists(tools.scaffoldCli)) {
279
+ if (options.project === undefined && (tools.scaffoldCli === undefined || !await fileExists(tools.scaffoldCli))) {
208
280
  throw new ProductionEvidenceError(
209
281
  'TN_PROD_SCAFFOLDER_UNAVAILABLE',
210
282
  "The installed 'create-threenative' package does not expose its built scaffolder; install it or run the repository build first.",
@@ -217,27 +289,43 @@ export async function collectProduction(options, context, runId) {
217
289
  );
218
290
  }
219
291
 
220
- const temporaryRoot = await mkdtemp(join(tmpdir(), 'threenative-production-'));
292
+ // Resolved before the scaffold so a lane that cannot carry a frame rate costs a second, not the
293
+ // three minutes it takes to pack the workspace and build a platformer nobody may judge.
294
+ const webDisplay = webArmRequested(options) ? await rateBearingDisplay(tools) : undefined;
295
+
296
+ // Keep staging on the checkout's volume (Windows packaging cannot cross volumes), but outside
297
+ // every repository workspace. A project under repo/.runtime is discovered by pnpm as part of the
298
+ // parent workspace, so its install populates the workspace root and leaves the staged project's
299
+ // node_modules missing. A linked worktree's own parent is no better - <primary>/.worktrees is
300
+ // still inside <primary> - so the parent of the *owning primary* checkout is the one directory
301
+ // that is both same-volume and workspace-free.
302
+ const stagingParent = inRepositoryCheckout
303
+ ? stagingParentDirectory(owningCheckout(commandRoot))
304
+ : tmpdir();
305
+ await mkdir(stagingParent, { recursive: true });
306
+ const temporaryRoot = await mkdtemp(join(stagingParent, 'threenative-production-'));
221
307
  const project = join(temporaryRoot, 'platformer');
222
308
  const startedAt = new Date().toISOString();
223
309
  try {
224
- await scaffoldPlatformer(project, tools);
310
+ await stageProductionProject(options, project, tools);
225
311
  tools.workloadSourceHash = await hashPath(join(project, 'src'));
226
312
  const scenarios = await writeRunScenarios(project, options);
227
313
  const artifactsRoot = join(project, 'artifacts', 'production');
228
314
  await mkdir(artifactsRoot, { recursive: true });
229
- const web = options.target === 'web' || options.target === 'desktop-pair'
230
- ? await collectWeb(project, scenarios, artifactsRoot, options, tools)
231
- : undefined;
315
+ const web = webDisplay === undefined ? undefined : await collectWeb(project, scenarios, artifactsRoot, options, tools, webDisplay);
232
316
  const native = nativeTargets.has(options.target) || options.target === 'desktop-pair'
233
317
  ? await collectNative(project, scenarios, artifactsRoot, options, tools)
234
318
  : undefined;
319
+ const resolutionScaleSetting = native === undefined
320
+ ? undefined
321
+ : await readResolutionScaleSetting(project, options);
235
322
  return assembleEvidence({
236
323
  context,
237
324
  native,
238
325
  options,
239
326
  performanceBounds: scenarios.performanceBounds,
240
327
  project,
328
+ resolutionScaleSetting,
241
329
  runId,
242
330
  startedAt,
243
331
  web,
@@ -255,6 +343,10 @@ function normalizeOptions(input = {}) {
255
343
  const defaultRenderSize = input.hostedSoftware === true && target === 'desktop'
256
344
  ? { height: 720, width: 1280 }
257
345
  : { height: 1080, width: 1920 };
346
+ const project = input.project === undefined ? undefined : resolve(input.project);
347
+ const scenario = input.scenario === undefined
348
+ ? undefined
349
+ : project === undefined ? resolve(input.scenario) : resolve(project, input.scenario);
258
350
  return {
259
351
  audioEvidence: input.audioEvidence,
260
352
  coldStarts: input.coldStarts ?? (regression ? REGRESSION_COLLECTION_PROFILE.coldStarts : 1),
@@ -263,12 +355,18 @@ function normalizeOptions(input = {}) {
263
355
  duration: input.duration ?? (regression ? REGRESSION_COLLECTION_PROFILE.durationSeconds : 60),
264
356
  hostedSoftware: input.hostedSoftware === true,
265
357
  help: input.help,
358
+ // Listed explicitly like every other option here: this function rebuilds the option set field by
359
+ // field, so an unlisted one is dropped rather than defaulted, and a `--live-clock` that never
360
+ // reached the instrumentation would quietly profile the frozen run it was asked to replace.
361
+ liveClock: input.liveClock === true,
266
362
  out: input.out ?? (regression ? '.runtime/prd358/regression' : '.runtime/prd064/production'),
267
363
  prebuiltArtifact: input.prebuiltArtifact === undefined ? undefined : resolve(input.prebuiltArtifact),
268
364
  physicalEvidence: input.physicalEvidence,
365
+ project,
269
366
  renderSize: renderSize ?? defaultRenderSize,
270
367
  profile,
271
368
  repetitions: input.repetitions ?? (regression ? 1 : 3),
369
+ scenario,
272
370
  sourceSha: input.sourceSha,
273
371
  target,
274
372
  warmup: input.warmup ?? (regression ? 5 : 60),
@@ -279,6 +377,57 @@ function warmupFramesFor(options) {
279
377
  return Math.max(0, Math.ceil((options.warmup ?? 0) * 60));
280
378
  }
281
379
 
380
+ // Only the scaffolded default needs its ticks paced to wall time, because only it has no authored
381
+ // workload whose own step durations are the seconds the run means. A live-clock run needs it too, and
382
+ // not because it needs pacing twice: the wrapper is idempotent, so an `advance` that already spent
383
+ // the interval leaves a wait of zero or less and the pace adds nothing. Excluding it left the native
384
+ // host free to consume the frame-count workload faster than wall time, and the run published a
385
+ // measured window shorter than the `--duration` it was asked for.
386
+ function paceTicksFor(options) {
387
+ return options.project === undefined;
388
+ }
389
+
390
+ // Directories the judge regenerates itself. Copying a previous build measures stale bytes and
391
+ // copying node_modules moves gigabytes; node_modules is linked into the staged copy instead.
392
+ const PROJECT_SKIP_ENTRIES = new Set(['.runtime-mailbox', '.threenative', 'artifacts', 'dist', 'dist-native', 'node_modules']);
393
+
394
+ // The default scaffold is built and thrown away. An existing project is copied first so every
395
+ // instrumented file, scenario and build output lands in the copy and the source is never touched.
396
+ export async function stageProductionProject(options, project, tools, dependencies = {}) {
397
+ if (options.project === undefined) {
398
+ await (dependencies.scaffoldPlatformer ?? scaffoldPlatformer)(project, tools);
399
+ return project;
400
+ }
401
+ const copy = dependencies.cp ?? cp;
402
+ const link = dependencies.symlink ?? symlink;
403
+ // Realpath first: a symlinked --project must stage a copy of the target, never write through it.
404
+ const source = await realpath(options.project).catch(() => undefined);
405
+ const details = source === undefined ? undefined : await stat(source).catch(() => undefined);
406
+ if (details === undefined || !details.isDirectory()) {
407
+ throw new ProductionEvidenceError('TN_PROD_PROJECT_MISSING', `--project '${basename(options.project)}' is not an existing project directory.`);
408
+ }
409
+ await copy(source, project, {
410
+ // Dereference so a nested symlink (for example src/main.ts into another checkout) becomes a
411
+ // real staged file; instrumentation then writes the copy instead of through to its source.
412
+ dereference: true,
413
+ recursive: true,
414
+ filter: (candidate) => {
415
+ const top = relative(source, candidate).split(sep)[0];
416
+ return top === '' || !PROJECT_SKIP_ENTRIES.has(top);
417
+ },
418
+ });
419
+ // node_modules is skipped by the filter above and linked wholesale, never copied or instrumented.
420
+ if (existsSync(join(source, 'node_modules'))) {
421
+ await link(join(source, 'node_modules'), join(project, 'node_modules'));
422
+ }
423
+ if (options.scenario !== undefined) {
424
+ // The staged copy is the only project the judge may read; re-anchor a scenario named inside
425
+ // the source so runs measure the staged snapshot, not the file the developer may still edit.
426
+ options.scenario = join(project, relative(options.project, options.scenario));
427
+ }
428
+ return project;
429
+ }
430
+
282
431
  async function scaffoldPlatformer(project, tools) {
283
432
  const packageArchiveRoot = join(project, '..', 'package-archives');
284
433
  await mkdir(packageArchiveRoot, { recursive: true });
@@ -340,22 +489,40 @@ function packageSourceFlag(name) {
340
489
  throw new Error(`TN_PROD_PACKAGE_FLAG_UNSUPPORTED: ${name}`);
341
490
  }
342
491
 
343
- function nativeDiagnostics(assertions) {
344
- return {
345
- ...assertions,
346
- diagnostics: {
347
- ...assertions.diagnostics,
348
- noConsoleErrors: true,
349
- noRuntimeDiagnostics: true,
350
- runtimeReady: true,
351
- noNetworkErrors: false,
352
- networkErrorsOptOutReason: 'Native mailbox transports have no browser network observer; console and runtime diagnostics remain required.',
353
- },
354
- };
492
+ function nativeAssertions(assertions, timeoutMs, hostedSoftware) {
493
+ const { diagnostics: _browserOnly, ...supported } = assertions;
494
+ return { ...supported, startup: supported.startup ?? (hostedSoftware
495
+ ? { maxCompileSettledMs: timeoutMs }
496
+ : { maxReadyMs: timeoutMs }) };
497
+ }
498
+
499
+ /**
500
+ * What the collector ITSELF pinned, restated as the tier the run may be held to.
501
+ *
502
+ * `--hosted-software` is explicit policy configuration, not a claim about the machine: it writes
503
+ * `__THREENATIVE_PROFILE__.hostedSoftware`, and the template's own render source answers that by
504
+ * choosing the low preset. A hardware adapter that honours a pinned-low profile is the run working
505
+ * as configured, so the expectation the collector writes has to be the tier it asked for.
506
+ *
507
+ * It removes `perAdapter` outright rather than leaving the branches beside the pinned tier. The
508
+ * branches assert the tier an adapter *class* implies, and the collector's pin overrides the class's
509
+ * preference on this run: a hardware adapter held to `low` would take the software branch's stages
510
+ * and contributions and fail a workload that did exactly what it was configured to do. What stays
511
+ * is the flat expectation at the pinned tier, and classification is untouched either way — the run
512
+ * is still classified from its own `adapter.info` reading, and a hardware run with no profile input
513
+ * is still held to the template's flat `high`.
514
+ */
515
+ function hostedSoftwareAssertions(assertions, hostedSoftware) {
516
+ if (!hostedSoftware || assertions?.renderChain === undefined) return assertions;
517
+ const { perAdapter: _perAdapter, ...renderChain } = assertions.renderChain;
518
+ return { ...assertions, renderChain: { ...renderChain, tier: 'low' } };
355
519
  }
356
520
 
357
521
  export async function writeRunScenarios(project, options) {
358
- const source = JSON.parse(await readFile(join(project, platformerScenario), 'utf8'));
522
+ const scenarioPath = options.scenario ?? join(project, platformerScenario);
523
+ const source = JSON.parse(await readFile(scenarioPath, 'utf8').catch(() => {
524
+ throw new ProductionEvidenceError('TN_PROD_SCENARIO_MISSING', `Production scenario '${basename(scenarioPath)}' was not found.`);
525
+ }));
359
526
  const sourceAssertions = source.assert && typeof source.assert === 'object' && !Array.isArray(source.assert)
360
527
  ? source.assert
361
528
  : {};
@@ -369,14 +536,24 @@ export async function writeRunScenarios(project, options) {
369
536
  const { assert: _sourceAssertions, ...scenarioSource } = source;
370
537
  const workloadFrames = Math.max(1, Math.ceil(options.duration * 60));
371
538
  const warmupFrames = Math.max(0, Math.ceil(options.warmup * 60));
539
+ // An existing project's own scenario is the workload: its steps are what the game actually does
540
+ // (a menu click, a flight), and replacing them with a forward run exercises nothing. The
541
+ // scaffolded default has no authored workload, so it keeps the synthetic run the warmup and
542
+ // duration size.
543
+ const workloadSteps = options.project === undefined
544
+ ? [
545
+ { holdFrames: Math.min(60, workloadFrames), kind: 'input', press: 'ArrowRight', release: true },
546
+ { kind: 'wait', release: true, waitFrames: workloadFrames },
547
+ ]
548
+ : scenarioSource.steps;
549
+ if (!Array.isArray(workloadSteps) || workloadSteps.length === 0) {
550
+ throw new ProductionEvidenceError('TN_PROD_SCENARIO_STEPS_MISSING', `Production scenario '${basename(scenarioPath)}' defines no workload steps.`);
551
+ }
372
552
  const workload = {
373
553
  ...scenarioSource,
374
554
  assert: workloadAssertions,
375
555
  artifacts: { screenshots: 'after' },
376
- steps: [
377
- { holdFrames: Math.min(60, workloadFrames), kind: 'input', press: 'ArrowRight', release: true },
378
- { kind: 'wait', release: true, waitFrames: workloadFrames },
379
- ],
556
+ steps: workloadSteps,
380
557
  viewport: options.renderSize,
381
558
  warmupFrames,
382
559
  };
@@ -390,7 +567,18 @@ export async function writeRunScenarios(project, options) {
390
567
  waitFrames: 1,
391
568
  })),
392
569
  ]
393
- : workload.steps;
570
+ : workload.steps.map((step) => {
571
+ if (step.kind !== 'click' || step.at === undefined || 'entity' in step.at) return step;
572
+ const viewport = scenarioSource.viewport ?? options.renderSize;
573
+ const { x, y } = step.at;
574
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(viewport.width)
575
+ || !Number.isFinite(viewport.height) || viewport.width <= 0 || viewport.height <= 0
576
+ || x < 0 || y < 0 || x > viewport.width || y > viewport.height) {
577
+ throw new ProductionEvidenceError('TN_PROD_NATIVE_CLICK_INVALID', `Click step '${step.label ?? ''}' lies outside its source viewport.`);
578
+ }
579
+ const { at: _at, kind: _kind, ...pointerStep } = step;
580
+ return { ...pointerStep, pointerPosition: { buttons: 1, x: x / viewport.width, y: y / viewport.height } };
581
+ });
394
582
  const startup = {
395
583
  ...scenarioSource,
396
584
  assert: { diagnostics: { noConsoleErrors: true, runtimeReady: true } },
@@ -399,9 +587,10 @@ export async function writeRunScenarios(project, options) {
399
587
  viewport: options.renderSize,
400
588
  warmupFrames: 0,
401
589
  };
590
+ const timeoutMs = playtestTimeoutMs(workload);
402
591
  const nativeWorkload = {
403
592
  ...workload,
404
- assert: nativeDiagnostics(workload.assert),
593
+ assert: hostedSoftwareAssertions(nativeAssertions(workload.assert, timeoutMs, options.hostedSoftware), options.hostedSoftware),
405
594
  artifacts: {
406
595
  screenshots: options.profile === REGRESSION_PROFILE || nativeTarget === 'desktop'
407
596
  ? 'after'
@@ -409,7 +598,7 @@ export async function writeRunScenarios(project, options) {
409
598
  },
410
599
  steps: nativeWorkloadSteps,
411
600
  };
412
- const nativeStartup = { ...startup, assert: nativeDiagnostics(startup.assert), artifacts: { screenshots: 'after' } };
601
+ const nativeStartup = { ...startup, assert: nativeAssertions(startup.assert, timeoutMs, options.hostedSoftware), artifacts: { screenshots: 'after' } };
413
602
  const workloadPath = join(project, 'playtests/production-performance.run.playtest.json');
414
603
  const startupPath = join(project, 'playtests/production-startup.run.playtest.json');
415
604
  const nativeWorkloadPath = join(project, 'playtests/production-performance.native.playtest.json');
@@ -423,14 +612,49 @@ export async function writeRunScenarios(project, options) {
423
612
  nativeStartupPath,
424
613
  nativeWorkloadPath,
425
614
  startupPath,
615
+ timeoutMs,
426
616
  workloadPath,
427
617
  };
428
618
  }
429
619
 
430
- async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
620
+ /**
621
+ * A production frame rate is only evidence from a display that can carry one. The runner provisions
622
+ * a private software Xvfb by default, and this repository's own playtest contract says a rate read
623
+ * there is wrong rather than missing. Two collections of the same built platformer at 1920x1080 on
624
+ * this host agree: the private-display web arm reported 33.97 fps mean and a 117.1 ms p99
625
+ * (`.runtime/prd064/control/web-baseline-paired/production-evidence.json`) where the session-display
626
+ * arm reported 163.45 fps and a 19.6 ms p99
627
+ * (`.runtime/prd064/production/desktop-pair-6/production-evidence.json`) — a 4.8x difference in the
628
+ * number the gate reads. Judging the budget on the private lane measures the X server, so the run
629
+ * refuses before it spends a collection on it.
630
+ */
631
+ export function webRateDisplayFault(strategy) {
632
+ if (strategy === undefined || strategy.kind !== 'private-xvfb') return undefined;
633
+ return new ProductionEvidenceError(
634
+ 'TN_PROD_DISPLAY_UNTRUSTWORTHY',
635
+ `A web frame-rate verdict needs a display that can carry one, and this run would be measured on a private software Xvfb (${strategy.screen}). Run it with TN_PLAYTEST_HOST_DISPLAY=1 on a machine with a live X display, or judge the native arm alone.`,
636
+ );
637
+ }
638
+
639
+ function webArmRequested(options) {
640
+ return options.target === 'web' || options.target === 'desktop-pair';
641
+ }
642
+
643
+ async function rateBearingDisplay(tools) {
644
+ const { decideDisplayStrategy } = await import(pathToFileURL(tools.playtestRunner).href);
645
+ const display = decideDisplayStrategy({ env: process.env, platform: process.platform });
646
+ const fault = webRateDisplayFault(display);
647
+ if (fault !== undefined) throw fault;
648
+ return display;
649
+ }
650
+
651
+ async function collectWeb(project, scenarios, artifactsRoot, options, tools, display) {
652
+ // The marker endpoint the judge is told to report its first frame to. The game's own samples ride
653
+ // the console (a fetch from the page is an in-flight request Chromium reports as ERR_ABORTED at
654
+ // teardown, which the scenario's own noNetworkErrors policy would fail the run for).
431
655
  const markerServer = await createFrameMarkerServer(options.profile === REGRESSION_PROFILE ? 41778 : 0);
432
656
  try {
433
- await installWebProfileEntry(project, markerServer.url, options.control, warmupFramesFor(options));
657
+ await installWebProfileEntry(project, options.control, warmupFramesFor(options), paceTicksFor(options), options.liveClock);
434
658
  // A production build can outlast the default timeout on slow hosted runners.
435
659
  const build = await runCommand('pnpm', ['run', 'build:web'], project, undefined, 300_000);
436
660
  if (build.status !== 0) throw new ProductionEvidenceError('TN_PROD_WEB_BUILD_FAILED', `The scaffolded platformer web build failed.${failureSuffix(build)}`);
@@ -438,7 +662,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
438
662
  const runs = [];
439
663
  const startups = [];
440
664
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
441
- const startup = await runWebScenario(project, scenarios.startupPath, join(artifactsRoot, `web-startup-${coldStart + 1}`), markerServer, tools.playtestCli);
665
+ const startup = await runWebScenario(project, scenarios.startupPath, join(artifactsRoot, `web-startup-${coldStart + 1}`), markerServer, tools.playtestCli, scenarios.timeoutMs);
442
666
  startups.push(startup);
443
667
  for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
444
668
  runs.push(await runWebScenario(
@@ -447,6 +671,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
447
671
  join(artifactsRoot, `web-${coldStart + 1}-${repetition + 1}`),
448
672
  markerServer,
449
673
  tools.playtestCli,
674
+ scenarios.timeoutMs,
450
675
  ));
451
676
  }
452
677
  }
@@ -456,6 +681,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
456
681
  applicationClass: 'platformer-web-build',
457
682
  driverClass: 'playwright-chromium-webgpu',
458
683
  kind: 'web',
684
+ display,
459
685
  runs,
460
686
  startups,
461
687
  };
@@ -464,7 +690,16 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
464
690
  }
465
691
  }
466
692
 
467
- async function runWebScenario(project, scenarioPath, artifactDirectory, markerServer, playtestCli) {
693
+ /**
694
+ * A display is the difference between the machine's GPU and SwiftShader. Headless Chromium serves
695
+ * WebGPU from its CPU rasteriser even with the recipe's `--enable-features=Vulkan`, so a machine
696
+ * that has a display must run the web arm headed: measured on one RTX 2080, headless reported
697
+ * `google / swiftshader` and headed `nvidia / turing`. The scene-overview probe already makes the
698
+ * same choice (`packages/playtest/src/runner/sceneOverview.ts`). The web arm is refused outright
699
+ * when the runner would measure it on a private Xvfb (`webRateDisplayFault`), so an unconditional
700
+ * `--headed` here costs no headless lane its frames.
701
+ */
702
+ async function runWebScenario(project, scenarioPath, artifactDirectory, markerServer, playtestCli, timeoutMs) {
468
703
  await mkdir(artifactDirectory, { recursive: true });
469
704
  const port = await availablePort();
470
705
  const relativeArtifact = relative(project, artifactDirectory);
@@ -473,24 +708,28 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
473
708
  relative(project, scenarioPath),
474
709
  '--artifacts', relativeArtifact,
475
710
  '--browser-recipe', 'webgpu',
711
+ // The judge reports its first frame here, and the runner exempts that one request from the
712
+ // network-failure policy. The game's own samples ride the console instead.
713
+ '--judge-marker-url', markerServer.url,
714
+ '--headed',
476
715
  '--project', project,
477
716
  '--server-command', `pnpm exec vite preview --host 127.0.0.1 --port ${port} --strictPort`,
478
- '--timeout', '30000',
717
+ '--timeout', String(timeoutMs),
479
718
  '--url', `http://127.0.0.1:${port}`,
480
719
  ];
481
720
  const command = await browserCommand(args);
482
- const markerIndex = markerServer.length;
483
- const startedAt = performance.now();
484
- const result = await runCommand(command.command, command.args, commandRoot, undefined, 180_000);
485
- const markers = await markerServer.waitFor(markerIndex, 1_000);
721
+ // The game stamps its first frame with `Date.now()`, so the elapsed clock here is wall time.
722
+ const startedAt = Date.now();
723
+ // The outer process has to outlive the inner operation budget it hands the CLI, or a scenario
724
+ // the CLI is still legitimately running would be killed from outside.
725
+ const result = await runCommand(command.command, command.args, commandRoot, undefined, timeoutMs + PLAYTEST_TIMEOUT_BASE_MS);
486
726
  const report = parsePlaytestReport(result.stdout);
487
727
  return normalizeRun(
488
728
  result,
489
729
  artifactDirectory,
490
730
  'web',
491
731
  report,
492
- markers?.firstFrame === undefined ? undefined : markers.firstFrame.receivedAt - startedAt,
493
- markers?.samples ?? [],
732
+ firstFrameMsFromReport(report, startedAt),
494
733
  );
495
734
  }
496
735
 
@@ -508,12 +747,16 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
508
747
  `The scaffolded platformer ${target} build failed.${details.length === 0 ? '' : `\n${details.slice(-4_000)}`}`,
509
748
  );
510
749
  }
511
- const artifactPath = options.prebuiltArtifact ?? await nativeArtifactPath(project, target);
750
+ // A desktop prebuilt artifact supplies the runtime used to build the game; launch the packaged
751
+ // game executable, not the bare runtime CLI.
752
+ const artifactPath = target !== 'desktop' && options.prebuiltArtifact !== undefined
753
+ ? options.prebuiltArtifact
754
+ : await nativeArtifactPath(project, target);
512
755
  const artifactSha = await hashPath(artifactPath);
513
756
  const runs = [];
514
757
  const startups = [];
515
758
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
516
- const startup = await runNativeScenario(project, target, scenarios.nativeStartupPath, join(artifactsRoot, `native-startup-${coldStart + 1}`), options, artifactPath, tools);
759
+ const startup = await runNativeScenario(project, target, scenarios.nativeStartupPath, join(artifactsRoot, `native-startup-${coldStart + 1}`), options, artifactPath, tools, scenarios.timeoutMs);
517
760
  startups.push(startup);
518
761
  for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
519
762
  runs.push(await runNativeScenario(
@@ -524,6 +767,7 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
524
767
  options,
525
768
  artifactPath,
526
769
  tools,
770
+ scenarios.timeoutMs,
527
771
  ));
528
772
  }
529
773
  }
@@ -539,10 +783,10 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
539
783
  };
540
784
  }
541
785
 
542
- async function runNativeScenario(project, target, scenarioPath, artifactDirectory, options, artifactPath, tools) {
786
+ async function runNativeScenario(project, target, scenarioPath, artifactDirectory, options, artifactPath, tools, timeoutMs) {
543
787
  await mkdir(artifactDirectory, { recursive: true });
544
788
  if (target === 'desktop') {
545
- return await runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools);
789
+ return await runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools, timeoutMs);
546
790
  }
547
791
  const modulePath = await playtestRunnerPath(project, tools);
548
792
  if (modulePath === undefined) {
@@ -568,7 +812,7 @@ async function runNativeScenario(project, target, scenarioPath, artifactDirector
568
812
  projectPath: project,
569
813
  scenarioPath: relative(project, scenarioPath),
570
814
  target,
571
- timeoutMs: 30_000,
815
+ timeoutMs,
572
816
  trace: false,
573
817
  url: 'http://127.0.0.1:41777',
574
818
  };
@@ -585,14 +829,14 @@ async function runNativeScenario(project, target, scenarioPath, artifactDirector
585
829
  target,
586
830
  report,
587
831
  firstFrameMsFromReport(report, startedAt),
588
- frameSeriesFromReport(report),
832
+ frameSeriesFromReport(report, target),
589
833
  );
590
834
  } catch {
591
835
  return { elapsedMs: performance.now() - started, report: undefined, screenshot: undefined, series: undefined, status: 2 };
592
836
  }
593
837
  }
594
838
 
595
- async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools) {
839
+ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools, timeoutMs) {
596
840
  const modulePath = await playtestRunnerPath(project, tools);
597
841
  if (modulePath === undefined) {
598
842
  return { elapsedMs: undefined, report: undefined, screenshot: undefined, series: undefined, status: 2 };
@@ -604,8 +848,7 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
604
848
  const responsePath = join(mailboxRoot, 'tn-playtest-response.json');
605
849
  const runner = await import(pathToFileURL(modulePath).href);
606
850
  const mailbox = new runner.LocalDeviceMailbox();
607
- const timeoutMs = 30_000;
608
- const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath }, timeoutMs);
851
+ const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath });
609
852
  const driver = createDesktopDriver(artifactPath, project, options, mailboxRoot);
610
853
  const transport = {
611
854
  capabilities: innerTransport.capabilities,
@@ -644,7 +887,6 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
644
887
  'desktop',
645
888
  report,
646
889
  firstFrameMsFromReport(report, startedAt),
647
- frameSeriesFromReport(report),
648
890
  );
649
891
  } catch (error) {
650
892
  let cleanupError;
@@ -681,6 +923,32 @@ export function profileConfigPath(project, configPath = undefined) {
681
923
  return configPath ?? join(project, '.threenative', 'build', 'config.json');
682
924
  }
683
925
 
926
+ export function rendererResolutionScaleSetting(config, target) {
927
+ const renderer = config?.renderer ?? {};
928
+ const scale = target.startsWith('android')
929
+ ? renderer.android?.resolutionScale ?? renderer.resolutionScale
930
+ : renderer.resolutionScale;
931
+ if (scale === undefined) return 'unset';
932
+ if (scale === 'auto') return scale;
933
+ if (typeof scale !== 'number' || !Number.isFinite(scale) || scale <= 0 || scale > 1) {
934
+ throw new ProductionEvidenceError('TN_PROD_RENDERER_SCALE_INVALID', 'Built config has an invalid renderer resolutionScale.');
935
+ }
936
+ return String(scale);
937
+ }
938
+
939
+ async function readResolutionScaleSetting(project, options) {
940
+ let config;
941
+ try {
942
+ config = JSON.parse(await readFile(profileConfigPath(project, options.config), 'utf8'));
943
+ } catch (error) {
944
+ throw new ProductionEvidenceError(
945
+ 'TN_PROD_RENDERER_SCALE_MISSING',
946
+ `Could not read the built renderer config: ${error instanceof Error ? error.message : String(error)}`,
947
+ );
948
+ }
949
+ return rendererResolutionScaleSetting(config, options.target);
950
+ }
951
+
684
952
  function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
685
953
  let child;
686
954
  let output = '';
@@ -716,7 +984,7 @@ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
716
984
  if (stopping !== undefined) return stopping;
717
985
  stopping = (async () => {
718
986
  if (child === undefined || child.exitCode !== null || child.signalCode !== null) return;
719
- const cleanupTimeoutMs = options.desktopCleanupTimeoutMs ?? 2_000;
987
+ const cleanupTimeoutMs = options.desktopCleanupTimeoutMs ?? 10_000;
720
988
  const waitForExit = new Promise((resolve, reject) => {
721
989
  let timer;
722
990
  let settled = false;
@@ -762,6 +1030,26 @@ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
762
1030
  };
763
1031
  }
764
1032
 
1033
+ // `xvfb-run` can replace a successful child's status with its cleanup failure. Use the
1034
+ // repository wrapper in headless Linux and preserve the child's own status.
1035
+ function privateDisplayCommand(executable, args) {
1036
+ if (process.platform !== 'linux' || process.env.DISPLAY !== undefined) {
1037
+ return { args, command: executable };
1038
+ }
1039
+ const wrapper = join(scriptDirectory, 'xvfb.sh');
1040
+ if (!existsSync(wrapper)) {
1041
+ throw new ProductionEvidenceError(
1042
+ 'TN_PROD_XVFB_WRAPPER_UNAVAILABLE',
1043
+ `Headless Linux profiling needs the packaged display wrapper '${wrapper}', which is missing.`,
1044
+ );
1045
+ }
1046
+ return { args: [wrapper, executable, ...args], command: '/bin/sh' };
1047
+ }
1048
+
1049
+ export function nativeLaunchesExternalBundle(artifactPath, options) {
1050
+ return options.prebuiltArtifact !== undefined && artifactPath === options.prebuiltArtifact;
1051
+ }
1052
+
765
1053
  function spawnNative(artifactPath, project, options, mailboxRoot) {
766
1054
  const bundle = join(project, '.threenative/build/game.js');
767
1055
  // A packaged desktop artifact embeds the instrumented game entry under its own module root, and
@@ -769,16 +1057,15 @@ function spawnNative(artifactPath, project, options, mailboxRoot) {
769
1057
  // the external bundle never loads and the run reports TN_PLAYTEST_BRIDGE_MISSING at zero frames.
770
1058
  // Launch the embedded entry. A bare runtime supplied through `--prebuilt-artifact` carries no
771
1059
  // embedded entry and still needs the external bundle named on the command line.
772
- const launchesExternalBundle = options.prebuiltArtifact !== undefined;
1060
+ const launchesExternalBundle = nativeLaunchesExternalBundle(artifactPath, options);
773
1061
  const nativeArgs = [
774
1062
  ...(launchesExternalBundle ? ['run', bundle] : []),
775
1063
  '--width', String(options.renderSize.width),
776
1064
  '--height', String(options.renderSize.height),
777
1065
  '--headless',
778
1066
  ];
779
- const command = process.platform === 'linux' && process.env.DISPLAY === undefined ? 'xvfb-run' : artifactPath;
780
- const args = command === 'xvfb-run' ? ['-a', '-s', '-screen 0 1600x900x24', artifactPath, ...nativeArgs] : nativeArgs;
781
- return spawn(command, args, {
1067
+ const command = privateDisplayCommand(artifactPath, nativeArgs);
1068
+ return spawn(command.command, command.args, {
782
1069
  cwd: project,
783
1070
  detached: process.platform !== 'win32',
784
1071
  env: { ...process.env, TN_PLAYTEST_MAILBOX_ROOT: mailboxRoot, SDL_VIDEODRIVER: process.platform === 'linux' ? 'x11' : process.env.SDL_VIDEODRIVER },
@@ -794,35 +1081,53 @@ export async function installNativeProfileEntry(project, target, options) {
794
1081
  const mailbox = target === 'desktop'
795
1082
  ? `globalThis.TN_PLAYTEST_MAILBOX = ${JSON.stringify({ request: join(mailboxRoot, 'tn-playtest-request.json'), response: join(mailboxRoot, 'tn-playtest-response.json') })};\n`
796
1083
  : '';
797
- const source = `import "./profile-native-profile.js";\nimport game from "./game.js";\n${nativeFrameInstrumentation(options.control, warmupFramesFor(options), true)}\n${mailbox}export default game;\n`;
1084
+ const source = `import "./profile-native-profile.js";\nimport game from "./game.js";\n${nativeFrameInstrumentation(options.control, warmupFramesFor(options), paceTicksFor(options), options.liveClock)}\n${mailbox}export default game;\n`;
798
1085
  await writeFile(profileMarkerPath, profileMarker);
799
1086
  await writeFile(entryPath, source);
800
- await setNativeProfileEntry(project, 'src/profile-native-entry.ts', target, options.renderSize);
1087
+ await setNativeProfileEntry(project, 'src/profile-native-entry.ts', options.renderSize);
1088
+ if (target === 'desktop') await pinThreejsDesktopHost(project);
1089
+ }
1090
+
1091
+ /**
1092
+ * A desktop profile launches the Three.js host's packaged executable (`mystral`), but a config that
1093
+ * sets no `engine` now builds a directory around the V8 engine player. Name the override in the
1094
+ * staged copy, once, and leave an `engine` the game declares as authored.
1095
+ */
1096
+ export async function pinThreejsDesktopHost(project) {
1097
+ const configPath = join(project, 'threenative.config.ts');
1098
+ const config = await readFile(configPath, 'utf8').catch(() => undefined);
1099
+ if (config === undefined || /^\s*["']?engine["']?\s*:/mu.test(config)) return;
1100
+ const opening = /(?:=|export default)\s*\{/u;
1101
+ if (!opening.test(config)) {
1102
+ throw new ProductionEvidenceError('TN_PROD_ENGINE_PIN_FAILED', `${configPath} has no config object to pin engine: "threejs" into.`);
1103
+ }
1104
+ await writeFile(configPath, config.replace(opening, '$&\n engine: "threejs",'));
801
1105
  }
802
1106
 
803
- export async function setNativeProfileEntry(project, entry, target, renderSize = undefined) {
1107
+ export async function setNativeProfileEntry(project, entry, renderSize = undefined) {
804
1108
  const configPath = join(project, 'threenative.config.ts');
805
1109
  const packagePath = join(project, 'package.json');
806
1110
  const config = await readFile(configPath, 'utf8').catch(() => undefined);
807
1111
  if (config !== undefined) {
808
- const withEntry = config.replace(
809
- /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu,
810
- `$1"${entry}"$2`,
811
- );
1112
+ // Whether the config declares the field at all is a different question from whether its value
1113
+ // changes, and only the first one decides where the entry lives. Reading it off `withEntry !==
1114
+ // config` conflates the two: a config already naming this entry left the value unchanged, fell
1115
+ // through to the package.json branch below, and declared `nativeEntry` in *both* files — which
1116
+ // the next `threenative build --target desktop` refuses with `TN_CONFIG_CONFLICT`. A project
1117
+ // profiled once could therefore never be profiled a second time.
1118
+ const entryPattern = /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu;
1119
+ const declaresEntry = entryPattern.test(config);
1120
+ const withEntry = config.replace(entryPattern, `$1"${entry}"$2`);
812
1121
  // The packaged desktop artifact carries the game's config embedded, and the native host reads
813
1122
  // its window size from there before any command-line flag, so the profiled surface is only the
814
1123
  // requested render size when the config states it.
815
1124
  const sized = renderSize === undefined ? withEntry : applyWindowSize(withEntry, renderSize);
816
- const rendered = target === 'desktop'
817
- ? sized.replace(
818
- /(\bui\s*:\s*\{\s*renderer\s*:\s*)["'][^"']*["']/mu,
819
- `$1"native"`,
820
- )
821
- : sized;
822
- if (rendered !== config) {
823
- await writeFile(configPath, rendered);
1125
+ if (sized !== config) {
1126
+ await writeFile(configPath, sized);
824
1127
  }
825
- if (withEntry !== config) {
1128
+ if (declaresEntry) {
1129
+ // One declaration, in the file the config layer resolves first. Dropping a stale key is also
1130
+ // how a project already corrupted by the old fall-through is repaired on its next run.
826
1131
  const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
827
1132
  if (packageJson.threenative?.nativeEntry !== undefined) {
828
1133
  delete packageJson.threenative.nativeEntry;
@@ -875,6 +1180,21 @@ const tnProductionReadPerformance = () => {
875
1180
  `;
876
1181
  }
877
1182
 
1183
+ /**
1184
+ * Ask the game for the wall clock, so the profile measures a game playing.
1185
+ *
1186
+ * A profile run is a playtest run, and a playtest run freezes the live clock: the runner asks the
1187
+ * bridge for fixed steps and the loop simulates nothing else, so the frames the host presents while
1188
+ * a burst of ticks is delivered repeat one standing state. The browser reported ~60 fps of a
1189
+ * platformer whose movement was advancing in ten-tick jumps, and the frame samples the judge reads
1190
+ * described that, not the game. `__THREENATIVE_PLAYTEST_CLOCK__` is the framework's own switch for
1191
+ * the opposite, and it has to be set before the bundle evaluates — which is what the instrumentation
1192
+ * this rides in is.
1193
+ */
1194
+ export function productionClockRequest(liveClock = false) {
1195
+ return liveClock === true ? 'globalThis.__THREENATIVE_PLAYTEST_CLOCK__ = "wall-clock";\n' : '';
1196
+ }
1197
+
878
1198
  /**
879
1199
  * Pace the fixed step to wall time so a synthetic workload's tick budget is the seconds it names.
880
1200
  *
@@ -884,6 +1204,14 @@ const tnProductionReadPerformance = () => {
884
1204
  * or measure, and the warmup boundary is never reached. Wrapping `advance` to wait one display
885
1205
  * interval per tick lets the host's own loop run during the wait, so the frames exist to be
886
1206
  * measured.
1207
+ *
1208
+ * The same wrapper arms on the live clock, and it is idempotent there rather than a second wait: a
1209
+ * wall-clock `advance` spends the span its ticks name before the wrapper reads its own deadline, so
1210
+ * the remainder is zero or less and no wall-clock run is slowed. It is also the only thing that
1211
+ * makes the host present the frames on any host whose `advance` did not wait them, which is what a
1212
+ * short measured window is. Reading the live clock as "already paced, so skip the pacer" was the
1213
+ * defect: the native host consumed the frame-count workload at its own speed, and 60 requested
1214
+ * seconds published as a 1.5 s window.
887
1215
  */
888
1216
  export function productionExecutionHold(paceTicks = false) {
889
1217
  return `
@@ -910,7 +1238,46 @@ tnProductionInstallPace();
910
1238
  `;
911
1239
  }
912
1240
 
913
- export function nativeFrameInstrumentation(control, warmupFrames = 0, paceTicks = false) {
1241
+ /**
1242
+ * The warmup boundary both arms share: the frame count *and* the wall time those frames were asked
1243
+ * to cover.
1244
+ *
1245
+ * A frame count only names a duration on a host that presents at 60 Hz, and neither host is one. The
1246
+ * native host ran 120 frames — the whole `--warmup 2` budget — in 1.18 s of a requested 2 s while it
1247
+ * booted at 100-170 Hz, so the measured window started at the last first-use pipeline compile and
1248
+ * published boot as a frame rate: native 26.29 mean fps, 306.04 ms p95, beside
1249
+ * `execution.warmupSeconds: 2`. The frame bound stays, because a host *slower* than 60 Hz needs it
1250
+ * more than a host that runs ahead, and the two are the same number on a 60 Hz browser.
1251
+ */
1252
+ function productionWarmupBoundary(warmupFrames = 0) {
1253
+ return `
1254
+ const tnProductionWarmupMs = ${Math.max(0, Math.floor(warmupFrames)) / 60 * 1_000};
1255
+ let tnProductionStartedAtMs;
1256
+ const tnProductionInWarmup = (frameIndex, now) => {
1257
+ tnProductionStartedAtMs ??= now;
1258
+ return frameIndex < tnProductionWarmupFrames || now - tnProductionStartedAtMs < tnProductionWarmupMs;
1259
+ };
1260
+ `;
1261
+ }
1262
+
1263
+ /**
1264
+ * The measurement reset, on the transition rather than on the frame count the boundary also checks.
1265
+ *
1266
+ * The frame count is only one of the two bounds, and a host that presents slower than 60 Hz reaches
1267
+ * the wall time later. Clearing the carry on the frame count left the last warmup frame still holding
1268
+ * the previous frame's clock, so the first measured frame reported the interval that spanned the
1269
+ * boundary — the crossing stall, or the whole warmup tail — as gameplay. Both arms warm up
1270
+ * monotonically, so the transition happens once and the flag keeps it to once.
1271
+ */
1272
+ function tnProductionMeasurementStart() {
1273
+ return `if (!inWarmup && !tnProductionMeasuring) {
1274
+ tnProductionMeasuring = true;
1275
+ tnProductionPreviousFrame = undefined;
1276
+ tnProductionSamples = [];
1277
+ }`;
1278
+ }
1279
+
1280
+ export function nativeFrameInstrumentation(control, warmupFrames = 0, paceTicks = false, liveClock = false) {
914
1281
  return `
915
1282
  const tnProductionControl = ${JSON.stringify(control ?? '')};
916
1283
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
@@ -918,27 +1285,28 @@ const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
918
1285
  if (typeof tnProductionRequestAnimationFrame !== "function") {
919
1286
  throw new Error("TN_PROD_NATIVE_RAF_UNAVAILABLE: native host did not provide requestAnimationFrame.");
920
1287
  }
1288
+ ${productionClockRequest(liveClock)}
921
1289
  let tnProductionFirstFrame = true;
922
1290
  let tnProductionFrameIndex = 0;
923
1291
  let tnProductionPreviousFrame;
1292
+ let tnProductionPresentation;
924
1293
  let tnProductionSamples = [];
1294
+ let tnProductionMeasuring = false;
925
1295
  let tnProductionSlowFramesRemaining = ${SLOW_FRAME_COUNT};
926
1296
  const tnProductionBusyWait = (milliseconds) => {
927
1297
  const deadline = performance.now() + milliseconds;
928
1298
  while (performance.now() < deadline) {}
929
1299
  };
1300
+ ${productionWarmupBoundary(warmupFrames)}
930
1301
  ${productionPerformanceReader()}
931
1302
  ${productionExecutionHold(paceTicks)}
932
1303
  globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
933
1304
  tnProductionInstallPace();
934
1305
  const frameIndex = tnProductionFrameIndex++;
935
- const inWarmup = frameIndex < tnProductionWarmupFrames;
936
- if (frameIndex === tnProductionWarmupFrames) {
937
- tnProductionPreviousFrame = undefined;
938
- tnProductionSamples = [];
939
- }
940
1306
  if (tnProductionFirstFrame && tnProductionControl === "slow-startup") tnProductionBusyWait(${SLOW_STARTUP_DELAY_MS});
941
1307
  const now = performance.now();
1308
+ const inWarmup = tnProductionInWarmup(frameIndex, now);
1309
+ ${tnProductionMeasurementStart()}
942
1310
  const frameMs = inWarmup || tnProductionPreviousFrame === undefined ? undefined : now - tnProductionPreviousFrame;
943
1311
  tnProductionPreviousFrame = now;
944
1312
  callback(timestamp);
@@ -967,48 +1335,58 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
967
1335
  `;
968
1336
  }
969
1337
 
970
- export function webFrameInstrumentation(markerUrl, control, warmupFrames = 0) {
1338
+ /**
1339
+ * The web arm reports over the console, the same transport the native arm already uses, so one
1340
+ * parser and one clock serve both. It used to POST to a marker server, which the playtest's own
1341
+ * `noNetworkErrors` policy then failed the run for: Chromium reports every in-flight `fetch` as
1342
+ * `net::ERR_ABORTED` when the runner tears the page down, so the profile failed its own runs for
1343
+ * its own instrumentation. The judge still owns `--judge-marker-url`; only the game's samples moved.
1344
+ */
1345
+ export function webFrameInstrumentation(control, warmupFrames = 0, paceTicks = false, liveClock = false) {
971
1346
  return `
972
1347
  const tnProductionControl = ${JSON.stringify(control ?? '')};
973
1348
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
974
- const tnProductionMarkerUrl = ${JSON.stringify(markerUrl)};
975
1349
  const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
976
1350
  if (typeof tnProductionRequestAnimationFrame !== "function") {
977
1351
  throw new Error("TN_PROD_WEB_RAF_UNAVAILABLE: browser host did not provide requestAnimationFrame.");
978
1352
  }
1353
+ ${productionClockRequest(liveClock)}
979
1354
  let tnProductionFirstFrame = true;
980
1355
  let tnProductionFrameIndex = 0;
981
1356
  let tnProductionPreviousFrame;
1357
+ let tnProductionPresentation;
982
1358
  let tnProductionSamples = [];
1359
+ let tnProductionMeasuring = false;
983
1360
  let tnProductionSlowFramesRemaining = ${SLOW_FRAME_COUNT};
984
1361
  const tnProductionBusyWait = (milliseconds) => {
985
1362
  const deadline = performance.now() + milliseconds;
986
1363
  while (performance.now() < deadline) {}
987
1364
  };
988
- const tnProductionPost = (payload) => {
989
- void fetch(tnProductionMarkerUrl, {
990
- body: JSON.stringify(payload),
991
- keepalive: true,
992
- method: "POST",
993
- mode: "no-cors",
994
- }).catch(() => undefined);
995
- };
1365
+ ${productionWarmupBoundary(warmupFrames)}
996
1366
  ${productionPerformanceReader()}
1367
+ ${productionExecutionHold(paceTicks)}
997
1368
  globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
1369
+ tnProductionInstallPace();
1370
+ // One browser presentation can invoke every callback registered for it with the same
1371
+ // DOMHighResTimeStamp. Counting each callback would push a zero-length interval and make meanFps
1372
+ // indeterminate, so only the first callback for a presentation is the frame; the rest still run
1373
+ // their callback unchanged.
1374
+ if (Number.isFinite(timestamp) && timestamp === tnProductionPresentation) {
1375
+ callback(timestamp);
1376
+ return;
1377
+ }
1378
+ tnProductionPresentation = Number.isFinite(timestamp) ? timestamp : undefined;
998
1379
  const frameIndex = tnProductionFrameIndex++;
999
- const inWarmup = frameIndex < tnProductionWarmupFrames;
1000
- if (frameIndex === tnProductionWarmupFrames) {
1001
- tnProductionPreviousFrame = undefined;
1002
- tnProductionSamples = [];
1003
- }
1004
1380
  if (tnProductionFirstFrame && tnProductionControl === "slow-startup") tnProductionBusyWait(${SLOW_STARTUP_DELAY_MS});
1005
1381
  const now = performance.now();
1382
+ const inWarmup = tnProductionInWarmup(frameIndex, now);
1383
+ ${tnProductionMeasurementStart()}
1006
1384
  const frameMs = inWarmup || tnProductionPreviousFrame === undefined ? undefined : now - tnProductionPreviousFrame;
1007
1385
  tnProductionPreviousFrame = now;
1008
1386
  callback(timestamp);
1009
1387
  if (tnProductionFirstFrame) {
1010
1388
  tnProductionFirstFrame = false;
1011
- tnProductionPost({ kind: "first-frame" });
1389
+ console.log("TN_PROD_FIRST_NONBLANK_FRAME:" + Date.now());
1012
1390
  }
1013
1391
  if (!inWarmup && frameMs !== undefined) {
1014
1392
  tnProductionSamples.push({
@@ -1019,7 +1397,7 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
1019
1397
  frameMs,
1020
1398
  });
1021
1399
  if (tnProductionSamples.length >= ${FRAME_SAMPLE_BATCH_SIZE}) {
1022
- tnProductionPost({ kind: "samples", samples: tnProductionSamples });
1400
+ console.log("TN_PROD_FRAME_SAMPLES:" + JSON.stringify(tnProductionSamples));
1023
1401
  tnProductionSamples = [];
1024
1402
  }
1025
1403
  }
@@ -1031,16 +1409,17 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
1031
1409
  `;
1032
1410
  }
1033
1411
 
1034
- async function installWebProfileEntry(project, markerUrl, control, warmupFrames = 0) {
1412
+ async function installWebProfileEntry(project, control, warmupFrames = 0, paceTicks = false, liveClock = false) {
1035
1413
  const markerPath = join(project, 'src/profile-production-marker.ts');
1036
1414
  const mainPath = join(project, 'src/main.ts');
1037
1415
  const markerImport = 'import "./profile-production-marker.js";';
1038
1416
  const main = await readFile(mainPath, 'utf8');
1039
- const source = webFrameInstrumentation(markerUrl, control, warmupFrames);
1417
+ const source = webFrameInstrumentation(control, warmupFrames, paceTicks, liveClock);
1040
1418
  await writeFile(markerPath, source);
1041
1419
  if (!main.includes(markerImport)) await writeFile(mainPath, `${markerImport}\n${main}`);
1042
1420
  }
1043
1421
 
1422
+
1044
1423
  async function createFrameMarkerServer(port = 0) {
1045
1424
  const events = [];
1046
1425
  const waiters = [];
@@ -1096,7 +1475,7 @@ function markerEvents(events) {
1096
1475
  return { firstFrame, samples };
1097
1476
  }
1098
1477
 
1099
- async function normalizeRun(
1478
+ export async function normalizeRun(
1100
1479
  result,
1101
1480
  artifactDirectory,
1102
1481
  kind,
@@ -1106,14 +1485,19 @@ async function normalizeRun(
1106
1485
  ) {
1107
1486
  const reportSeries = report?.observations?.visual?.runtimeDiagnosticsSeries;
1108
1487
  const performanceSeries = report?.observations?.performanceSeries;
1109
- const consoleSeries = frameSeriesFromReport(report);
1110
- const series = [collectedSeries, reportSeries, performanceSeries, consoleSeries]
1111
- .find((candidate) => Array.isArray(candidate) && candidate.length > 0);
1488
+ const consoleSeries = frameSeriesFromReport(report, kind);
1489
+ const series = kind === 'desktop'
1490
+ ? consoleSeries
1491
+ : [collectedSeries, reportSeries, performanceSeries, consoleSeries]
1492
+ .find((candidate) => Array.isArray(candidate) && candidate.length > 0);
1112
1493
  const screenshotPath = join(artifactDirectory, 'after.png');
1113
1494
  const screenshot = await nonBlankPng(screenshotPath) ? await readFile(screenshotPath) : undefined;
1114
1495
  return {
1115
1496
  elapsedMs: result.durationMs,
1116
1497
  ...(Number.isFinite(firstFrameMs) ? { firstFrameMs } : {}),
1498
+ // A child that exits without a parseable report has no report and usually no screenshot, so
1499
+ // without this the whole run vanishes from the evidence and the failure is an absence.
1500
+ ...(report === undefined ? { failure: missingReportFailure(result) } : {}),
1117
1501
  kind,
1118
1502
  report: report === undefined ? undefined : safeReport(report),
1119
1503
  screenshot,
@@ -1122,6 +1506,16 @@ async function normalizeRun(
1122
1506
  };
1123
1507
  }
1124
1508
 
1509
+ function missingReportFailure(result) {
1510
+ return sanitizeReportValue({
1511
+ code: 'TN_PROD_RUN_REPORT_MISSING',
1512
+ message: `The child run exited without a parseable report${failureSuffix(result).slice(-4_000)}`,
1513
+ severity: 'error',
1514
+ status: result.status,
1515
+ timedOut: result.timedOut === true,
1516
+ });
1517
+ }
1518
+
1125
1519
  const REPORT_REDACTION_MESSAGE = 'TN_PROD_REDACTION: unsafe native report detail withheld.';
1126
1520
 
1127
1521
  export function safeReport(report) {
@@ -1195,9 +1589,26 @@ function firstFrameMsFromReport(report, startedAt) {
1195
1589
  return elapsed >= 0 ? elapsed : undefined;
1196
1590
  }
1197
1591
 
1198
- function frameSeriesFromReport(report) {
1592
+ /**
1593
+ * The desktop host takes its `after.png` inside its own frame loop, so the readback runs where a
1594
+ * frame runs and the frame that spans it reports the readback as its own `frameMs`. Both clean-HEAD
1595
+ * native collections at `f645e65c8` carry a 358.26 ms and a 312.72 ms gap in the batch logged after
1596
+ * the host's capture line, beside a `TN_SLOW_PHASE pollEvents` at 358.19 and 312.79 ms. The capture
1597
+ * line and the sample batches are both `std::cout` in that one process, so console order is write
1598
+ * order and the line is an exact boundary rather than a threshold: every batch logged at or after it
1599
+ * is dropped whole, because such a batch straddles the capture and dropping one is the direction
1600
+ * that cannot read the readback as gameplay. The capture is still requested and its artifact still
1601
+ * retained — this bounds the measured window, it does not remove the evidence.
1602
+ */
1603
+ function frameSeriesFromReport(report, kind) {
1604
+ const lines = reportConsoleLines(report);
1605
+ // No capture line means no boundary, so a desktop report keeps nothing and fails closed rather than
1606
+ // publishing a window this parser cannot bound; every other arm keeps its whole console.
1607
+ const capture = kind === 'desktop'
1608
+ ? lines.findIndex((line) => line.includes('[Screenshot] First 16 bytes'))
1609
+ : lines.length;
1199
1610
  const series = [];
1200
- for (const line of reportConsoleLines(report)) {
1611
+ for (const line of lines.slice(0, Math.max(capture, 0))) {
1201
1612
  const prefix = 'TN_PROD_FRAME_SAMPLES:';
1202
1613
  const offset = line.indexOf(prefix);
1203
1614
  if (offset === -1) continue;
@@ -1210,7 +1621,7 @@ function frameSeriesFromReport(report) {
1210
1621
  return series.length === 0 ? undefined : series;
1211
1622
  }
1212
1623
 
1213
- export function assembleEvidence({ context, native, options, performanceBounds, project, runId, startedAt, web }) {
1624
+ export function assembleEvidence({ context, native, options, performanceBounds, project, resolutionScaleSetting, runId, startedAt, web }) {
1214
1625
  const arms = [web, native].filter((arm) => arm !== undefined);
1215
1626
  const regression = options.profile === REGRESSION_PROFILE;
1216
1627
  const expectedRuns = collectionLaunchPlan(options).filter((entry) => entry === 'steady').length;
@@ -1227,10 +1638,12 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1227
1638
  for (const [index, run] of arm.runs.entries()) {
1228
1639
  if (run.screenshot !== undefined) rawArtifacts.push({ content: run.screenshot, label: `production-render-${arm.kind}-${index + 1}` });
1229
1640
  if (run.report !== undefined) rawArtifacts.push({ content: JSON.stringify(run.report), label: `production-playtest-${arm.kind}-${index + 1}` });
1641
+ if (run.failure !== undefined) rawArtifacts.push({ content: JSON.stringify(run.failure), label: `production-run-failure-${arm.kind}-${index + 1}` });
1230
1642
  }
1231
1643
  for (const [index, startup] of arm.startups.entries()) {
1232
1644
  if (startup.screenshot !== undefined) rawArtifacts.push({ content: startup.screenshot, label: `production-first-frame-${arm.kind}-${index + 1}` });
1233
1645
  if (startup.report !== undefined) rawArtifacts.push({ content: JSON.stringify(startup.report), label: `production-startup-${arm.kind}-${index + 1}` });
1646
+ if (startup.failure !== undefined) rawArtifacts.push({ content: JSON.stringify(startup.failure), label: `production-startup-failure-${arm.kind}-${index + 1}` });
1234
1647
  }
1235
1648
  }
1236
1649
  const metricsByArm = new Map(arms.map((arm) => [arm.kind, aggregateMetrics(arm.runs, arm.startups, warmupFramesFor(options))]));
@@ -1265,7 +1678,7 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1265
1678
  }
1266
1679
  const artifactHashes = arms.map(({ artifactSha, bundleSha }) => `${artifactSha}:${bundleSha ?? artifactSha}`);
1267
1680
  const target = options.target;
1268
- const identity = identityFor(options, web, native, artifactHashes);
1681
+ const identity = identityFor(options, web, native, artifactHashes, resolutionScaleSetting);
1269
1682
  const evidence = {
1270
1683
  artifact: {
1271
1684
  applicationClass: target === 'desktop-pair' ? 'platformer-desktop-pair' : arms[0]?.applicationClass ?? 'platformer-production',
@@ -1274,9 +1687,14 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1274
1687
  },
1275
1688
  artifacts: [],
1276
1689
  budget: {
1277
- maxP99FrameMs: 33,
1278
- maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1279
- minMeanFps: target.includes('physical') ? 59.4 : 60,
1690
+ // The scaffolded platformer is judged by the default steady-state budget. An existing project
1691
+ // is judged only by the bounds its own scenario authors: a known ~40 fps game must not fail
1692
+ // before A/B on a default it never claimed.
1693
+ ...(options.project === undefined ? {
1694
+ maxP99FrameMs: 33,
1695
+ maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1696
+ minMeanFps: target.includes('physical') ? 59.4 : 60,
1697
+ } : {}),
1280
1698
  ...(regression ? {
1281
1699
  minDurationSeconds: REGRESSION_COLLECTION_PROFILE.durationSeconds,
1282
1700
  minFrameSamples: REGRESSION_COLLECTION_PROFILE.minFrameSamples,
@@ -1287,6 +1705,9 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1287
1705
  codes: [...new Set(codes)],
1288
1706
  evidenceClasses: ['production'],
1289
1707
  execution: {
1708
+ // Which clock the arms ran on, published because the two are not the same measurement: on a
1709
+ // frozen clock every presented frame repeats a standing state, so its rate is not a frame rate.
1710
+ clock: options.liveClock === true ? 'wall-clock' : 'fixed-step',
1290
1711
  coldStarts: options.coldStarts,
1291
1712
  ...(options.control === undefined ? {} : { control: options.control }),
1292
1713
  deviceSelected: options.device !== undefined,
@@ -1308,6 +1729,7 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1308
1729
  dirty: context.sourceState.dirty,
1309
1730
  ...(context.sourceState.diffSha === undefined ? {} : { diffSha: context.sourceState.diffSha }),
1310
1731
  sha: context.sourceSha,
1732
+ ...(context.sourceState.rawStatus === undefined ? {} : { snapshot: { rawStatus: context.sourceState.rawStatus, normalizedTrackedFiles: context.sourceState.normalizedTrackedFiles } }),
1311
1733
  },
1312
1734
  target,
1313
1735
  timestamps: { endedAt: new Date().toISOString(), startedAt },
@@ -1446,7 +1868,9 @@ export function postWarmupFrameSamples(samples, warmupFrames = 0) {
1446
1868
 
1447
1869
  export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1448
1870
  const intervals = [];
1449
- const frameIntervalsMs = [];
1871
+ const callbackIntervalsMs = [];
1872
+ const presentedIntervalsMs = [];
1873
+ const presentedStampsMs = [];
1450
1874
  const clockSamplesMs = [];
1451
1875
  const presentationSamplesMs = [];
1452
1876
  const runWindows = [];
@@ -1456,28 +1880,25 @@ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1456
1880
  .map(({ firstFrameMs }) => firstFrameMs);
1457
1881
  let timestampMs = 0;
1458
1882
  let sequence = 1;
1459
- let sampleCount = 0;
1460
- let hitchCount = 0;
1461
- let worstFrameMs;
1883
+ let callbackCount = 0;
1884
+ let presentedElapsedMs = 0;
1462
1885
  let missingClock = false;
1463
1886
  let missingPresentationClock = false;
1887
+ let unmeasurablePresentation = false;
1464
1888
  for (const run of runs) {
1465
1889
  let clockOrigin;
1466
1890
  let presentationOrigin;
1891
+ let lastPresentedMs;
1467
1892
  const postWarmupSamples = postWarmupFrameSamples(run.series ?? [], warmupFrames);
1468
1893
  let runDurationMs = 0;
1469
1894
  let runSampleCount = 0;
1470
1895
  for (const sample of postWarmupSamples) {
1471
1896
  if (typeof sample?.frameMs !== 'number') {
1472
- frameIntervalsMs.push(sample?.frameMs);
1897
+ callbackIntervalsMs.push(sample?.frameMs);
1473
1898
  continue;
1474
1899
  }
1475
- frameIntervalsMs.push(sample.frameMs);
1476
- sampleCount += 1;
1477
- runSampleCount += 1;
1478
- runDurationMs += sample.frameMs;
1479
- if (sample.frameMs > 33.3) hitchCount += 1;
1480
- worstFrameMs = worstFrameMs === undefined ? sample.frameMs : Math.max(worstFrameMs, sample.frameMs);
1900
+ callbackIntervalsMs.push(sample.frameMs);
1901
+ callbackCount += 1;
1481
1902
  if (Number.isFinite(sample.clockMs)) {
1482
1903
  clockOrigin ??= sample.clockMs;
1483
1904
  clockSamplesMs.push(timestampMs + sample.clockMs - clockOrigin);
@@ -1485,10 +1906,34 @@ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1485
1906
  missingClock = true;
1486
1907
  }
1487
1908
  if (Number.isFinite(sample.presentationMs)) {
1909
+ // The frame interval the budget is about is the gap between presented frames, and the rAF
1910
+ // timestamp is the frame. Both arms run three rAF callbacks per presented frame — the
1911
+ // engine loop, the UI hit-test pump and this instrumentation each register one — so a
1912
+ // `performance.now()` callback delta measures how the host spread its callbacks inside a
1913
+ // fixed display period: at its 95th percentile it is the idle remainder of that period, and
1914
+ // the arm that spends less per callback is the one that reads worse. The presented series
1915
+ // therefore advances only when the presentation stamp changes, and one frame's callbacks
1916
+ // collapse into the single interval they belong to. Every quantity the frame budget counts —
1917
+ // the per-second floor, the window's sample count, the worst frame and the hitch count —
1918
+ // counts this series, because a callback count reads three frames for every frame presented.
1919
+ if (lastPresentedMs !== undefined && sample.presentationMs !== lastPresentedMs) {
1920
+ const presentedDeltaMs = sample.presentationMs - lastPresentedMs;
1921
+ if (presentedDeltaMs > 0) {
1922
+ presentedIntervalsMs.push(presentedDeltaMs);
1923
+ runSampleCount += 1;
1924
+ runDurationMs += presentedDeltaMs;
1925
+ presentedElapsedMs += presentedDeltaMs;
1926
+ presentedStampsMs.push(presentedElapsedMs);
1927
+ } else {
1928
+ unmeasurablePresentation = true;
1929
+ }
1930
+ }
1931
+ lastPresentedMs = sample.presentationMs;
1488
1932
  presentationOrigin ??= sample.presentationMs;
1489
1933
  presentationSamplesMs.push(timestampMs + sample.presentationMs - presentationOrigin);
1490
1934
  } else {
1491
1935
  missingPresentationClock = true;
1936
+ unmeasurablePresentation = true;
1492
1937
  }
1493
1938
  if (sample.phases !== undefined && typeof sample.phases === 'object' && sample.phases !== null) {
1494
1939
  for (const [phase, value] of Object.entries(sample.phases)) {
@@ -1512,31 +1957,49 @@ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1512
1957
  }
1513
1958
  runWindows.push({ durationSeconds: runDurationMs / 1_000, sampleCount: runSampleCount });
1514
1959
  }
1960
+ // A sample the presentation clock could not place has no place in a cadence series, and a partial
1961
+ // one would publish a percentile of the frames that happened to survive. The series stays
1962
+ // unmeasured, which fails the timing budget and blocks a pair rather than judging a subset. The
1963
+ // windows go with it: a count of presented frames and a duration measured from the same voided
1964
+ // series are the same partial subset under two names.
1965
+ if (unmeasurablePresentation) presentedIntervalsMs.length = 0;
1515
1966
  const phaseP95ByName = Object.fromEntries(
1516
1967
  Object.entries(phaseSamples).map(([phase, samples]) => [phase, nearestRank(samples, 0.95)]),
1517
1968
  );
1969
+ const presentedFrames = presentedIntervalsMs.length;
1970
+ const presentedHitchCount = presentedIntervalsMs.filter((value) => value > 33.3).length;
1518
1971
  return {
1519
1972
  ...(clockSamplesMs.length === 0 ? {} : { clockSamplesMs }),
1520
- ...(sampleCount === 0 ? {} : { clockSource: missingClock ? 'missing' : 'monotonic-performance' }),
1521
- ...(frameIntervalsMs.length === 0 ? {} : { frameIntervalsMs }),
1522
- ...(hitchCount === 0 ? { hitchCount: 0 } : { hitchCount }),
1973
+ ...(callbackCount === 0 ? {} : { clockSource: missingClock ? 'missing' : 'monotonic-performance' }),
1974
+ ...(presentedFrames === 0 ? {} : { frameIntervalsMs: presentedIntervalsMs }),
1523
1975
  ...(intervals.length === 0 ? {} : { intervals }),
1524
1976
  ...(Object.keys(phaseP95ByName).length === 0 ? {} : {
1525
1977
  phaseP95ByName,
1526
1978
  ...(phaseP95ByName.render === undefined ? {} : { phaseP95Ms: phaseP95ByName.render }),
1527
1979
  }),
1528
1980
  ...(presentationSamplesMs.length === 0 ? {} : { presentationSamplesMs }),
1529
- ...(runWindows.length === 0 ? {} : { runWindows }),
1530
- ...(sampleCount === 0 ? {} : { presentationClockSource: missingPresentationClock ? 'missing' : 'raf-presentation', sampleCount, worstFrameMs }),
1981
+ ...(runWindows.length === 0 || unmeasurablePresentation ? {} : { runWindows }),
1982
+ ...(callbackCount === 0 ? {} : { presentationClockSource: missingPresentationClock ? 'missing' : 'raf-presentation' }),
1531
1983
  ...(startupSamplesMs.length === 0 ? {} : { startupSamplesMs, startupMs: startupSamplesMs[0] }),
1532
1984
  ...(timestampMs === 0 ? {} : { durationSeconds: timestampMs / 1_000 }),
1533
1985
  ...(startupSamplesMs.length === 0 ? {} : { startupP95Ms: nearestRank(startupSamplesMs, 0.95) }),
1534
- ...(frameIntervalsMs.length === 0 ? {} : {
1535
- meanFps: meanFps(frameIntervalsMs),
1536
- p50FrameMs: nearestRank(frameIntervalsMs, 0.5),
1537
- p95FrameMs: nearestRank(frameIntervalsMs, 0.95),
1538
- p99FrameMs: nearestRank(frameIntervalsMs, 0.99),
1986
+ // The presented-frame quantities publish together or not at all: a sample count beside a
1987
+ // percentile of a different series is how a 3x callback count reads as a collected window.
1988
+ ...(presentedFrames === 0 ? {} : {
1989
+ hitchCount: presentedHitchCount,
1990
+ oneSecondFps: oneSecondFrameFloors(presentedStampsMs),
1991
+ sampleCount: presentedFrames,
1992
+ worstFrameMs: Math.max(...presentedIntervalsMs),
1539
1993
  }),
1994
+ ...(presentedFrames === 0 ? {} : {
1995
+ meanFps: meanFps(presentedIntervalsMs),
1996
+ p50FrameMs: nearestRank(presentedIntervalsMs, 0.5),
1997
+ p95FrameMs: nearestRank(presentedIntervalsMs, 0.95),
1998
+ p99FrameMs: nearestRank(presentedIntervalsMs, 0.99),
1999
+ }),
2000
+ ...(unmeasurableIntervalCount(callbackIntervalsMs) === 0
2001
+ ? {}
2002
+ : { unmeasurableCallbackIntervals: unmeasurableIntervalCount(callbackIntervalsMs) }),
1540
2003
  ...(intervals.some(({ drawCalls }) => drawCalls !== undefined) ? { drawCalls: Math.max(...intervals.flatMap(({ drawCalls }) => drawCalls === undefined ? [] : [drawCalls])) } : {}),
1541
2004
  ...(intervals.some(({ triangles }) => triangles !== undefined) ? { triangles: Math.max(...intervals.flatMap(({ triangles }) => triangles === undefined ? [] : [triangles])) } : {}),
1542
2005
  };
@@ -1555,13 +2018,37 @@ function pairMetrics(metrics) {
1555
2018
  };
1556
2019
  }
1557
2020
 
1558
- function identityFor(options, web, native, artifactHashes) {
2021
+ /**
2022
+ * The display a web frame rate was read from.
2023
+ *
2024
+ * `observations.hardwareIdentity` was the key this used to read and no producer has ever written it,
2025
+ * so every web artifact published an identity with no GPU in it. `webDisplay` is published from the
2026
+ * decision the runner itself made, and it is the field that separates this host's two web
2027
+ * collections: 33.97 fps on the private display, 163.45 fps on the session display.
2028
+ *
2029
+ * The playtest report retains its observed WebGPU adapter in the pipeline census. Repeated
2030
+ * workload runs must agree before one adapter can identify the whole rate sample.
2031
+ */
2032
+ export function webRateIdentity(web) {
2033
+ const display = web?.display;
2034
+ const adapters = web?.runs?.map((run) => run?.report?.observations?.pipelineCensus?.adapter?.identity);
2035
+ const adapter = adapters?.length > 0 && adapters.every((identity) => typeof identity === 'string' && identity !== 'unavailable' && identity === adapters[0])
2036
+ ? adapters[0]
2037
+ : undefined;
2038
+ return {
2039
+ ...(display === undefined ? {} : { webDisplay: display.kind === 'existing' ? `session:${display.display}` : display.kind }),
2040
+ ...(adapter === undefined ? {} : { webAdapter: adapter }),
2041
+ };
2042
+ }
2043
+
2044
+ function identityFor(options, web, native, artifactHashes, resolutionScaleSetting) {
1559
2045
  const common = {
1560
2046
  // Only observed hardware data may certify a promoted comparison. Missing fields remain absent.
1561
- ...(web?.runs[0]?.report?.observations?.hardwareIdentity ?? native?.runs[0]?.report?.observations?.hardwareIdentity ?? {}),
2047
+ ...webRateIdentity(web),
1562
2048
  workloadHash: web?.workloadHash ?? native?.workloadHash,
1563
2049
  renderHeight: options.renderSize.height,
1564
2050
  renderWidth: options.renderSize.width,
2051
+ ...(resolutionScaleSetting === undefined ? {} : { resolutionScaleSetting }),
1565
2052
  };
1566
2053
  if (options.target === 'desktop-pair') {
1567
2054
  return {
@@ -1652,7 +2139,10 @@ function profileCommand(options) {
1652
2139
  `--repetitions ${options.repetitions}`,
1653
2140
  ...(options.device === undefined ? [] : ['--device <selected>']),
1654
2141
  ...(options.hostedSoftware ? ['--hosted-software'] : []),
2142
+ ...(options.liveClock === true ? ['--live-clock'] : []),
1655
2143
  ...(options.prebuiltArtifact === undefined ? [] : ['--prebuilt-artifact <existing-build>']),
2144
+ ...(options.project === undefined ? [] : ['--project <existing-project>']),
2145
+ ...(options.scenario === undefined ? [] : ['--scenario <production-scenario>']),
1656
2146
  ].join(' ');
1657
2147
  }
1658
2148
 
@@ -1697,8 +2187,12 @@ async function createFixtureControlEvidence(options, context, runId) {
1697
2187
  }
1698
2188
 
1699
2189
  async function collectFixtureFrameSeries(control) {
2190
+ // The real producers stamp every sample with the rAF presentation timestamp, so the fixture that
2191
+ // stands in for them carries one too: the judge reads presented cadence, and a fixture without
2192
+ // presentation identity would now be (correctly) unmeasured rather than a passing control.
1700
2193
  const intervals = Array.from({ length: 120 }, (_, index) => ({
1701
2194
  frameMs: 16.5,
2195
+ presentationMs: index * 16.5,
1702
2196
  sequence: index + 1,
1703
2197
  timestampMs: index * 16.5,
1704
2198
  }));
@@ -1706,7 +2200,9 @@ async function collectFixtureFrameSeries(control) {
1706
2200
  for (const index of [intervals.length - 2, intervals.length - 1]) {
1707
2201
  const startedAt = performance.now();
1708
2202
  await new Promise((resolve) => setTimeout(resolve, SLOW_FRAME_DELAY_MS));
1709
- intervals[index].frameMs = Math.max(SLOW_FRAME_DELAY_MS, performance.now() - startedAt);
2203
+ const slowFrameMs = Math.max(SLOW_FRAME_DELAY_MS, performance.now() - startedAt);
2204
+ intervals[index].frameMs = slowFrameMs;
2205
+ intervals[index].presentationMs = intervals[index - 1].presentationMs + slowFrameMs;
1710
2206
  intervals[index].timestampMs = intervals[index - 1].timestampMs + intervals[index - 1].frameMs;
1711
2207
  }
1712
2208
  return intervals;
@@ -1793,15 +2289,52 @@ function applyNegativeControl(input, control) {
1793
2289
  return evidence;
1794
2290
  }
1795
2291
 
1796
- async function currentSourceState() {
2292
+ export async function currentSourceState(root = commandRoot, execute = execFileAsync) {
1797
2293
  try {
1798
- const [{ stdout: sha }, { stdout: status }, { stdout: diff }] = await Promise.all([
1799
- execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: commandRoot }),
1800
- execFileAsync('git', ['status', '--porcelain'], { cwd: commandRoot }),
1801
- execFileAsync('git', ['diff', 'HEAD'], { cwd: commandRoot }),
1802
- ]);
1803
- const dirty = status.trim().length > 0;
1804
- return { dirty, ...(dirty ? { diffSha: sha256(Buffer.from(diff)) } : {}), sha: sha.trim() };
2294
+ // Git can report an LF rewrite of a CRLF checkout as modified even though its
2295
+ // normalized candidate blob is identical. Preserve that raw status and prove
2296
+ // each byte identity explicitly; an empty diff alone never grants cleanliness.
2297
+ const git = async (...args) => (await execute('git', ['--literal-pathspecs', ...args], { cwd: root })).stdout;
2298
+ const sha = (await git('rev-parse', 'HEAD')).trim();
2299
+ const rawStatus = await git('status', '--porcelain=v1', '-z', '--untracked-files=all');
2300
+ const diff = await git('diff', '--no-ext-diff', '--no-textconv', 'HEAD');
2301
+ let dirty = rawStatus.length > 0;
2302
+ const normalizedTrackedFiles = [];
2303
+ const entries = rawStatus.split('\0').filter(Boolean);
2304
+ if (dirty && diff === '' && entries.every((entry) => entry.startsWith(' M '))) {
2305
+ for (const entry of entries) {
2306
+ const name = entry.slice(3);
2307
+ const file = join(root, name);
2308
+ if (!(await lstat(file)).isFile()) break;
2309
+ const head = /^(100644|100755) blob ([a-f0-9]{40,64})\t/u.exec(await git('ls-tree', '-z', 'HEAD', '--', name));
2310
+ const index = /^(100644|100755) ([a-f0-9]{40,64}) 0\t/u.exec(await git('ls-files', '--stage', '-z', '--', name));
2311
+ if (!head || !index || head[1] !== index[1] || head[2] !== index[2]) break;
2312
+ const raw = await readFile(file);
2313
+ const before = sha256(raw);
2314
+ const { stdout: headBytes } = await execute('git', ['cat-file', 'blob', head[2]], { cwd: root, encoding: 'buffer', maxBuffer: 16 * 1024 * 1024 });
2315
+ // Restrict the accepted transformation to line endings. Git clean filters
2316
+ // or working-tree encodings must never conceal executable byte changes.
2317
+ const lfBytes = Buffer.from(raw.toString('latin1').replace(/\r\n/gu, '\n'), 'latin1');
2318
+ if (!Buffer.isBuffer(headBytes) || !lfBytes.equals(headBytes)) break;
2319
+ const worktreeBlob = (await git('hash-object', `--path=${name}`, '--', name)).trim();
2320
+ if (worktreeBlob !== head[2] || sha256(await readFile(file)) !== before) break;
2321
+ normalizedTrackedFiles.push({ path: name, headBlob: head[2], worktreeBlob, rawSha256: before, normalization: 'crlf-to-lf-only' });
2322
+ }
2323
+ dirty = normalizedTrackedFiles.length !== entries.length;
2324
+ }
2325
+ // A changing tree or HEAD is never a coherent candidate snapshot.
2326
+ if ((await git('rev-parse', 'HEAD')).trim() !== sha ||
2327
+ (await git('status', '--porcelain=v1', '-z', '--untracked-files=all')) !== rawStatus) dirty = true;
2328
+ if (!dirty && normalizedTrackedFiles.length) {
2329
+ for (const proof of normalizedTrackedFiles) {
2330
+ const file = join(root, proof.path);
2331
+ if (!(await lstat(file)).isFile() || sha256(await readFile(file)) !== proof.rawSha256) dirty = true;
2332
+ }
2333
+ if ((await git('diff', '--no-ext-diff', '--no-textconv', 'HEAD')) !== '') dirty = true;
2334
+ if ((await git('rev-parse', 'HEAD')).trim() !== sha ||
2335
+ (await git('status', '--porcelain=v1', '-z', '--untracked-files=all')) !== rawStatus) dirty = true;
2336
+ }
2337
+ return { dirty, ...(dirty ? { diffSha: sha256(Buffer.from(diff)) } : {}), sha, rawStatus, normalizedTrackedFiles };
1805
2338
  } catch {
1806
2339
  return { dirty: true, diffSha: sha256(Buffer.from('source-state-unavailable')), sha: '0000000' };
1807
2340
  }
@@ -1830,12 +2363,32 @@ async function readOptionalArtifact(path) {
1830
2363
  }
1831
2364
  }
1832
2365
 
1833
- async function nativeArtifactPath(project, target) {
2366
+ export async function nativeArtifactPath(project, target) {
1834
2367
  const directory = join(project, 'dist-native');
1835
- const entries = await readdir(directory);
1836
- const candidate = entries.find((entry) => target === 'ios' ? entry.endsWith('.app') : target === 'android' ? entry.endsWith('.apk') : true);
2368
+ const entries = (await readdir(directory, { withFileTypes: true }))
2369
+ .slice()
2370
+ .sort((left, right) => left.name.localeCompare(right.name));
2371
+ const candidate = target === 'ios'
2372
+ ? entries.find((entry) => entry.isDirectory() && entry.name.endsWith('.app'))
2373
+ : target === 'android'
2374
+ ? entries.find((entry) => entry.isFile() && entry.name.endsWith('.apk'))
2375
+ : await desktopExecutableEntry(directory, entries);
1837
2376
  if (candidate === undefined) throw new ProductionEvidenceError('TN_PROD_NATIVE_ARTIFACT_MISSING', `The scaffolded ${target} build produced no native artifact.`);
1838
- return join(directory, candidate);
2377
+ return join(directory, candidate.name);
2378
+ }
2379
+
2380
+ // A desktop build stages the `ui/` web bundle beside the executable, so the artifact is the one
2381
+ // regular file the host can run - never the first directory that happens to sort first.
2382
+ async function desktopExecutableEntry(directory, entries) {
2383
+ for (const entry of entries) {
2384
+ if (!entry.isFile()) continue;
2385
+ if (process.platform === 'win32') {
2386
+ if (entry.name.endsWith('.exe')) return entry;
2387
+ continue;
2388
+ }
2389
+ if (((await stat(join(directory, entry.name))).mode & 0o111) !== 0) return entry;
2390
+ }
2391
+ return undefined;
1839
2392
  }
1840
2393
 
1841
2394
  async function playtestRunnerPath(project, tools) {
@@ -1910,10 +2463,7 @@ function isNonBlankFrame(value) {
1910
2463
  }
1911
2464
 
1912
2465
  async function browserCommand(args) {
1913
- if (process.platform !== 'linux' || process.env.DISPLAY !== undefined) return { args, command: process.execPath };
1914
- const result = await runCommand('which', ['xvfb-run'], commandRoot);
1915
- if (result.status !== 0) return { args, command: process.execPath };
1916
- return { args: ['-a', '-s', '-screen 0 1600x900x24', process.execPath, ...args], command: 'xvfb-run' };
2466
+ return privateDisplayCommand(process.execPath, args);
1917
2467
  }
1918
2468
 
1919
2469
  async function availablePort() {