@threenative/runtime-native 0.3.2 → 0.3.4

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.
@@ -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, 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,
@@ -53,9 +55,31 @@ const SLOW_STARTUP_DELAY_MS = 5_100;
53
55
  const FRAME_SAMPLE_BATCH_SIZE = 30;
54
56
  // Android logcat truncates long lines, so native samples use a smaller JSON batch.
55
57
  const NATIVE_FRAME_SAMPLE_BATCH_SIZE = 5;
58
+ // The wall-clock a paced fixed step gives each tick, so a synthetic workload's tick budget stands
59
+ // in for the seconds it names and the host's render loop actually presents frames while it runs.
60
+ const PRODUCTION_TICK_INTERVAL_MS = 1_000 / 60;
56
61
  const DESKTOP_SCREENSHOT_TIMEOUT_MS = 5_000;
57
62
  const PRODUCTION_PROFILE = 'production';
58
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
+ }
59
83
 
60
84
  function installedPackageFile(packageName, file) {
61
85
  try {
@@ -82,6 +106,33 @@ export function resolveProductionTools() {
82
106
  };
83
107
  }
84
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
+
85
136
  export function parseProductionArgs(argv = process.argv.slice(2)) {
86
137
  const options = {
87
138
  audioEvidence: undefined,
@@ -91,12 +142,15 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
91
142
  device: undefined,
92
143
  duration: 60,
93
144
  hostedSoftware: false,
145
+ liveClock: false,
94
146
  out: '.runtime/prd064/production',
95
147
  prebuiltArtifact: undefined,
96
148
  physicalEvidence: undefined,
97
149
  profile: PRODUCTION_PROFILE,
150
+ project: undefined,
98
151
  renderSize: undefined,
99
152
  repetitions: 3,
153
+ scenario: undefined,
100
154
  sourceSha: undefined,
101
155
  target: undefined,
102
156
  warmup: 60,
@@ -112,13 +166,16 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
112
166
  else if (flag === '--device') { explicit.add('device'); options.device = nextValue(argv, ++index, flag); }
113
167
  else if (flag === '--duration') { explicit.add('duration'); options.duration = positiveNumber(nextValue(argv, ++index, flag), flag); }
114
168
  else if (flag === '--hosted-software') { options.hostedSoftware = true; }
169
+ else if (flag === '--live-clock') { options.liveClock = true; }
115
170
  else if (flag === '--out') { explicit.add('out'); options.out = nextValue(argv, ++index, flag); }
116
171
  else if (flag === '--prebuilt-artifact') { explicit.add('prebuiltArtifact'); options.prebuiltArtifact = nextValue(argv, ++index, flag); }
117
172
  else if (flag === '--physical-evidence') { explicit.add('physicalEvidence'); options.physicalEvidence = nextValue(argv, ++index, flag); }
118
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); }
119
175
  else if (flag === '--regression') options.profile = REGRESSION_PROFILE;
120
176
  else if (flag === '--render-size') { explicit.add('renderSize'); options.renderSize = parseRenderSize(nextValue(argv, ++index, flag)); }
121
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); }
122
179
  else if (flag === '--source-sha') { explicit.add('sourceSha'); options.sourceSha = nextValue(argv, ++index, flag); }
123
180
  else if (flag === '--target') { explicit.add('target'); options.target = nextValue(argv, ++index, flag); }
124
181
  else if (flag === '--warmup') { explicit.add('warmup'); options.warmup = positiveNumber(nextValue(argv, ++index, flag), flag); }
@@ -136,6 +193,15 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
136
193
  return validateProductionOptions(options);
137
194
  }
138
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
+
139
205
  export function validateProductionOptions(input) {
140
206
  const options = normalizeOptions(input);
141
207
  if (options.help) return options;
@@ -151,6 +217,15 @@ export function validateProductionOptions(input) {
151
217
  if (options.control !== undefined && !supportedControls.has(options.control)) {
152
218
  throw new ProductionEvidenceError('TN_PROD_CONTROL_UNSUPPORTED', `Production control '${options.control}' is not supported.`);
153
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
+ }
154
229
  if (options.target === 'fixture' && options.control === undefined) {
155
230
  throw new ProductionEvidenceError('TN_PROD_FIXTURE_CONTROL_REQUIRED', 'The fixture target is available only as an explicit negative control.');
156
231
  }
@@ -201,7 +276,7 @@ export async function runProductionProfile(input, dependencies = {}) {
201
276
 
202
277
  export async function collectProduction(options, context, runId) {
203
278
  const tools = resolveProductionTools();
204
- if (tools.scaffoldCli === undefined || !await fileExists(tools.scaffoldCli)) {
279
+ if (options.project === undefined && (tools.scaffoldCli === undefined || !await fileExists(tools.scaffoldCli))) {
205
280
  throw new ProductionEvidenceError(
206
281
  'TN_PROD_SCAFFOLDER_UNAVAILABLE',
207
282
  "The installed 'create-threenative' package does not expose its built scaffolder; install it or run the repository build first.",
@@ -214,27 +289,43 @@ export async function collectProduction(options, context, runId) {
214
289
  );
215
290
  }
216
291
 
217
- 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-'));
218
307
  const project = join(temporaryRoot, 'platformer');
219
308
  const startedAt = new Date().toISOString();
220
309
  try {
221
- await scaffoldPlatformer(project, tools);
310
+ await stageProductionProject(options, project, tools);
222
311
  tools.workloadSourceHash = await hashPath(join(project, 'src'));
223
312
  const scenarios = await writeRunScenarios(project, options);
224
313
  const artifactsRoot = join(project, 'artifacts', 'production');
225
314
  await mkdir(artifactsRoot, { recursive: true });
226
- const web = options.target === 'web' || options.target === 'desktop-pair'
227
- ? await collectWeb(project, scenarios, artifactsRoot, options, tools)
228
- : undefined;
315
+ const web = webDisplay === undefined ? undefined : await collectWeb(project, scenarios, artifactsRoot, options, tools, webDisplay);
229
316
  const native = nativeTargets.has(options.target) || options.target === 'desktop-pair'
230
317
  ? await collectNative(project, scenarios, artifactsRoot, options, tools)
231
318
  : undefined;
319
+ const resolutionScaleSetting = native === undefined
320
+ ? undefined
321
+ : await readResolutionScaleSetting(project, options);
232
322
  return assembleEvidence({
233
323
  context,
234
324
  native,
235
325
  options,
236
326
  performanceBounds: scenarios.performanceBounds,
237
327
  project,
328
+ resolutionScaleSetting,
238
329
  runId,
239
330
  startedAt,
240
331
  web,
@@ -252,6 +343,10 @@ function normalizeOptions(input = {}) {
252
343
  const defaultRenderSize = input.hostedSoftware === true && target === 'desktop'
253
344
  ? { height: 720, width: 1280 }
254
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);
255
350
  return {
256
351
  audioEvidence: input.audioEvidence,
257
352
  coldStarts: input.coldStarts ?? (regression ? REGRESSION_COLLECTION_PROFILE.coldStarts : 1),
@@ -260,12 +355,18 @@ function normalizeOptions(input = {}) {
260
355
  duration: input.duration ?? (regression ? REGRESSION_COLLECTION_PROFILE.durationSeconds : 60),
261
356
  hostedSoftware: input.hostedSoftware === true,
262
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,
263
362
  out: input.out ?? (regression ? '.runtime/prd358/regression' : '.runtime/prd064/production'),
264
363
  prebuiltArtifact: input.prebuiltArtifact === undefined ? undefined : resolve(input.prebuiltArtifact),
265
364
  physicalEvidence: input.physicalEvidence,
365
+ project,
266
366
  renderSize: renderSize ?? defaultRenderSize,
267
367
  profile,
268
368
  repetitions: input.repetitions ?? (regression ? 1 : 3),
369
+ scenario,
269
370
  sourceSha: input.sourceSha,
270
371
  target,
271
372
  warmup: input.warmup ?? (regression ? 5 : 60),
@@ -276,6 +377,57 @@ function warmupFramesFor(options) {
276
377
  return Math.max(0, Math.ceil((options.warmup ?? 0) * 60));
277
378
  }
278
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
+
279
431
  async function scaffoldPlatformer(project, tools) {
280
432
  const packageArchiveRoot = join(project, '..', 'package-archives');
281
433
  await mkdir(packageArchiveRoot, { recursive: true });
@@ -299,9 +451,10 @@ async function scaffoldPlatformer(project, tools) {
299
451
  '--template', 'platformer',
300
452
  ...localSources.flatMap(([name, source]) => [packageSourceFlag(name), source]),
301
453
  ];
302
- const result = await runCommand(process.execPath, args, commandRoot);
454
+ // Scaffolding packs and installs the whole workspace, which is slow on hosted runners.
455
+ const result = await runCommand(process.execPath, args, commandRoot, undefined, 600_000);
303
456
  if (result.status !== 0) {
304
- throw new ProductionEvidenceError('TN_PROD_SCAFFOLD_FAILED', 'Scaffolding the production platformer failed.');
457
+ throw new ProductionEvidenceError('TN_PROD_SCAFFOLD_FAILED', `Scaffolding the production platformer failed.${failureSuffix(result)}`);
305
458
  }
306
459
  }
307
460
 
@@ -319,7 +472,7 @@ function localWorkspacePackages() {
319
472
  async function packLocalPackage(directory, destination) {
320
473
  const before = new Set(await readdir(destination));
321
474
  const result = await runCommand('pnpm', ['pack', '--pack-destination', destination], directory);
322
- if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' failed.`);
475
+ if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' failed.${failureSuffix(result)}`);
323
476
  const archive = (await readdir(destination)).find((entry) => entry.endsWith('.tgz') && !before.has(entry));
324
477
  if (archive === undefined) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' produced no archive.`);
325
478
  return join(destination, archive);
@@ -336,22 +489,40 @@ function packageSourceFlag(name) {
336
489
  throw new Error(`TN_PROD_PACKAGE_FLAG_UNSUPPORTED: ${name}`);
337
490
  }
338
491
 
339
- function nativeDiagnostics(assertions) {
340
- return {
341
- ...assertions,
342
- diagnostics: {
343
- ...assertions.diagnostics,
344
- noConsoleErrors: true,
345
- noRuntimeDiagnostics: true,
346
- runtimeReady: true,
347
- noNetworkErrors: false,
348
- networkErrorsOptOutReason: 'Native mailbox transports have no browser network observer; console and runtime diagnostics remain required.',
349
- },
350
- };
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' } };
351
519
  }
352
520
 
353
521
  export async function writeRunScenarios(project, options) {
354
- 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
+ }));
355
526
  const sourceAssertions = source.assert && typeof source.assert === 'object' && !Array.isArray(source.assert)
356
527
  ? source.assert
357
528
  : {};
@@ -365,14 +536,24 @@ export async function writeRunScenarios(project, options) {
365
536
  const { assert: _sourceAssertions, ...scenarioSource } = source;
366
537
  const workloadFrames = Math.max(1, Math.ceil(options.duration * 60));
367
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
+ }
368
552
  const workload = {
369
553
  ...scenarioSource,
370
554
  assert: workloadAssertions,
371
555
  artifacts: { screenshots: 'after' },
372
- steps: [
373
- { holdFrames: Math.min(60, workloadFrames), kind: 'input', press: 'ArrowRight', release: true },
374
- { kind: 'wait', release: true, waitFrames: workloadFrames },
375
- ],
556
+ steps: workloadSteps,
376
557
  viewport: options.renderSize,
377
558
  warmupFrames,
378
559
  };
@@ -386,7 +567,18 @@ export async function writeRunScenarios(project, options) {
386
567
  waitFrames: 1,
387
568
  })),
388
569
  ]
389
- : 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
+ });
390
582
  const startup = {
391
583
  ...scenarioSource,
392
584
  assert: { diagnostics: { noConsoleErrors: true, runtimeReady: true } },
@@ -395,9 +587,10 @@ export async function writeRunScenarios(project, options) {
395
587
  viewport: options.renderSize,
396
588
  warmupFrames: 0,
397
589
  };
590
+ const timeoutMs = playtestTimeoutMs(workload);
398
591
  const nativeWorkload = {
399
592
  ...workload,
400
- assert: nativeDiagnostics(workload.assert),
593
+ assert: hostedSoftwareAssertions(nativeAssertions(workload.assert, timeoutMs, options.hostedSoftware), options.hostedSoftware),
401
594
  artifacts: {
402
595
  screenshots: options.profile === REGRESSION_PROFILE || nativeTarget === 'desktop'
403
596
  ? 'after'
@@ -405,7 +598,7 @@ export async function writeRunScenarios(project, options) {
405
598
  },
406
599
  steps: nativeWorkloadSteps,
407
600
  };
408
- const nativeStartup = { ...startup, assert: nativeDiagnostics(startup.assert), artifacts: { screenshots: 'after' } };
601
+ const nativeStartup = { ...startup, assert: nativeAssertions(startup.assert, timeoutMs, options.hostedSoftware), artifacts: { screenshots: 'after' } };
409
602
  const workloadPath = join(project, 'playtests/production-performance.run.playtest.json');
410
603
  const startupPath = join(project, 'playtests/production-startup.run.playtest.json');
411
604
  const nativeWorkloadPath = join(project, 'playtests/production-performance.native.playtest.json');
@@ -419,21 +612,57 @@ export async function writeRunScenarios(project, options) {
419
612
  nativeStartupPath,
420
613
  nativeWorkloadPath,
421
614
  startupPath,
615
+ timeoutMs,
422
616
  workloadPath,
423
617
  };
424
618
  }
425
619
 
426
- 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).
427
655
  const markerServer = await createFrameMarkerServer(options.profile === REGRESSION_PROFILE ? 41778 : 0);
428
656
  try {
429
- await installWebProfileEntry(project, markerServer.url, options.control, warmupFramesFor(options));
430
- const build = await runCommand('pnpm', ['run', 'build:web'], project);
431
- if (build.status !== 0) throw new ProductionEvidenceError('TN_PROD_WEB_BUILD_FAILED', 'The scaffolded platformer web build failed.');
657
+ await installWebProfileEntry(project, options.control, warmupFramesFor(options), paceTicksFor(options), options.liveClock);
658
+ // A production build can outlast the default timeout on slow hosted runners.
659
+ const build = await runCommand('pnpm', ['run', 'build:web'], project, undefined, 300_000);
660
+ if (build.status !== 0) throw new ProductionEvidenceError('TN_PROD_WEB_BUILD_FAILED', `The scaffolded platformer web build failed.${failureSuffix(build)}`);
432
661
  const artifactSha = await hashPath(join(project, 'dist'));
433
662
  const runs = [];
434
663
  const startups = [];
435
664
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
436
- 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);
437
666
  startups.push(startup);
438
667
  for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
439
668
  runs.push(await runWebScenario(
@@ -442,6 +671,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
442
671
  join(artifactsRoot, `web-${coldStart + 1}-${repetition + 1}`),
443
672
  markerServer,
444
673
  tools.playtestCli,
674
+ scenarios.timeoutMs,
445
675
  ));
446
676
  }
447
677
  }
@@ -451,6 +681,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
451
681
  applicationClass: 'platformer-web-build',
452
682
  driverClass: 'playwright-chromium-webgpu',
453
683
  kind: 'web',
684
+ display,
454
685
  runs,
455
686
  startups,
456
687
  };
@@ -459,7 +690,16 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
459
690
  }
460
691
  }
461
692
 
462
- 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) {
463
703
  await mkdir(artifactDirectory, { recursive: true });
464
704
  const port = await availablePort();
465
705
  const relativeArtifact = relative(project, artifactDirectory);
@@ -468,24 +708,28 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
468
708
  relative(project, scenarioPath),
469
709
  '--artifacts', relativeArtifact,
470
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',
471
715
  '--project', project,
472
716
  '--server-command', `pnpm exec vite preview --host 127.0.0.1 --port ${port} --strictPort`,
473
- '--timeout', '30000',
717
+ '--timeout', String(timeoutMs),
474
718
  '--url', `http://127.0.0.1:${port}`,
475
719
  ];
476
720
  const command = await browserCommand(args);
477
- const markerIndex = markerServer.length;
478
- const startedAt = performance.now();
479
- const result = await runCommand(command.command, command.args, commandRoot, undefined, 180_000);
480
- 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);
481
726
  const report = parsePlaytestReport(result.stdout);
482
727
  return normalizeRun(
483
728
  result,
484
729
  artifactDirectory,
485
730
  'web',
486
731
  report,
487
- markers?.firstFrame === undefined ? undefined : markers.firstFrame.receivedAt - startedAt,
488
- markers?.samples ?? [],
732
+ firstFrameMsFromReport(report, startedAt),
489
733
  );
490
734
  }
491
735
 
@@ -503,12 +747,16 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
503
747
  `The scaffolded platformer ${target} build failed.${details.length === 0 ? '' : `\n${details.slice(-4_000)}`}`,
504
748
  );
505
749
  }
506
- 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);
507
755
  const artifactSha = await hashPath(artifactPath);
508
756
  const runs = [];
509
757
  const startups = [];
510
758
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
511
- 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);
512
760
  startups.push(startup);
513
761
  for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
514
762
  runs.push(await runNativeScenario(
@@ -519,6 +767,7 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
519
767
  options,
520
768
  artifactPath,
521
769
  tools,
770
+ scenarios.timeoutMs,
522
771
  ));
523
772
  }
524
773
  }
@@ -534,10 +783,10 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
534
783
  };
535
784
  }
536
785
 
537
- async function runNativeScenario(project, target, scenarioPath, artifactDirectory, options, artifactPath, tools) {
786
+ async function runNativeScenario(project, target, scenarioPath, artifactDirectory, options, artifactPath, tools, timeoutMs) {
538
787
  await mkdir(artifactDirectory, { recursive: true });
539
788
  if (target === 'desktop') {
540
- return await runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools);
789
+ return await runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools, timeoutMs);
541
790
  }
542
791
  const modulePath = await playtestRunnerPath(project, tools);
543
792
  if (modulePath === undefined) {
@@ -563,7 +812,7 @@ async function runNativeScenario(project, target, scenarioPath, artifactDirector
563
812
  projectPath: project,
564
813
  scenarioPath: relative(project, scenarioPath),
565
814
  target,
566
- timeoutMs: 30_000,
815
+ timeoutMs,
567
816
  trace: false,
568
817
  url: 'http://127.0.0.1:41777',
569
818
  };
@@ -580,14 +829,14 @@ async function runNativeScenario(project, target, scenarioPath, artifactDirector
580
829
  target,
581
830
  report,
582
831
  firstFrameMsFromReport(report, startedAt),
583
- frameSeriesFromReport(report),
832
+ frameSeriesFromReport(report, target),
584
833
  );
585
834
  } catch {
586
835
  return { elapsedMs: performance.now() - started, report: undefined, screenshot: undefined, series: undefined, status: 2 };
587
836
  }
588
837
  }
589
838
 
590
- async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools) {
839
+ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools, timeoutMs) {
591
840
  const modulePath = await playtestRunnerPath(project, tools);
592
841
  if (modulePath === undefined) {
593
842
  return { elapsedMs: undefined, report: undefined, screenshot: undefined, series: undefined, status: 2 };
@@ -599,8 +848,7 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
599
848
  const responsePath = join(mailboxRoot, 'tn-playtest-response.json');
600
849
  const runner = await import(pathToFileURL(modulePath).href);
601
850
  const mailbox = new runner.LocalDeviceMailbox();
602
- const timeoutMs = 30_000;
603
- const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath }, timeoutMs);
851
+ const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath });
604
852
  const driver = createDesktopDriver(artifactPath, project, options, mailboxRoot);
605
853
  const transport = {
606
854
  capabilities: innerTransport.capabilities,
@@ -639,7 +887,6 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
639
887
  'desktop',
640
888
  report,
641
889
  firstFrameMsFromReport(report, startedAt),
642
- frameSeriesFromReport(report),
643
890
  );
644
891
  } catch (error) {
645
892
  let cleanupError;
@@ -676,6 +923,32 @@ export function profileConfigPath(project, configPath = undefined) {
676
923
  return configPath ?? join(project, '.threenative', 'build', 'config.json');
677
924
  }
678
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
+
679
952
  function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
680
953
  let child;
681
954
  let output = '';
@@ -711,7 +984,7 @@ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
711
984
  if (stopping !== undefined) return stopping;
712
985
  stopping = (async () => {
713
986
  if (child === undefined || child.exitCode !== null || child.signalCode !== null) return;
714
- const cleanupTimeoutMs = options.desktopCleanupTimeoutMs ?? 2_000;
987
+ const cleanupTimeoutMs = options.desktopCleanupTimeoutMs ?? 10_000;
715
988
  const waitForExit = new Promise((resolve, reject) => {
716
989
  let timer;
717
990
  let settled = false;
@@ -757,18 +1030,42 @@ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
757
1030
  };
758
1031
  }
759
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
+
760
1053
  function spawnNative(artifactPath, project, options, mailboxRoot) {
761
1054
  const bundle = join(project, '.threenative/build/game.js');
1055
+ // A packaged desktop artifact embeds the instrumented game entry under its own module root, and
1056
+ // an explicit `run <absolute path>` is resolved against that root rather than the filesystem, so
1057
+ // the external bundle never loads and the run reports TN_PLAYTEST_BRIDGE_MISSING at zero frames.
1058
+ // Launch the embedded entry. A bare runtime supplied through `--prebuilt-artifact` carries no
1059
+ // embedded entry and still needs the external bundle named on the command line.
1060
+ const launchesExternalBundle = nativeLaunchesExternalBundle(artifactPath, options);
762
1061
  const nativeArgs = [
763
- 'run',
764
- bundle,
1062
+ ...(launchesExternalBundle ? ['run', bundle] : []),
765
1063
  '--width', String(options.renderSize.width),
766
1064
  '--height', String(options.renderSize.height),
767
1065
  '--headless',
768
1066
  ];
769
- const command = process.platform === 'linux' && process.env.DISPLAY === undefined ? 'xvfb-run' : artifactPath;
770
- const args = command === 'xvfb-run' ? ['-a', '-s', '-screen 0 1600x900x24', artifactPath, ...nativeArgs] : nativeArgs;
771
- return spawn(command, args, {
1067
+ const command = privateDisplayCommand(artifactPath, nativeArgs);
1068
+ return spawn(command.command, command.args, {
772
1069
  cwd: project,
773
1070
  detached: process.platform !== 'win32',
774
1071
  env: { ...process.env, TN_PLAYTEST_MAILBOX_ROOT: mailboxRoot, SDL_VIDEODRIVER: process.platform === 'linux' ? 'x11' : process.env.SDL_VIDEODRIVER },
@@ -784,31 +1081,36 @@ export async function installNativeProfileEntry(project, target, options) {
784
1081
  const mailbox = target === 'desktop'
785
1082
  ? `globalThis.TN_PLAYTEST_MAILBOX = ${JSON.stringify({ request: join(mailboxRoot, 'tn-playtest-request.json'), response: join(mailboxRoot, 'tn-playtest-response.json') })};\n`
786
1083
  : '';
787
- const source = `import "./profile-native-profile.js";\nimport game from "./game.js";\n${nativeFrameInstrumentation(options.control, warmupFramesFor(options))}\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`;
788
1085
  await writeFile(profileMarkerPath, profileMarker);
789
1086
  await writeFile(entryPath, source);
790
- await setNativeProfileEntry(project, 'src/profile-native-entry.ts', target);
1087
+ await setNativeProfileEntry(project, 'src/profile-native-entry.ts', options.renderSize);
791
1088
  }
792
1089
 
793
- export async function setNativeProfileEntry(project, entry, target) {
1090
+ export async function setNativeProfileEntry(project, entry, renderSize = undefined) {
794
1091
  const configPath = join(project, 'threenative.config.ts');
795
1092
  const packagePath = join(project, 'package.json');
796
1093
  const config = await readFile(configPath, 'utf8').catch(() => undefined);
797
1094
  if (config !== undefined) {
798
- const withEntry = config.replace(
799
- /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu,
800
- `$1"${entry}"$2`,
801
- );
802
- const rendered = target === 'desktop'
803
- ? withEntry.replace(
804
- /(\bui\s*:\s*\{\s*renderer\s*:\s*)["'][^"']*["']/mu,
805
- `$1"native"`,
806
- )
807
- : withEntry;
808
- if (rendered !== config) {
809
- await writeFile(configPath, rendered);
1095
+ // Whether the config declares the field at all is a different question from whether its value
1096
+ // changes, and only the first one decides where the entry lives. Reading it off `withEntry !==
1097
+ // config` conflates the two: a config already naming this entry left the value unchanged, fell
1098
+ // through to the package.json branch below, and declared `nativeEntry` in *both* files — which
1099
+ // the next `threenative build --target desktop` refuses with `TN_CONFIG_CONFLICT`. A project
1100
+ // profiled once could therefore never be profiled a second time.
1101
+ const entryPattern = /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu;
1102
+ const declaresEntry = entryPattern.test(config);
1103
+ const withEntry = config.replace(entryPattern, `$1"${entry}"$2`);
1104
+ // The packaged desktop artifact carries the game's config embedded, and the native host reads
1105
+ // its window size from there before any command-line flag, so the profiled surface is only the
1106
+ // requested render size when the config states it.
1107
+ const sized = renderSize === undefined ? withEntry : applyWindowSize(withEntry, renderSize);
1108
+ if (sized !== config) {
1109
+ await writeFile(configPath, sized);
810
1110
  }
811
- if (withEntry !== config) {
1111
+ if (declaresEntry) {
1112
+ // One declaration, in the file the config layer resolves first. Dropping a stale key is also
1113
+ // how a project already corrupted by the old fall-through is repaired on its next run.
812
1114
  const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
813
1115
  if (packageJson.threenative?.nativeEntry !== undefined) {
814
1116
  delete packageJson.threenative.nativeEntry;
@@ -823,28 +1125,142 @@ export async function setNativeProfileEntry(project, entry, target) {
823
1125
  await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
824
1126
  }
825
1127
 
1128
+ function applyWindowSize(config, renderSize) {
1129
+ return config
1130
+ .replace(/(\bwindow\s*:\s*\{[^}]*?\bwidth\s*:\s*)\d+/mu, `$1${renderSize.width}`)
1131
+ .replace(/(\bwindow\s*:\s*\{[^}]*?\bheight\s*:\s*)\d+/mu, `$1${renderSize.height}`);
1132
+ }
1133
+
826
1134
  function productionPerformanceReader() {
827
1135
  return `
1136
+ // The installed bridge answers through a promise: core's playtest plugin wraps sample() to merge
1137
+ // its runtime observation contributions asynchronously, so reading the returned snapshot inline
1138
+ // saw a thenable and dropped every draw-call and triangle reading. Keep the last resolved
1139
+ // performance read and answer it on the next frame instead.
1140
+ let tnProductionLastPerformance;
828
1141
  const tnProductionReadPerformance = () => {
829
1142
  const bridge = globalThis.__THREENATIVE_PLAYTEST_BRIDGE__;
830
- if (typeof bridge?.sample !== "function") return {};
831
- try {
832
- const snapshot = bridge.sample({});
833
- if (snapshot === null || typeof snapshot !== "object" || typeof snapshot.then === "function") return {};
834
- const performance = snapshot.performance;
835
- return {
836
- ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
837
- ...(performance?.phases !== undefined ? { phases: performance.phases } : {}),
838
- ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
839
- };
840
- } catch {
841
- return {};
1143
+ if (typeof bridge?.sample === "function") {
1144
+ try {
1145
+ const snapshot = bridge.sample({});
1146
+ if (snapshot !== null && typeof snapshot === "object") {
1147
+ if (typeof snapshot.then === "function") {
1148
+ snapshot.then((resolved) => { tnProductionLastPerformance = resolved?.performance; }).catch(() => undefined);
1149
+ } else {
1150
+ tnProductionLastPerformance = snapshot.performance;
1151
+ }
1152
+ }
1153
+ } catch {
1154
+ }
842
1155
  }
1156
+ const performance = tnProductionLastPerformance;
1157
+ return {
1158
+ ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
1159
+ ...(performance?.phases !== undefined ? { phases: performance.phases } : {}),
1160
+ ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
1161
+ };
843
1162
  };
844
1163
  `;
845
1164
  }
846
1165
 
847
- export function nativeFrameInstrumentation(control, warmupFrames = 0) {
1166
+ /**
1167
+ * Ask the game for the wall clock, so the profile measures a game playing.
1168
+ *
1169
+ * A profile run is a playtest run, and a playtest run freezes the live clock: the runner asks the
1170
+ * bridge for fixed steps and the loop simulates nothing else, so the frames the host presents while
1171
+ * a burst of ticks is delivered repeat one standing state. The browser reported ~60 fps of a
1172
+ * platformer whose movement was advancing in ten-tick jumps, and the frame samples the judge reads
1173
+ * described that, not the game. `__THREENATIVE_PLAYTEST_CLOCK__` is the framework's own switch for
1174
+ * the opposite, and it has to be set before the bundle evaluates — which is what the instrumentation
1175
+ * this rides in is.
1176
+ */
1177
+ export function productionClockRequest(liveClock = false) {
1178
+ return liveClock === true ? 'globalThis.__THREENATIVE_PLAYTEST_CLOCK__ = "wall-clock";\n' : '';
1179
+ }
1180
+
1181
+ /**
1182
+ * Pace the fixed step to wall time so a synthetic workload's tick budget is the seconds it names.
1183
+ *
1184
+ * The native device transport drives the simulation through `bridge.advance(ticks)`, and the host
1185
+ * runs that loop synchronously: a single `advance(3600)` finishes in milliseconds, so the host's
1186
+ * requestAnimationFrame loop never presents the 60 seconds of frames the scenario asked to warm up
1187
+ * or measure, and the warmup boundary is never reached. Wrapping `advance` to wait one display
1188
+ * interval per tick lets the host's own loop run during the wait, so the frames exist to be
1189
+ * measured.
1190
+ *
1191
+ * The same wrapper arms on the live clock, and it is idempotent there rather than a second wait: a
1192
+ * wall-clock `advance` spends the span its ticks name before the wrapper reads its own deadline, so
1193
+ * the remainder is zero or less and no wall-clock run is slowed. It is also the only thing that
1194
+ * makes the host present the frames on any host whose `advance` did not wait them, which is what a
1195
+ * short measured window is. Reading the live clock as "already paced, so skip the pacer" was the
1196
+ * defect: the native host consumed the frame-count workload at its own speed, and 60 requested
1197
+ * seconds published as a 1.5 s window.
1198
+ */
1199
+ export function productionExecutionHold(paceTicks = false) {
1200
+ return `
1201
+ const tnProductionPaceEnabled = ${paceTicks === true};
1202
+ const tnProductionTickIntervalMs = ${PRODUCTION_TICK_INTERVAL_MS};
1203
+ let tnProductionPaceAt;
1204
+ let tnProductionPaceInstalled = false;
1205
+ const tnProductionInstallPace = () => {
1206
+ if (!tnProductionPaceEnabled || tnProductionPaceInstalled) return;
1207
+ const tnProductionBridge = globalThis.__THREENATIVE_PLAYTEST_BRIDGE__;
1208
+ if (typeof tnProductionBridge?.advance !== "function") return;
1209
+ const tnProductionAdvance = tnProductionBridge.advance.bind(tnProductionBridge);
1210
+ tnProductionBridge.advance = async (ticks) => {
1211
+ const startedAt = performance.now();
1212
+ tnProductionPaceAt = Math.max(tnProductionPaceAt ?? startedAt, startedAt) + ticks * tnProductionTickIntervalMs;
1213
+ const result = await tnProductionAdvance(ticks);
1214
+ const waitMs = tnProductionPaceAt - performance.now();
1215
+ if (waitMs > 0) await new Promise((resolve) => setTimeout(resolve, waitMs));
1216
+ return result;
1217
+ };
1218
+ tnProductionPaceInstalled = true;
1219
+ };
1220
+ tnProductionInstallPace();
1221
+ `;
1222
+ }
1223
+
1224
+ /**
1225
+ * The warmup boundary both arms share: the frame count *and* the wall time those frames were asked
1226
+ * to cover.
1227
+ *
1228
+ * A frame count only names a duration on a host that presents at 60 Hz, and neither host is one. The
1229
+ * native host ran 120 frames — the whole `--warmup 2` budget — in 1.18 s of a requested 2 s while it
1230
+ * booted at 100-170 Hz, so the measured window started at the last first-use pipeline compile and
1231
+ * published boot as a frame rate: native 26.29 mean fps, 306.04 ms p95, beside
1232
+ * `execution.warmupSeconds: 2`. The frame bound stays, because a host *slower* than 60 Hz needs it
1233
+ * more than a host that runs ahead, and the two are the same number on a 60 Hz browser.
1234
+ */
1235
+ function productionWarmupBoundary(warmupFrames = 0) {
1236
+ return `
1237
+ const tnProductionWarmupMs = ${Math.max(0, Math.floor(warmupFrames)) / 60 * 1_000};
1238
+ let tnProductionStartedAtMs;
1239
+ const tnProductionInWarmup = (frameIndex, now) => {
1240
+ tnProductionStartedAtMs ??= now;
1241
+ return frameIndex < tnProductionWarmupFrames || now - tnProductionStartedAtMs < tnProductionWarmupMs;
1242
+ };
1243
+ `;
1244
+ }
1245
+
1246
+ /**
1247
+ * The measurement reset, on the transition rather than on the frame count the boundary also checks.
1248
+ *
1249
+ * The frame count is only one of the two bounds, and a host that presents slower than 60 Hz reaches
1250
+ * the wall time later. Clearing the carry on the frame count left the last warmup frame still holding
1251
+ * the previous frame's clock, so the first measured frame reported the interval that spanned the
1252
+ * boundary — the crossing stall, or the whole warmup tail — as gameplay. Both arms warm up
1253
+ * monotonically, so the transition happens once and the flag keeps it to once.
1254
+ */
1255
+ function tnProductionMeasurementStart() {
1256
+ return `if (!inWarmup && !tnProductionMeasuring) {
1257
+ tnProductionMeasuring = true;
1258
+ tnProductionPreviousFrame = undefined;
1259
+ tnProductionSamples = [];
1260
+ }`;
1261
+ }
1262
+
1263
+ export function nativeFrameInstrumentation(control, warmupFrames = 0, paceTicks = false, liveClock = false) {
848
1264
  return `
849
1265
  const tnProductionControl = ${JSON.stringify(control ?? '')};
850
1266
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
@@ -852,25 +1268,28 @@ const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
852
1268
  if (typeof tnProductionRequestAnimationFrame !== "function") {
853
1269
  throw new Error("TN_PROD_NATIVE_RAF_UNAVAILABLE: native host did not provide requestAnimationFrame.");
854
1270
  }
1271
+ ${productionClockRequest(liveClock)}
855
1272
  let tnProductionFirstFrame = true;
856
1273
  let tnProductionFrameIndex = 0;
857
1274
  let tnProductionPreviousFrame;
1275
+ let tnProductionPresentation;
858
1276
  let tnProductionSamples = [];
1277
+ let tnProductionMeasuring = false;
859
1278
  let tnProductionSlowFramesRemaining = ${SLOW_FRAME_COUNT};
860
1279
  const tnProductionBusyWait = (milliseconds) => {
861
1280
  const deadline = performance.now() + milliseconds;
862
1281
  while (performance.now() < deadline) {}
863
1282
  };
1283
+ ${productionWarmupBoundary(warmupFrames)}
864
1284
  ${productionPerformanceReader()}
1285
+ ${productionExecutionHold(paceTicks)}
865
1286
  globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
1287
+ tnProductionInstallPace();
866
1288
  const frameIndex = tnProductionFrameIndex++;
867
- const inWarmup = frameIndex < tnProductionWarmupFrames;
868
- if (frameIndex === tnProductionWarmupFrames) {
869
- tnProductionPreviousFrame = undefined;
870
- tnProductionSamples = [];
871
- }
872
1289
  if (tnProductionFirstFrame && tnProductionControl === "slow-startup") tnProductionBusyWait(${SLOW_STARTUP_DELAY_MS});
873
1290
  const now = performance.now();
1291
+ const inWarmup = tnProductionInWarmup(frameIndex, now);
1292
+ ${tnProductionMeasurementStart()}
874
1293
  const frameMs = inWarmup || tnProductionPreviousFrame === undefined ? undefined : now - tnProductionPreviousFrame;
875
1294
  tnProductionPreviousFrame = now;
876
1295
  callback(timestamp);
@@ -899,48 +1318,58 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
899
1318
  `;
900
1319
  }
901
1320
 
902
- export function webFrameInstrumentation(markerUrl, control, warmupFrames = 0) {
1321
+ /**
1322
+ * The web arm reports over the console, the same transport the native arm already uses, so one
1323
+ * parser and one clock serve both. It used to POST to a marker server, which the playtest's own
1324
+ * `noNetworkErrors` policy then failed the run for: Chromium reports every in-flight `fetch` as
1325
+ * `net::ERR_ABORTED` when the runner tears the page down, so the profile failed its own runs for
1326
+ * its own instrumentation. The judge still owns `--judge-marker-url`; only the game's samples moved.
1327
+ */
1328
+ export function webFrameInstrumentation(control, warmupFrames = 0, paceTicks = false, liveClock = false) {
903
1329
  return `
904
1330
  const tnProductionControl = ${JSON.stringify(control ?? '')};
905
1331
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
906
- const tnProductionMarkerUrl = ${JSON.stringify(markerUrl)};
907
1332
  const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
908
1333
  if (typeof tnProductionRequestAnimationFrame !== "function") {
909
1334
  throw new Error("TN_PROD_WEB_RAF_UNAVAILABLE: browser host did not provide requestAnimationFrame.");
910
1335
  }
1336
+ ${productionClockRequest(liveClock)}
911
1337
  let tnProductionFirstFrame = true;
912
1338
  let tnProductionFrameIndex = 0;
913
1339
  let tnProductionPreviousFrame;
1340
+ let tnProductionPresentation;
914
1341
  let tnProductionSamples = [];
1342
+ let tnProductionMeasuring = false;
915
1343
  let tnProductionSlowFramesRemaining = ${SLOW_FRAME_COUNT};
916
1344
  const tnProductionBusyWait = (milliseconds) => {
917
1345
  const deadline = performance.now() + milliseconds;
918
1346
  while (performance.now() < deadline) {}
919
1347
  };
920
- const tnProductionPost = (payload) => {
921
- void fetch(tnProductionMarkerUrl, {
922
- body: JSON.stringify(payload),
923
- keepalive: true,
924
- method: "POST",
925
- mode: "no-cors",
926
- }).catch(() => undefined);
927
- };
1348
+ ${productionWarmupBoundary(warmupFrames)}
928
1349
  ${productionPerformanceReader()}
1350
+ ${productionExecutionHold(paceTicks)}
929
1351
  globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
1352
+ tnProductionInstallPace();
1353
+ // One browser presentation can invoke every callback registered for it with the same
1354
+ // DOMHighResTimeStamp. Counting each callback would push a zero-length interval and make meanFps
1355
+ // indeterminate, so only the first callback for a presentation is the frame; the rest still run
1356
+ // their callback unchanged.
1357
+ if (Number.isFinite(timestamp) && timestamp === tnProductionPresentation) {
1358
+ callback(timestamp);
1359
+ return;
1360
+ }
1361
+ tnProductionPresentation = Number.isFinite(timestamp) ? timestamp : undefined;
930
1362
  const frameIndex = tnProductionFrameIndex++;
931
- const inWarmup = frameIndex < tnProductionWarmupFrames;
932
- if (frameIndex === tnProductionWarmupFrames) {
933
- tnProductionPreviousFrame = undefined;
934
- tnProductionSamples = [];
935
- }
936
1363
  if (tnProductionFirstFrame && tnProductionControl === "slow-startup") tnProductionBusyWait(${SLOW_STARTUP_DELAY_MS});
937
1364
  const now = performance.now();
1365
+ const inWarmup = tnProductionInWarmup(frameIndex, now);
1366
+ ${tnProductionMeasurementStart()}
938
1367
  const frameMs = inWarmup || tnProductionPreviousFrame === undefined ? undefined : now - tnProductionPreviousFrame;
939
1368
  tnProductionPreviousFrame = now;
940
1369
  callback(timestamp);
941
1370
  if (tnProductionFirstFrame) {
942
1371
  tnProductionFirstFrame = false;
943
- tnProductionPost({ kind: "first-frame" });
1372
+ console.log("TN_PROD_FIRST_NONBLANK_FRAME:" + Date.now());
944
1373
  }
945
1374
  if (!inWarmup && frameMs !== undefined) {
946
1375
  tnProductionSamples.push({
@@ -951,7 +1380,7 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
951
1380
  frameMs,
952
1381
  });
953
1382
  if (tnProductionSamples.length >= ${FRAME_SAMPLE_BATCH_SIZE}) {
954
- tnProductionPost({ kind: "samples", samples: tnProductionSamples });
1383
+ console.log("TN_PROD_FRAME_SAMPLES:" + JSON.stringify(tnProductionSamples));
955
1384
  tnProductionSamples = [];
956
1385
  }
957
1386
  }
@@ -963,16 +1392,17 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
963
1392
  `;
964
1393
  }
965
1394
 
966
- async function installWebProfileEntry(project, markerUrl, control, warmupFrames = 0) {
1395
+ async function installWebProfileEntry(project, control, warmupFrames = 0, paceTicks = false, liveClock = false) {
967
1396
  const markerPath = join(project, 'src/profile-production-marker.ts');
968
1397
  const mainPath = join(project, 'src/main.ts');
969
1398
  const markerImport = 'import "./profile-production-marker.js";';
970
1399
  const main = await readFile(mainPath, 'utf8');
971
- const source = webFrameInstrumentation(markerUrl, control, warmupFrames);
1400
+ const source = webFrameInstrumentation(control, warmupFrames, paceTicks, liveClock);
972
1401
  await writeFile(markerPath, source);
973
1402
  if (!main.includes(markerImport)) await writeFile(mainPath, `${markerImport}\n${main}`);
974
1403
  }
975
1404
 
1405
+
976
1406
  async function createFrameMarkerServer(port = 0) {
977
1407
  const events = [];
978
1408
  const waiters = [];
@@ -1028,7 +1458,7 @@ function markerEvents(events) {
1028
1458
  return { firstFrame, samples };
1029
1459
  }
1030
1460
 
1031
- async function normalizeRun(
1461
+ export async function normalizeRun(
1032
1462
  result,
1033
1463
  artifactDirectory,
1034
1464
  kind,
@@ -1038,14 +1468,19 @@ async function normalizeRun(
1038
1468
  ) {
1039
1469
  const reportSeries = report?.observations?.visual?.runtimeDiagnosticsSeries;
1040
1470
  const performanceSeries = report?.observations?.performanceSeries;
1041
- const consoleSeries = frameSeriesFromReport(report);
1042
- const series = [collectedSeries, reportSeries, performanceSeries, consoleSeries]
1043
- .find((candidate) => Array.isArray(candidate) && candidate.length > 0);
1471
+ const consoleSeries = frameSeriesFromReport(report, kind);
1472
+ const series = kind === 'desktop'
1473
+ ? consoleSeries
1474
+ : [collectedSeries, reportSeries, performanceSeries, consoleSeries]
1475
+ .find((candidate) => Array.isArray(candidate) && candidate.length > 0);
1044
1476
  const screenshotPath = join(artifactDirectory, 'after.png');
1045
1477
  const screenshot = await nonBlankPng(screenshotPath) ? await readFile(screenshotPath) : undefined;
1046
1478
  return {
1047
1479
  elapsedMs: result.durationMs,
1048
1480
  ...(Number.isFinite(firstFrameMs) ? { firstFrameMs } : {}),
1481
+ // A child that exits without a parseable report has no report and usually no screenshot, so
1482
+ // without this the whole run vanishes from the evidence and the failure is an absence.
1483
+ ...(report === undefined ? { failure: missingReportFailure(result) } : {}),
1049
1484
  kind,
1050
1485
  report: report === undefined ? undefined : safeReport(report),
1051
1486
  screenshot,
@@ -1054,6 +1489,16 @@ async function normalizeRun(
1054
1489
  };
1055
1490
  }
1056
1491
 
1492
+ function missingReportFailure(result) {
1493
+ return sanitizeReportValue({
1494
+ code: 'TN_PROD_RUN_REPORT_MISSING',
1495
+ message: `The child run exited without a parseable report${failureSuffix(result).slice(-4_000)}`,
1496
+ severity: 'error',
1497
+ status: result.status,
1498
+ timedOut: result.timedOut === true,
1499
+ });
1500
+ }
1501
+
1057
1502
  const REPORT_REDACTION_MESSAGE = 'TN_PROD_REDACTION: unsafe native report detail withheld.';
1058
1503
 
1059
1504
  export function safeReport(report) {
@@ -1127,9 +1572,26 @@ function firstFrameMsFromReport(report, startedAt) {
1127
1572
  return elapsed >= 0 ? elapsed : undefined;
1128
1573
  }
1129
1574
 
1130
- function frameSeriesFromReport(report) {
1575
+ /**
1576
+ * The desktop host takes its `after.png` inside its own frame loop, so the readback runs where a
1577
+ * frame runs and the frame that spans it reports the readback as its own `frameMs`. Both clean-HEAD
1578
+ * native collections at `f645e65c8` carry a 358.26 ms and a 312.72 ms gap in the batch logged after
1579
+ * the host's capture line, beside a `TN_SLOW_PHASE pollEvents` at 358.19 and 312.79 ms. The capture
1580
+ * line and the sample batches are both `std::cout` in that one process, so console order is write
1581
+ * order and the line is an exact boundary rather than a threshold: every batch logged at or after it
1582
+ * is dropped whole, because such a batch straddles the capture and dropping one is the direction
1583
+ * that cannot read the readback as gameplay. The capture is still requested and its artifact still
1584
+ * retained — this bounds the measured window, it does not remove the evidence.
1585
+ */
1586
+ function frameSeriesFromReport(report, kind) {
1587
+ const lines = reportConsoleLines(report);
1588
+ // No capture line means no boundary, so a desktop report keeps nothing and fails closed rather than
1589
+ // publishing a window this parser cannot bound; every other arm keeps its whole console.
1590
+ const capture = kind === 'desktop'
1591
+ ? lines.findIndex((line) => line.includes('[Screenshot] First 16 bytes'))
1592
+ : lines.length;
1131
1593
  const series = [];
1132
- for (const line of reportConsoleLines(report)) {
1594
+ for (const line of lines.slice(0, Math.max(capture, 0))) {
1133
1595
  const prefix = 'TN_PROD_FRAME_SAMPLES:';
1134
1596
  const offset = line.indexOf(prefix);
1135
1597
  if (offset === -1) continue;
@@ -1142,7 +1604,7 @@ function frameSeriesFromReport(report) {
1142
1604
  return series.length === 0 ? undefined : series;
1143
1605
  }
1144
1606
 
1145
- export function assembleEvidence({ context, native, options, performanceBounds, project, runId, startedAt, web }) {
1607
+ export function assembleEvidence({ context, native, options, performanceBounds, project, resolutionScaleSetting, runId, startedAt, web }) {
1146
1608
  const arms = [web, native].filter((arm) => arm !== undefined);
1147
1609
  const regression = options.profile === REGRESSION_PROFILE;
1148
1610
  const expectedRuns = collectionLaunchPlan(options).filter((entry) => entry === 'steady').length;
@@ -1159,10 +1621,12 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1159
1621
  for (const [index, run] of arm.runs.entries()) {
1160
1622
  if (run.screenshot !== undefined) rawArtifacts.push({ content: run.screenshot, label: `production-render-${arm.kind}-${index + 1}` });
1161
1623
  if (run.report !== undefined) rawArtifacts.push({ content: JSON.stringify(run.report), label: `production-playtest-${arm.kind}-${index + 1}` });
1624
+ if (run.failure !== undefined) rawArtifacts.push({ content: JSON.stringify(run.failure), label: `production-run-failure-${arm.kind}-${index + 1}` });
1162
1625
  }
1163
1626
  for (const [index, startup] of arm.startups.entries()) {
1164
1627
  if (startup.screenshot !== undefined) rawArtifacts.push({ content: startup.screenshot, label: `production-first-frame-${arm.kind}-${index + 1}` });
1165
1628
  if (startup.report !== undefined) rawArtifacts.push({ content: JSON.stringify(startup.report), label: `production-startup-${arm.kind}-${index + 1}` });
1629
+ if (startup.failure !== undefined) rawArtifacts.push({ content: JSON.stringify(startup.failure), label: `production-startup-failure-${arm.kind}-${index + 1}` });
1166
1630
  }
1167
1631
  }
1168
1632
  const metricsByArm = new Map(arms.map((arm) => [arm.kind, aggregateMetrics(arm.runs, arm.startups, warmupFramesFor(options))]));
@@ -1197,7 +1661,7 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1197
1661
  }
1198
1662
  const artifactHashes = arms.map(({ artifactSha, bundleSha }) => `${artifactSha}:${bundleSha ?? artifactSha}`);
1199
1663
  const target = options.target;
1200
- const identity = identityFor(options, web, native, artifactHashes);
1664
+ const identity = identityFor(options, web, native, artifactHashes, resolutionScaleSetting);
1201
1665
  const evidence = {
1202
1666
  artifact: {
1203
1667
  applicationClass: target === 'desktop-pair' ? 'platformer-desktop-pair' : arms[0]?.applicationClass ?? 'platformer-production',
@@ -1206,9 +1670,14 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1206
1670
  },
1207
1671
  artifacts: [],
1208
1672
  budget: {
1209
- maxP99FrameMs: 33,
1210
- maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1211
- minMeanFps: target.includes('physical') ? 59.4 : 60,
1673
+ // The scaffolded platformer is judged by the default steady-state budget. An existing project
1674
+ // is judged only by the bounds its own scenario authors: a known ~40 fps game must not fail
1675
+ // before A/B on a default it never claimed.
1676
+ ...(options.project === undefined ? {
1677
+ maxP99FrameMs: 33,
1678
+ maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1679
+ minMeanFps: target.includes('physical') ? 59.4 : 60,
1680
+ } : {}),
1212
1681
  ...(regression ? {
1213
1682
  minDurationSeconds: REGRESSION_COLLECTION_PROFILE.durationSeconds,
1214
1683
  minFrameSamples: REGRESSION_COLLECTION_PROFILE.minFrameSamples,
@@ -1219,6 +1688,9 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1219
1688
  codes: [...new Set(codes)],
1220
1689
  evidenceClasses: ['production'],
1221
1690
  execution: {
1691
+ // Which clock the arms ran on, published because the two are not the same measurement: on a
1692
+ // frozen clock every presented frame repeats a standing state, so its rate is not a frame rate.
1693
+ clock: options.liveClock === true ? 'wall-clock' : 'fixed-step',
1222
1694
  coldStarts: options.coldStarts,
1223
1695
  ...(options.control === undefined ? {} : { control: options.control }),
1224
1696
  deviceSelected: options.device !== undefined,
@@ -1378,7 +1850,9 @@ export function postWarmupFrameSamples(samples, warmupFrames = 0) {
1378
1850
 
1379
1851
  export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1380
1852
  const intervals = [];
1381
- const frameIntervalsMs = [];
1853
+ const callbackIntervalsMs = [];
1854
+ const presentedIntervalsMs = [];
1855
+ const presentedStampsMs = [];
1382
1856
  const clockSamplesMs = [];
1383
1857
  const presentationSamplesMs = [];
1384
1858
  const runWindows = [];
@@ -1388,28 +1862,25 @@ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1388
1862
  .map(({ firstFrameMs }) => firstFrameMs);
1389
1863
  let timestampMs = 0;
1390
1864
  let sequence = 1;
1391
- let sampleCount = 0;
1392
- let hitchCount = 0;
1393
- let worstFrameMs;
1865
+ let callbackCount = 0;
1866
+ let presentedElapsedMs = 0;
1394
1867
  let missingClock = false;
1395
1868
  let missingPresentationClock = false;
1869
+ let unmeasurablePresentation = false;
1396
1870
  for (const run of runs) {
1397
1871
  let clockOrigin;
1398
1872
  let presentationOrigin;
1873
+ let lastPresentedMs;
1399
1874
  const postWarmupSamples = postWarmupFrameSamples(run.series ?? [], warmupFrames);
1400
1875
  let runDurationMs = 0;
1401
1876
  let runSampleCount = 0;
1402
1877
  for (const sample of postWarmupSamples) {
1403
1878
  if (typeof sample?.frameMs !== 'number') {
1404
- frameIntervalsMs.push(sample?.frameMs);
1879
+ callbackIntervalsMs.push(sample?.frameMs);
1405
1880
  continue;
1406
1881
  }
1407
- frameIntervalsMs.push(sample.frameMs);
1408
- sampleCount += 1;
1409
- runSampleCount += 1;
1410
- runDurationMs += sample.frameMs;
1411
- if (sample.frameMs > 33.3) hitchCount += 1;
1412
- worstFrameMs = worstFrameMs === undefined ? sample.frameMs : Math.max(worstFrameMs, sample.frameMs);
1882
+ callbackIntervalsMs.push(sample.frameMs);
1883
+ callbackCount += 1;
1413
1884
  if (Number.isFinite(sample.clockMs)) {
1414
1885
  clockOrigin ??= sample.clockMs;
1415
1886
  clockSamplesMs.push(timestampMs + sample.clockMs - clockOrigin);
@@ -1417,10 +1888,34 @@ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1417
1888
  missingClock = true;
1418
1889
  }
1419
1890
  if (Number.isFinite(sample.presentationMs)) {
1891
+ // The frame interval the budget is about is the gap between presented frames, and the rAF
1892
+ // timestamp is the frame. Both arms run three rAF callbacks per presented frame — the
1893
+ // engine loop, the UI hit-test pump and this instrumentation each register one — so a
1894
+ // `performance.now()` callback delta measures how the host spread its callbacks inside a
1895
+ // fixed display period: at its 95th percentile it is the idle remainder of that period, and
1896
+ // the arm that spends less per callback is the one that reads worse. The presented series
1897
+ // therefore advances only when the presentation stamp changes, and one frame's callbacks
1898
+ // collapse into the single interval they belong to. Every quantity the frame budget counts —
1899
+ // the per-second floor, the window's sample count, the worst frame and the hitch count —
1900
+ // counts this series, because a callback count reads three frames for every frame presented.
1901
+ if (lastPresentedMs !== undefined && sample.presentationMs !== lastPresentedMs) {
1902
+ const presentedDeltaMs = sample.presentationMs - lastPresentedMs;
1903
+ if (presentedDeltaMs > 0) {
1904
+ presentedIntervalsMs.push(presentedDeltaMs);
1905
+ runSampleCount += 1;
1906
+ runDurationMs += presentedDeltaMs;
1907
+ presentedElapsedMs += presentedDeltaMs;
1908
+ presentedStampsMs.push(presentedElapsedMs);
1909
+ } else {
1910
+ unmeasurablePresentation = true;
1911
+ }
1912
+ }
1913
+ lastPresentedMs = sample.presentationMs;
1420
1914
  presentationOrigin ??= sample.presentationMs;
1421
1915
  presentationSamplesMs.push(timestampMs + sample.presentationMs - presentationOrigin);
1422
1916
  } else {
1423
1917
  missingPresentationClock = true;
1918
+ unmeasurablePresentation = true;
1424
1919
  }
1425
1920
  if (sample.phases !== undefined && typeof sample.phases === 'object' && sample.phases !== null) {
1426
1921
  for (const [phase, value] of Object.entries(sample.phases)) {
@@ -1444,31 +1939,49 @@ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1444
1939
  }
1445
1940
  runWindows.push({ durationSeconds: runDurationMs / 1_000, sampleCount: runSampleCount });
1446
1941
  }
1942
+ // A sample the presentation clock could not place has no place in a cadence series, and a partial
1943
+ // one would publish a percentile of the frames that happened to survive. The series stays
1944
+ // unmeasured, which fails the timing budget and blocks a pair rather than judging a subset. The
1945
+ // windows go with it: a count of presented frames and a duration measured from the same voided
1946
+ // series are the same partial subset under two names.
1947
+ if (unmeasurablePresentation) presentedIntervalsMs.length = 0;
1447
1948
  const phaseP95ByName = Object.fromEntries(
1448
1949
  Object.entries(phaseSamples).map(([phase, samples]) => [phase, nearestRank(samples, 0.95)]),
1449
1950
  );
1951
+ const presentedFrames = presentedIntervalsMs.length;
1952
+ const presentedHitchCount = presentedIntervalsMs.filter((value) => value > 33.3).length;
1450
1953
  return {
1451
1954
  ...(clockSamplesMs.length === 0 ? {} : { clockSamplesMs }),
1452
- ...(sampleCount === 0 ? {} : { clockSource: missingClock ? 'missing' : 'monotonic-performance' }),
1453
- ...(frameIntervalsMs.length === 0 ? {} : { frameIntervalsMs }),
1454
- ...(hitchCount === 0 ? { hitchCount: 0 } : { hitchCount }),
1955
+ ...(callbackCount === 0 ? {} : { clockSource: missingClock ? 'missing' : 'monotonic-performance' }),
1956
+ ...(presentedFrames === 0 ? {} : { frameIntervalsMs: presentedIntervalsMs }),
1455
1957
  ...(intervals.length === 0 ? {} : { intervals }),
1456
1958
  ...(Object.keys(phaseP95ByName).length === 0 ? {} : {
1457
1959
  phaseP95ByName,
1458
1960
  ...(phaseP95ByName.render === undefined ? {} : { phaseP95Ms: phaseP95ByName.render }),
1459
1961
  }),
1460
1962
  ...(presentationSamplesMs.length === 0 ? {} : { presentationSamplesMs }),
1461
- ...(runWindows.length === 0 ? {} : { runWindows }),
1462
- ...(sampleCount === 0 ? {} : { presentationClockSource: missingPresentationClock ? 'missing' : 'raf-presentation', sampleCount, worstFrameMs }),
1963
+ ...(runWindows.length === 0 || unmeasurablePresentation ? {} : { runWindows }),
1964
+ ...(callbackCount === 0 ? {} : { presentationClockSource: missingPresentationClock ? 'missing' : 'raf-presentation' }),
1463
1965
  ...(startupSamplesMs.length === 0 ? {} : { startupSamplesMs, startupMs: startupSamplesMs[0] }),
1464
1966
  ...(timestampMs === 0 ? {} : { durationSeconds: timestampMs / 1_000 }),
1465
1967
  ...(startupSamplesMs.length === 0 ? {} : { startupP95Ms: nearestRank(startupSamplesMs, 0.95) }),
1466
- ...(frameIntervalsMs.length === 0 ? {} : {
1467
- meanFps: meanFps(frameIntervalsMs),
1468
- p50FrameMs: nearestRank(frameIntervalsMs, 0.5),
1469
- p95FrameMs: nearestRank(frameIntervalsMs, 0.95),
1470
- p99FrameMs: nearestRank(frameIntervalsMs, 0.99),
1968
+ // The presented-frame quantities publish together or not at all: a sample count beside a
1969
+ // percentile of a different series is how a 3x callback count reads as a collected window.
1970
+ ...(presentedFrames === 0 ? {} : {
1971
+ hitchCount: presentedHitchCount,
1972
+ oneSecondFps: oneSecondFrameFloors(presentedStampsMs),
1973
+ sampleCount: presentedFrames,
1974
+ worstFrameMs: Math.max(...presentedIntervalsMs),
1471
1975
  }),
1976
+ ...(presentedFrames === 0 ? {} : {
1977
+ meanFps: meanFps(presentedIntervalsMs),
1978
+ p50FrameMs: nearestRank(presentedIntervalsMs, 0.5),
1979
+ p95FrameMs: nearestRank(presentedIntervalsMs, 0.95),
1980
+ p99FrameMs: nearestRank(presentedIntervalsMs, 0.99),
1981
+ }),
1982
+ ...(unmeasurableIntervalCount(callbackIntervalsMs) === 0
1983
+ ? {}
1984
+ : { unmeasurableCallbackIntervals: unmeasurableIntervalCount(callbackIntervalsMs) }),
1472
1985
  ...(intervals.some(({ drawCalls }) => drawCalls !== undefined) ? { drawCalls: Math.max(...intervals.flatMap(({ drawCalls }) => drawCalls === undefined ? [] : [drawCalls])) } : {}),
1473
1986
  ...(intervals.some(({ triangles }) => triangles !== undefined) ? { triangles: Math.max(...intervals.flatMap(({ triangles }) => triangles === undefined ? [] : [triangles])) } : {}),
1474
1987
  };
@@ -1487,13 +2000,37 @@ function pairMetrics(metrics) {
1487
2000
  };
1488
2001
  }
1489
2002
 
1490
- function identityFor(options, web, native, artifactHashes) {
2003
+ /**
2004
+ * The display a web frame rate was read from.
2005
+ *
2006
+ * `observations.hardwareIdentity` was the key this used to read and no producer has ever written it,
2007
+ * so every web artifact published an identity with no GPU in it. `webDisplay` is published from the
2008
+ * decision the runner itself made, and it is the field that separates this host's two web
2009
+ * collections: 33.97 fps on the private display, 163.45 fps on the session display.
2010
+ *
2011
+ * The playtest report retains its observed WebGPU adapter in the pipeline census. Repeated
2012
+ * workload runs must agree before one adapter can identify the whole rate sample.
2013
+ */
2014
+ export function webRateIdentity(web) {
2015
+ const display = web?.display;
2016
+ const adapters = web?.runs?.map((run) => run?.report?.observations?.pipelineCensus?.adapter?.identity);
2017
+ const adapter = adapters?.length > 0 && adapters.every((identity) => typeof identity === 'string' && identity !== 'unavailable' && identity === adapters[0])
2018
+ ? adapters[0]
2019
+ : undefined;
2020
+ return {
2021
+ ...(display === undefined ? {} : { webDisplay: display.kind === 'existing' ? `session:${display.display}` : display.kind }),
2022
+ ...(adapter === undefined ? {} : { webAdapter: adapter }),
2023
+ };
2024
+ }
2025
+
2026
+ function identityFor(options, web, native, artifactHashes, resolutionScaleSetting) {
1491
2027
  const common = {
1492
2028
  // Only observed hardware data may certify a promoted comparison. Missing fields remain absent.
1493
- ...(web?.runs[0]?.report?.observations?.hardwareIdentity ?? native?.runs[0]?.report?.observations?.hardwareIdentity ?? {}),
2029
+ ...webRateIdentity(web),
1494
2030
  workloadHash: web?.workloadHash ?? native?.workloadHash,
1495
2031
  renderHeight: options.renderSize.height,
1496
2032
  renderWidth: options.renderSize.width,
2033
+ ...(resolutionScaleSetting === undefined ? {} : { resolutionScaleSetting }),
1497
2034
  };
1498
2035
  if (options.target === 'desktop-pair') {
1499
2036
  return {
@@ -1584,7 +2121,10 @@ function profileCommand(options) {
1584
2121
  `--repetitions ${options.repetitions}`,
1585
2122
  ...(options.device === undefined ? [] : ['--device <selected>']),
1586
2123
  ...(options.hostedSoftware ? ['--hosted-software'] : []),
2124
+ ...(options.liveClock === true ? ['--live-clock'] : []),
1587
2125
  ...(options.prebuiltArtifact === undefined ? [] : ['--prebuilt-artifact <existing-build>']),
2126
+ ...(options.project === undefined ? [] : ['--project <existing-project>']),
2127
+ ...(options.scenario === undefined ? [] : ['--scenario <production-scenario>']),
1588
2128
  ].join(' ');
1589
2129
  }
1590
2130
 
@@ -1629,8 +2169,12 @@ async function createFixtureControlEvidence(options, context, runId) {
1629
2169
  }
1630
2170
 
1631
2171
  async function collectFixtureFrameSeries(control) {
2172
+ // The real producers stamp every sample with the rAF presentation timestamp, so the fixture that
2173
+ // stands in for them carries one too: the judge reads presented cadence, and a fixture without
2174
+ // presentation identity would now be (correctly) unmeasured rather than a passing control.
1632
2175
  const intervals = Array.from({ length: 120 }, (_, index) => ({
1633
2176
  frameMs: 16.5,
2177
+ presentationMs: index * 16.5,
1634
2178
  sequence: index + 1,
1635
2179
  timestampMs: index * 16.5,
1636
2180
  }));
@@ -1638,7 +2182,9 @@ async function collectFixtureFrameSeries(control) {
1638
2182
  for (const index of [intervals.length - 2, intervals.length - 1]) {
1639
2183
  const startedAt = performance.now();
1640
2184
  await new Promise((resolve) => setTimeout(resolve, SLOW_FRAME_DELAY_MS));
1641
- intervals[index].frameMs = Math.max(SLOW_FRAME_DELAY_MS, performance.now() - startedAt);
2185
+ const slowFrameMs = Math.max(SLOW_FRAME_DELAY_MS, performance.now() - startedAt);
2186
+ intervals[index].frameMs = slowFrameMs;
2187
+ intervals[index].presentationMs = intervals[index - 1].presentationMs + slowFrameMs;
1642
2188
  intervals[index].timestampMs = intervals[index - 1].timestampMs + intervals[index - 1].frameMs;
1643
2189
  }
1644
2190
  return intervals;
@@ -1762,12 +2308,32 @@ async function readOptionalArtifact(path) {
1762
2308
  }
1763
2309
  }
1764
2310
 
1765
- async function nativeArtifactPath(project, target) {
2311
+ export async function nativeArtifactPath(project, target) {
1766
2312
  const directory = join(project, 'dist-native');
1767
- const entries = await readdir(directory);
1768
- const candidate = entries.find((entry) => target === 'ios' ? entry.endsWith('.app') : target === 'android' ? entry.endsWith('.apk') : true);
2313
+ const entries = (await readdir(directory, { withFileTypes: true }))
2314
+ .slice()
2315
+ .sort((left, right) => left.name.localeCompare(right.name));
2316
+ const candidate = target === 'ios'
2317
+ ? entries.find((entry) => entry.isDirectory() && entry.name.endsWith('.app'))
2318
+ : target === 'android'
2319
+ ? entries.find((entry) => entry.isFile() && entry.name.endsWith('.apk'))
2320
+ : await desktopExecutableEntry(directory, entries);
1769
2321
  if (candidate === undefined) throw new ProductionEvidenceError('TN_PROD_NATIVE_ARTIFACT_MISSING', `The scaffolded ${target} build produced no native artifact.`);
1770
- return join(directory, candidate);
2322
+ return join(directory, candidate.name);
2323
+ }
2324
+
2325
+ // A desktop build stages the `ui/` web bundle beside the executable, so the artifact is the one
2326
+ // regular file the host can run - never the first directory that happens to sort first.
2327
+ async function desktopExecutableEntry(directory, entries) {
2328
+ for (const entry of entries) {
2329
+ if (!entry.isFile()) continue;
2330
+ if (process.platform === 'win32') {
2331
+ if (entry.name.endsWith('.exe')) return entry;
2332
+ continue;
2333
+ }
2334
+ if (((await stat(join(directory, entry.name))).mode & 0o111) !== 0) return entry;
2335
+ }
2336
+ return undefined;
1771
2337
  }
1772
2338
 
1773
2339
  async function playtestRunnerPath(project, tools) {
@@ -1788,7 +2354,7 @@ async function installAndroidArtifact(apk, device) {
1788
2354
  });
1789
2355
  const args = [...(device === undefined ? [] : ['-s', device]), 'install', '-r', apk];
1790
2356
  const result = await runCommand('adb', args, commandRoot);
1791
- if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_ANDROID_INSTALL_FAILED', 'Installing the scaffolded Android platformer failed.');
2357
+ if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_ANDROID_INSTALL_FAILED', `Installing the scaffolded Android platformer failed.${failureSuffix(result)}`);
1792
2358
  }
1793
2359
 
1794
2360
  async function hashPath(path) {
@@ -1842,10 +2408,7 @@ function isNonBlankFrame(value) {
1842
2408
  }
1843
2409
 
1844
2410
  async function browserCommand(args) {
1845
- if (process.platform !== 'linux' || process.env.DISPLAY !== undefined) return { args, command: process.execPath };
1846
- const result = await runCommand('which', ['xvfb-run'], commandRoot);
1847
- if (result.status !== 0) return { args, command: process.execPath };
1848
- return { args: ['-a', '-s', '-screen 0 1600x900x24', process.execPath, ...args], command: 'xvfb-run' };
2411
+ return privateDisplayCommand(process.execPath, args);
1849
2412
  }
1850
2413
 
1851
2414
  async function availablePort() {
@@ -1860,7 +2423,7 @@ async function availablePort() {
1860
2423
  return address.port;
1861
2424
  }
1862
2425
 
1863
- async function runCommand(command, args, cwd, env = undefined, timeout = 120_000) {
2426
+ export async function runCommand(command, args, cwd, env = undefined, timeout = 120_000) {
1864
2427
  const started = performance.now();
1865
2428
  try {
1866
2429
  const result = await execFileAsync(command, args, {
@@ -1870,17 +2433,30 @@ async function runCommand(command, args, cwd, env = undefined, timeout = 120_000
1870
2433
  maxBuffer: 32 * 1024 * 1024,
1871
2434
  timeout,
1872
2435
  });
1873
- return { durationMs: performance.now() - started, status: 0, stderr: result.stderr, stdout: result.stdout };
2436
+ return { durationMs: performance.now() - started, status: 0, stderr: result.stderr, stdout: result.stdout, timeout, timedOut: false };
1874
2437
  } catch (error) {
1875
2438
  return {
1876
2439
  durationMs: performance.now() - started,
1877
2440
  status: typeof error?.code === 'number' ? error.code : 2,
1878
2441
  stderr: error?.stderr ?? '',
1879
2442
  stdout: error?.stdout ?? '',
2443
+ timeout,
2444
+ timedOut: error?.killed === true,
1880
2445
  };
1881
2446
  }
1882
2447
  }
1883
2448
 
2449
+ export function failureSuffix(result) {
2450
+ if (result.timedOut === true) return `: timed out after ${Math.round(result.timeout / 1_000)} s`;
2451
+ const lines = [result.stderr, result.stdout]
2452
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
2453
+ .join('\n')
2454
+ .split('\n')
2455
+ .filter((line) => line.trim().length > 0)
2456
+ .slice(-20);
2457
+ return lines.length === 0 ? '' : `\n${lines.join('\n')}`;
2458
+ }
2459
+
1884
2460
  async function removeMailbox(root) {
1885
2461
  await Promise.all([
1886
2462
  rm(join(root, 'tn-playtest-request.json'), { force: true }),