@threenative/runtime-native 0.3.0 → 0.3.1

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.
@@ -16,10 +16,12 @@ import { suppressPlayProtectOnAdbInstalls } from './device-preflight.mjs';
16
16
  import {
17
17
  PRODUCTION_EVIDENCE_VERSION,
18
18
  ProductionEvidenceError,
19
+ REGRESSION_COLLECTION_PROFILE,
19
20
  meanFps,
20
21
  nearestRank,
21
22
  sha256,
22
23
  writeProductionEvidence,
24
+ sanitizeManifest,
23
25
  } from './production-evidence.mjs';
24
26
 
25
27
  const execFileAsync = promisify(execFile);
@@ -52,6 +54,8 @@ const FRAME_SAMPLE_BATCH_SIZE = 30;
52
54
  // Android logcat truncates long lines, so native samples use a smaller JSON batch.
53
55
  const NATIVE_FRAME_SAMPLE_BATCH_SIZE = 5;
54
56
  const DESKTOP_SCREENSHOT_TIMEOUT_MS = 5_000;
57
+ const PRODUCTION_PROFILE = 'production';
58
+ const REGRESSION_PROFILE = 'regression';
55
59
 
56
60
  function installedPackageFile(packageName, file) {
57
61
  try {
@@ -86,40 +90,61 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
86
90
  control: undefined,
87
91
  device: undefined,
88
92
  duration: 60,
93
+ hostedSoftware: false,
89
94
  out: '.runtime/prd064/production',
95
+ prebuiltArtifact: undefined,
90
96
  physicalEvidence: undefined,
91
- renderSize: { height: 1080, width: 1920 },
97
+ profile: PRODUCTION_PROFILE,
98
+ renderSize: undefined,
92
99
  repetitions: 3,
93
100
  sourceSha: undefined,
94
101
  target: undefined,
95
102
  warmup: 60,
96
103
  };
104
+ const explicit = new Set();
97
105
  for (let index = 0; index < argv.length; index += 1) {
98
106
  const flag = argv[index];
99
107
  if (flag === '--') continue;
100
- if (flag === '--audio-evidence') options.audioEvidence = nextValue(argv, ++index, flag);
101
- else if (flag === '--cold-starts') options.coldStarts = positiveInteger(nextValue(argv, ++index, flag), flag);
102
- else if (flag === '--config') options.config = nextValue(argv, ++index, flag);
103
- else if (flag === '--control') options.control = nextValue(argv, ++index, flag);
104
- else if (flag === '--device') options.device = nextValue(argv, ++index, flag);
105
- else if (flag === '--duration') options.duration = positiveNumber(nextValue(argv, ++index, flag), flag);
106
- else if (flag === '--out') options.out = nextValue(argv, ++index, flag);
107
- else if (flag === '--physical-evidence') options.physicalEvidence = nextValue(argv, ++index, flag);
108
- else if (flag === '--render-size') options.renderSize = parseRenderSize(nextValue(argv, ++index, flag));
109
- else if (flag === '--repetitions') options.repetitions = positiveInteger(nextValue(argv, ++index, flag), flag);
110
- else if (flag === '--source-sha') options.sourceSha = nextValue(argv, ++index, flag);
111
- else if (flag === '--target') options.target = nextValue(argv, ++index, flag);
112
- else if (flag === '--warmup') options.warmup = positiveNumber(nextValue(argv, ++index, flag), flag);
108
+ if (flag === '--audio-evidence') { explicit.add('audioEvidence'); options.audioEvidence = nextValue(argv, ++index, flag); }
109
+ else if (flag === '--cold-starts') { explicit.add('coldStarts'); options.coldStarts = positiveInteger(nextValue(argv, ++index, flag), flag); }
110
+ else if (flag === '--config') { explicit.add('config'); options.config = nextValue(argv, ++index, flag); }
111
+ else if (flag === '--control') { explicit.add('control'); options.control = nextValue(argv, ++index, flag); }
112
+ else if (flag === '--device') { explicit.add('device'); options.device = nextValue(argv, ++index, flag); }
113
+ else if (flag === '--duration') { explicit.add('duration'); options.duration = positiveNumber(nextValue(argv, ++index, flag), flag); }
114
+ else if (flag === '--hosted-software') { options.hostedSoftware = true; }
115
+ else if (flag === '--out') { explicit.add('out'); options.out = nextValue(argv, ++index, flag); }
116
+ else if (flag === '--prebuilt-artifact') { explicit.add('prebuiltArtifact'); options.prebuiltArtifact = nextValue(argv, ++index, flag); }
117
+ else if (flag === '--physical-evidence') { explicit.add('physicalEvidence'); options.physicalEvidence = nextValue(argv, ++index, flag); }
118
+ else if (flag === '--profile') options.profile = nextValue(argv, ++index, flag);
119
+ else if (flag === '--regression') options.profile = REGRESSION_PROFILE;
120
+ else if (flag === '--render-size') { explicit.add('renderSize'); options.renderSize = parseRenderSize(nextValue(argv, ++index, flag)); }
121
+ else if (flag === '--repetitions') { explicit.add('repetitions'); options.repetitions = positiveInteger(nextValue(argv, ++index, flag), flag); }
122
+ else if (flag === '--source-sha') { explicit.add('sourceSha'); options.sourceSha = nextValue(argv, ++index, flag); }
123
+ else if (flag === '--target') { explicit.add('target'); options.target = nextValue(argv, ++index, flag); }
124
+ else if (flag === '--warmup') { explicit.add('warmup'); options.warmup = positiveNumber(nextValue(argv, ++index, flag), flag); }
113
125
  else if (flag === '--help') return { ...options, help: true };
114
126
  else throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', `Unknown production profile option '${flag}'.`);
115
127
  }
116
128
  if (options.target === undefined) throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', 'Production profile requires --target.');
129
+ if (options.profile === REGRESSION_PROFILE) {
130
+ if (!explicit.has('coldStarts')) options.coldStarts = REGRESSION_COLLECTION_PROFILE.coldStarts;
131
+ if (!explicit.has('duration')) options.duration = REGRESSION_COLLECTION_PROFILE.durationSeconds;
132
+ if (!explicit.has('out')) options.out = '.runtime/prd358/regression';
133
+ if (!explicit.has('repetitions')) options.repetitions = 1;
134
+ if (!explicit.has('warmup')) options.warmup = 5;
135
+ }
117
136
  return validateProductionOptions(options);
118
137
  }
119
138
 
120
139
  export function validateProductionOptions(input) {
121
140
  const options = normalizeOptions(input);
122
141
  if (options.help) return options;
142
+ if (options.profile === REGRESSION_PROFILE && (options.repetitions !== 1 || options.coldStarts !== 5 || options.duration < 30 || options.duration > 60 || options.warmup > 10)) {
143
+ throw new ProductionEvidenceError('TN_PROD_PAIR_UNIT', 'Each regression arm requires one 30–60 second steady launch, five startup launches, and at most ten seconds warmup.');
144
+ }
145
+ if (options.profile !== PRODUCTION_PROFILE && options.profile !== REGRESSION_PROFILE) {
146
+ throw new ProductionEvidenceError('TN_PROD_PROFILE_UNSUPPORTED', `Production profile '${options.profile}' is not supported.`);
147
+ }
123
148
  if (!supportedTargets.has(options.target)) {
124
149
  throw new ProductionEvidenceError('TN_PROD_TARGET_UNSUPPORTED', `Production target '${options.target}' is not supported.`);
125
150
  }
@@ -138,6 +163,9 @@ export function validateProductionOptions(input) {
138
163
  if (physicalTargets.has(options.target) && options.device === undefined) {
139
164
  throw new ProductionEvidenceError('TN_PROD_DEVICE_REQUIRED', `Target '${options.target}' requires --device.`);
140
165
  }
166
+ if (options.hostedSoftware && (physicalTargets.has(options.target) || options.target === 'fixture')) {
167
+ throw new ProductionEvidenceError('TN_PROD_HOSTED_SOFTWARE_UNSUPPORTED', 'Hosted-software evaluation is only valid for non-physical platform probes.');
168
+ }
141
169
  if (options.target === 'desktop-pair' && options.control === 'slow-native') return options;
142
170
  if (options.control === 'slow-native' && options.target !== 'desktop-pair') {
143
171
  throw new ProductionEvidenceError('TN_PROD_CONTROL_UNSUPPORTED', "The 'slow-native' control requires --target desktop-pair.");
@@ -158,6 +186,7 @@ export async function runProductionProfile(input, dependencies = {}) {
158
186
  const sourceState = await currentSourceState();
159
187
  const requiredSourceSha = sourceState.sha;
160
188
  const sourceSha = options.sourceSha ?? requiredSourceSha;
189
+ options.sourceSha = sourceSha;
161
190
  const runId = `${options.target}-${Date.now()}`;
162
191
  const physicalEvidence = await readPhysicalEvidence(options.physicalEvidence);
163
192
  const audioEvidence = await readOptionalArtifact(options.audioEvidence);
@@ -190,6 +219,7 @@ export async function collectProduction(options, context, runId) {
190
219
  const startedAt = new Date().toISOString();
191
220
  try {
192
221
  await scaffoldPlatformer(project, tools);
222
+ tools.workloadSourceHash = await hashPath(join(project, 'src'));
193
223
  const scenarios = await writeRunScenarios(project, options);
194
224
  const artifactsRoot = join(project, 'artifacts', 'production');
195
225
  await mkdir(artifactsRoot, { recursive: true });
@@ -217,20 +247,28 @@ export async function collectProduction(options, context, runId) {
217
247
  function normalizeOptions(input = {}) {
218
248
  const renderSize = typeof input.renderSize === 'string' ? parseRenderSize(input.renderSize) : input.renderSize;
219
249
  const target = input.target === 'desktop-web' ? 'web' : input.target;
250
+ const profile = input.profile ?? PRODUCTION_PROFILE;
251
+ const regression = profile === REGRESSION_PROFILE;
252
+ const defaultRenderSize = input.hostedSoftware === true && target === 'desktop'
253
+ ? { height: 720, width: 1280 }
254
+ : { height: 1080, width: 1920 };
220
255
  return {
221
256
  audioEvidence: input.audioEvidence,
222
- coldStarts: input.coldStarts ?? 1,
257
+ coldStarts: input.coldStarts ?? (regression ? REGRESSION_COLLECTION_PROFILE.coldStarts : 1),
223
258
  control: input.control,
224
259
  device: input.device,
225
- duration: input.duration ?? 60,
260
+ duration: input.duration ?? (regression ? REGRESSION_COLLECTION_PROFILE.durationSeconds : 60),
261
+ hostedSoftware: input.hostedSoftware === true,
226
262
  help: input.help,
227
- out: input.out ?? '.runtime/prd064/production',
263
+ out: input.out ?? (regression ? '.runtime/prd358/regression' : '.runtime/prd064/production'),
264
+ prebuiltArtifact: input.prebuiltArtifact === undefined ? undefined : resolve(input.prebuiltArtifact),
228
265
  physicalEvidence: input.physicalEvidence,
229
- renderSize: renderSize ?? { height: 1080, width: 1920 },
230
- repetitions: input.repetitions ?? 3,
266
+ renderSize: renderSize ?? defaultRenderSize,
267
+ profile,
268
+ repetitions: input.repetitions ?? (regression ? 1 : 3),
231
269
  sourceSha: input.sourceSha,
232
270
  target,
233
- warmup: input.warmup ?? 60,
271
+ warmup: input.warmup ?? (regression ? 5 : 60),
234
272
  };
235
273
  }
236
274
 
@@ -289,6 +327,7 @@ async function packLocalPackage(directory, destination) {
289
327
 
290
328
  function packageSourceFlag(name) {
291
329
  if (name === 'create-threenative') return '--cli-package';
330
+ if (name === 'threenative-blender-mcp') return '--blender-mcp-package';
292
331
  if (name === 'threenative-engine-mcp') return '--engine-mcp-package';
293
332
  if (name.startsWith('@threenative/')) {
294
333
  const suffix = name.slice('@threenative/'.length);
@@ -297,15 +336,32 @@ function packageSourceFlag(name) {
297
336
  throw new Error(`TN_PROD_PACKAGE_FLAG_UNSUPPORTED: ${name}`);
298
337
  }
299
338
 
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
+ };
351
+ }
352
+
300
353
  export async function writeRunScenarios(project, options) {
301
354
  const source = JSON.parse(await readFile(join(project, platformerScenario), 'utf8'));
302
355
  const sourceAssertions = source.assert && typeof source.assert === 'object' && !Array.isArray(source.assert)
303
356
  ? source.assert
304
357
  : {};
305
358
  const { performance: performanceBounds, ...playtestAssertions } = sourceAssertions;
306
- const workloadAssertions = Object.keys(playtestAssertions).length === 0
359
+ const baseWorkloadAssertions = Object.keys(playtestAssertions).length === 0
307
360
  ? { diagnostics: { noConsoleErrors: true, runtimeReady: true } }
308
361
  : playtestAssertions;
362
+ const workloadAssertions = options.profile === REGRESSION_PROFILE
363
+ ? { ...baseWorkloadAssertions, movement: { entity: 'player', minDistance: 0.1 } }
364
+ : baseWorkloadAssertions;
309
365
  const { assert: _sourceAssertions, ...scenarioSource } = source;
310
366
  const workloadFrames = Math.max(1, Math.ceil(options.duration * 60));
311
367
  const warmupFrames = Math.max(0, Math.ceil(options.warmup * 60));
@@ -341,10 +397,15 @@ export async function writeRunScenarios(project, options) {
341
397
  };
342
398
  const nativeWorkload = {
343
399
  ...workload,
344
- artifacts: { screenshots: nativeTarget === 'desktop' ? 'after' : false },
400
+ assert: nativeDiagnostics(workload.assert),
401
+ artifacts: {
402
+ screenshots: options.profile === REGRESSION_PROFILE || nativeTarget === 'desktop'
403
+ ? 'after'
404
+ : false,
405
+ },
345
406
  steps: nativeWorkloadSteps,
346
407
  };
347
- const nativeStartup = { ...startup, artifacts: { screenshots: 'after' } };
408
+ const nativeStartup = { ...startup, assert: nativeDiagnostics(startup.assert), artifacts: { screenshots: 'after' } };
348
409
  const workloadPath = join(project, 'playtests/production-performance.run.playtest.json');
349
410
  const startupPath = join(project, 'playtests/production-startup.run.playtest.json');
350
411
  const nativeWorkloadPath = join(project, 'playtests/production-performance.native.playtest.json');
@@ -363,7 +424,7 @@ export async function writeRunScenarios(project, options) {
363
424
  }
364
425
 
365
426
  async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
366
- const markerServer = await createFrameMarkerServer();
427
+ const markerServer = await createFrameMarkerServer(options.profile === REGRESSION_PROFILE ? 41778 : 0);
367
428
  try {
368
429
  await installWebProfileEntry(project, markerServer.url, options.control, warmupFramesFor(options));
369
430
  const build = await runCommand('pnpm', ['run', 'build:web'], project);
@@ -374,7 +435,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
374
435
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
375
436
  const startup = await runWebScenario(project, scenarios.startupPath, join(artifactsRoot, `web-startup-${coldStart + 1}`), markerServer, tools.playtestCli);
376
437
  startups.push(startup);
377
- for (let repetition = 0; repetition < options.repetitions; repetition += 1) {
438
+ for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
378
439
  runs.push(await runWebScenario(
379
440
  project,
380
441
  scenarios.workloadPath,
@@ -386,6 +447,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
386
447
  }
387
448
  return {
388
449
  artifactSha,
450
+ workloadHash: await workloadHashFor(project, tools.workloadSourceHash),
389
451
  applicationClass: 'platformer-web-build',
390
452
  driverClass: 'playwright-chromium-webgpu',
391
453
  kind: 'web',
@@ -407,7 +469,7 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
407
469
  '--artifacts', relativeArtifact,
408
470
  '--browser-recipe', 'webgpu',
409
471
  '--project', project,
410
- '--server-command', `pnpm dev --host 127.0.0.1 --port ${port} --strictPort`,
472
+ '--server-command', `pnpm exec vite preview --host 127.0.0.1 --port ${port} --strictPort`,
411
473
  '--timeout', '30000',
412
474
  '--url', `http://127.0.0.1:${port}`,
413
475
  ];
@@ -430,7 +492,7 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
430
492
  async function collectNative(project, scenarios, artifactsRoot, options, tools) {
431
493
  const target = options.target === 'desktop-pair' || options.target === 'desktop' ? 'desktop' : options.target.startsWith('ios') ? 'ios' : 'android';
432
494
  await installNativeProfileEntry(project, target, options);
433
- const build = await runCommand('pnpm', ['run', `build:${target}`], project);
495
+ const build = await prepareNativeWorkload(project, target, options);
434
496
  if (build.status !== 0) {
435
497
  const details = [build.stdout, build.stderr]
436
498
  .filter((value) => typeof value === 'string' && value.trim().length > 0)
@@ -441,14 +503,14 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
441
503
  `The scaffolded platformer ${target} build failed.${details.length === 0 ? '' : `\n${details.slice(-4_000)}`}`,
442
504
  );
443
505
  }
444
- const artifactPath = await nativeArtifactPath(project, target);
506
+ const artifactPath = options.prebuiltArtifact ?? await nativeArtifactPath(project, target);
445
507
  const artifactSha = await hashPath(artifactPath);
446
508
  const runs = [];
447
509
  const startups = [];
448
510
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
449
511
  const startup = await runNativeScenario(project, target, scenarios.nativeStartupPath, join(artifactsRoot, `native-startup-${coldStart + 1}`), options, artifactPath, tools);
450
512
  startups.push(startup);
451
- for (let repetition = 0; repetition < options.repetitions; repetition += 1) {
513
+ for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
452
514
  runs.push(await runNativeScenario(
453
515
  project,
454
516
  target,
@@ -462,6 +524,8 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
462
524
  }
463
525
  return {
464
526
  artifactSha,
527
+ workloadHash: build.workloadHash ?? await workloadHashFor(project, tools.workloadSourceHash),
528
+ bundleSha: build.bundleSha ?? await hashPath(join(project, '.threenative/build/game.js')),
465
529
  applicationClass: `platformer-${target}-build`,
466
530
  driverClass: `threenative-${target}-runtime`,
467
531
  kind: target,
@@ -482,9 +546,12 @@ async function runNativeScenario(project, target, scenarioPath, artifactDirector
482
546
  if (target === 'android') await installAndroidArtifact(artifactPath, options.device);
483
547
  // The game declares its identity in `threenative.config.ts` and packaging resolves it; profiling
484
548
  // launches whatever packaging shipped, so it reads the id from there instead of restating one.
485
- const appId = readAndroidConfig(profileConfigPath(project, options.config)).app.id;
549
+ const appId = options.prebuiltArtifact === undefined
550
+ ? readAndroidConfig(profileConfigPath(project, options.config)).app.id
551
+ : (await readPrebuiltWorkload(options.prebuiltArtifact, target, options)).appId;
486
552
  const config = {
487
553
  android: { activity: 'com.threenative.runtime.MystralActivity', packageName: appId },
554
+ allowSoftwareAdapter: options.hostedSoftware,
488
555
  artifactDirectory,
489
556
  device: options.device,
490
557
  headless: true,
@@ -530,15 +597,11 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
530
597
  await removeMailbox(mailboxRoot);
531
598
  const requestPath = join(mailboxRoot, 'tn-playtest-request.json');
532
599
  const responsePath = join(mailboxRoot, 'tn-playtest-response.json');
533
- const screenshotRequestPath = join(mailboxRoot, 'tn-production-screenshot-request.json');
534
600
  const runner = await import(pathToFileURL(modulePath).href);
535
- const mailbox = {
536
- read: async (path) => readFile(path, 'utf8').catch((error) => error?.code === 'ENOENT' ? undefined : Promise.reject(error)),
537
- remove: async (path) => rm(path, { force: true }).catch(() => undefined),
538
- write: async (path, contents) => writeFile(path, contents, 'utf8'),
539
- };
540
- const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath });
541
- const driver = createDesktopDriver(artifactPath, project, options, screenshotRequestPath);
601
+ const mailbox = new runner.LocalDeviceMailbox();
602
+ const timeoutMs = 30_000;
603
+ const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath }, timeoutMs);
604
+ const driver = createDesktopDriver(artifactPath, project, options, mailboxRoot);
542
605
  const transport = {
543
606
  capabilities: innerTransport.capabilities,
544
607
  call: innerTransport.call.bind(innerTransport),
@@ -550,12 +613,13 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
550
613
  waitForBridge: innerTransport.waitForBridge.bind(innerTransport),
551
614
  };
552
615
  const config = {
616
+ allowSoftwareAdapter: options.hostedSoftware,
553
617
  artifactDirectory,
554
618
  headless: true,
555
619
  projectPath: project,
556
620
  scenarioPath: relative(project, scenarioPath),
557
621
  target: 'android',
558
- timeoutMs: 30_000,
622
+ timeoutMs,
559
623
  trace: false,
560
624
  url: 'http://127.0.0.1:41777',
561
625
  };
@@ -577,24 +641,51 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
577
641
  firstFrameMsFromReport(report, startedAt),
578
642
  frameSeriesFromReport(report),
579
643
  );
580
- } catch {
581
- await driver.stop();
582
- return { elapsedMs: performance.now() - started, report: undefined, screenshot: undefined, series: undefined, status: 2 };
644
+ } catch (error) {
645
+ let cleanupError;
646
+ try {
647
+ await driver.stop();
648
+ } catch (error) {
649
+ cleanupError = error;
650
+ }
651
+ return desktopFailureRun(error, await driver.captureConsole(), performance.now() - started, cleanupError);
583
652
  }
584
653
  }
585
654
 
655
+ export function desktopFailureRun(error, consoleOutput, elapsedMs, cleanupError = undefined) {
656
+ const retain = (value, fallback) => {
657
+ try { return sanitizeManifest(value); } catch { return fallback; }
658
+ };
659
+ const diagnostic = cleanupError?.diagnostic ?? error?.diagnostic;
660
+ return {
661
+ elapsedMs, status: 2, screenshot: undefined, series: undefined,
662
+ report: {
663
+ pass: false, target: 'desktop', assertionResults: [],
664
+ diagnostics: [retain(diagnostic ?? {
665
+ code: 'TN_PROD_PLAYTEST_FAILED', severity: 'error',
666
+ message: error instanceof Error ? error.message : String(error),
667
+ }, { code: 'TN_PROD_REDACTION', severity: 'error', message: 'Unsafe native error details withheld.' })],
668
+ observations: { console: consoleOutput.map((entry) => retain(entry, {
669
+ type: 'error', text: 'TN_PROD_REDACTION: unsafe native console entry withheld.',
670
+ })) },
671
+ },
672
+ };
673
+ }
674
+
586
675
  export function profileConfigPath(project, configPath = undefined) {
587
676
  return configPath ?? join(project, '.threenative', 'build', 'config.json');
588
677
  }
589
678
 
590
- function createDesktopDriver(artifactPath, project, options, screenshotRequestPath) {
679
+ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
591
680
  let child;
592
681
  let output = '';
682
+ let stopping;
683
+ const screenshotRequestPath = join(mailboxRoot, 'tn-playtest-screenshot-request.txt');
593
684
  return {
594
685
  captureConsole: async () => output.split(/\r?\n/u).filter(Boolean).map((text) => ({ text, type: /\b(?:Error|FAILED|FATAL)\b/u.test(text) ? 'error' : 'log' })),
595
686
  isAlive: async () => child !== undefined && child.exitCode === null,
596
687
  launch: async () => {
597
- child = spawnNative(artifactPath, project, options);
688
+ child = spawnNative(artifactPath, project, options, mailboxRoot);
598
689
  child.stdout?.on('data', (chunk) => { output += chunk.toString(); });
599
690
  child.stderr?.on('data', (chunk) => { output += chunk.toString(); });
600
691
  await new Promise((resolve, reject) => {
@@ -607,7 +698,7 @@ function createDesktopDriver(artifactPath, project, options, screenshotRequestPa
607
698
  removeFile: async (path) => rm(path, { force: true }).catch(() => undefined),
608
699
  screenshot: async (path) => {
609
700
  const temporary = `${screenshotRequestPath}.tmp`;
610
- await writeFile(temporary, JSON.stringify({ path }), 'utf8');
701
+ await writeFile(temporary, path, 'utf8');
611
702
  await rename(temporary, screenshotRequestPath);
612
703
  const deadline = Date.now() + DESKTOP_SCREENSHOT_TIMEOUT_MS;
613
704
  while (Date.now() < deadline) {
@@ -617,16 +708,56 @@ function createDesktopDriver(artifactPath, project, options, screenshotRequestPa
617
708
  throw new Error('TN_PROD_NATIVE_SCREENSHOT_UNAVAILABLE');
618
709
  },
619
710
  stop: async () => {
620
- if (child === undefined || child.exitCode !== null) return;
621
- if (process.platform === 'win32') child.kill();
622
- else process.kill(-child.pid, 'SIGTERM');
623
- await new Promise((resolve) => child.once('exit', resolve));
711
+ if (stopping !== undefined) return stopping;
712
+ stopping = (async () => {
713
+ if (child === undefined || child.exitCode !== null || child.signalCode !== null) return;
714
+ const cleanupTimeoutMs = options.desktopCleanupTimeoutMs ?? 2_000;
715
+ const waitForExit = new Promise((resolve, reject) => {
716
+ let timer;
717
+ let settled = false;
718
+ const finish = (exited) => {
719
+ if (settled) return;
720
+ settled = true;
721
+ clearTimeout(timer);
722
+ child.off('exit', onExit);
723
+ resolve(exited);
724
+ };
725
+ const onExit = () => finish(true);
726
+ child.once('exit', onExit);
727
+ timer = setTimeout(() => finish(false), cleanupTimeoutMs);
728
+ try {
729
+ if (process.platform === 'win32') child.kill();
730
+ else process.kill(-child.pid, 'SIGTERM');
731
+ } catch (error) {
732
+ if (error?.code === 'ESRCH') finish(true);
733
+ else {
734
+ settled = true;
735
+ clearTimeout(timer);
736
+ child.off('exit', onExit);
737
+ reject(error);
738
+ }
739
+ }
740
+ if (child.exitCode !== null || child.signalCode !== null) finish(true);
741
+ });
742
+ if (await waitForExit || child.exitCode !== null || child.signalCode !== null) return;
743
+ const diagnostic = {
744
+ code: 'TN_PROD_DESKTOP_CLEANUP_TIMEOUT',
745
+ message: `Desktop cleanup phase 'desktop-stop' did not observe the process exit within ${cleanupTimeoutMs}ms; process was observed alive.`,
746
+ observedAlive: true,
747
+ observedExited: false,
748
+ phase: 'desktop-stop',
749
+ processState: 'alive',
750
+ severity: 'error',
751
+ };
752
+ throw Object.assign(new Error(diagnostic.message), { diagnostic });
753
+ })();
754
+ return stopping;
624
755
  },
625
756
  writeFile: async (path, contents) => writeFile(path, contents, 'utf8'),
626
757
  };
627
758
  }
628
759
 
629
- function spawnNative(artifactPath, project, options) {
760
+ function spawnNative(artifactPath, project, options, mailboxRoot) {
630
761
  const bundle = join(project, '.threenative/build/game.js');
631
762
  const nativeArgs = [
632
763
  'run',
@@ -640,34 +771,44 @@ function spawnNative(artifactPath, project, options) {
640
771
  return spawn(command, args, {
641
772
  cwd: project,
642
773
  detached: process.platform !== 'win32',
643
- env: { ...process.env, SDL_VIDEODRIVER: process.platform === 'linux' ? 'x11' : process.env.SDL_VIDEODRIVER },
774
+ env: { ...process.env, TN_PLAYTEST_MAILBOX_ROOT: mailboxRoot, SDL_VIDEODRIVER: process.platform === 'linux' ? 'x11' : process.env.SDL_VIDEODRIVER },
644
775
  stdio: ['ignore', 'pipe', 'pipe'],
645
776
  });
646
777
  }
647
778
 
648
- async function installNativeProfileEntry(project, target, options) {
779
+ export async function installNativeProfileEntry(project, target, options) {
649
780
  const entryPath = join(project, 'src/profile-native-entry.ts');
650
- const mailboxRoot = join(project, '.runtime-mailbox');
781
+ const profileMarkerPath = join(project, 'src/profile-native-profile.ts');
782
+ const mailboxRoot = '.runtime-mailbox';
783
+ const profileMarker = `Object.assign(globalThis, { __THREENATIVE_PROFILE__: Object.freeze({ hostedSoftware: ${options.hostedSoftware === true} }) });\n`;
651
784
  const mailbox = target === 'desktop'
652
- ? `globalThis.TN_PLAYTEST_MAILBOX = { request: ${JSON.stringify(join(mailboxRoot, 'tn-playtest-request.json'))}, response: ${JSON.stringify(join(mailboxRoot, 'tn-playtest-response.json'))};\n`
785
+ ? `globalThis.TN_PLAYTEST_MAILBOX = ${JSON.stringify({ request: join(mailboxRoot, 'tn-playtest-request.json'), response: join(mailboxRoot, 'tn-playtest-response.json') })};\n`
653
786
  : '';
654
- const screenshotRequestPath = target === 'desktop' ? join(mailboxRoot, 'tn-production-screenshot-request.json') : undefined;
655
- const source = `import game from "./game.js";\n${nativeFrameInstrumentation(options.control, warmupFramesFor(options), screenshotRequestPath)}\n${mailbox}export default game;\n`;
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`;
788
+ await writeFile(profileMarkerPath, profileMarker);
656
789
  await writeFile(entryPath, source);
657
- await setNativeProfileEntry(project, 'src/profile-native-entry.ts');
790
+ await setNativeProfileEntry(project, 'src/profile-native-entry.ts', target);
658
791
  }
659
792
 
660
- export async function setNativeProfileEntry(project, entry) {
793
+ export async function setNativeProfileEntry(project, entry, target) {
661
794
  const configPath = join(project, 'threenative.config.ts');
662
795
  const packagePath = join(project, 'package.json');
663
796
  const config = await readFile(configPath, 'utf8').catch(() => undefined);
664
797
  if (config !== undefined) {
665
- const rendered = config.replace(
798
+ const withEntry = config.replace(
666
799
  /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu,
667
800
  `$1"${entry}"$2`,
668
801
  );
802
+ const rendered = target === 'desktop'
803
+ ? withEntry.replace(
804
+ /(\bui\s*:\s*\{\s*renderer\s*:\s*)["'][^"']*["']/mu,
805
+ `$1"native"`,
806
+ )
807
+ : withEntry;
669
808
  if (rendered !== config) {
670
809
  await writeFile(configPath, rendered);
810
+ }
811
+ if (withEntry !== config) {
671
812
  const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
672
813
  if (packageJson.threenative?.nativeEntry !== undefined) {
673
814
  delete packageJson.threenative.nativeEntry;
@@ -693,6 +834,7 @@ const tnProductionReadPerformance = () => {
693
834
  const performance = snapshot.performance;
694
835
  return {
695
836
  ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
837
+ ...(performance?.phases !== undefined ? { phases: performance.phases } : {}),
696
838
  ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
697
839
  };
698
840
  } catch {
@@ -702,11 +844,10 @@ const tnProductionReadPerformance = () => {
702
844
  `;
703
845
  }
704
846
 
705
- export function nativeFrameInstrumentation(control, warmupFrames = 0, screenshotRequestPath = undefined) {
847
+ export function nativeFrameInstrumentation(control, warmupFrames = 0) {
706
848
  return `
707
849
  const tnProductionControl = ${JSON.stringify(control ?? '')};
708
850
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
709
- const tnProductionScreenshotRequestPath = ${JSON.stringify(screenshotRequestPath)};
710
851
  const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
711
852
  if (typeof tnProductionRequestAnimationFrame !== "function") {
712
853
  throw new Error("TN_PROD_NATIVE_RAF_UNAVAILABLE: native host did not provide requestAnimationFrame.");
@@ -738,26 +879,18 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
738
879
  console.log("TN_PROD_FIRST_NONBLANK_FRAME:" + Date.now());
739
880
  }
740
881
  if (!inWarmup && frameMs !== undefined) {
741
- tnProductionSamples.push({ ...tnProductionReadPerformance(), frameIndex, frameMs });
882
+ tnProductionSamples.push({
883
+ ...tnProductionReadPerformance(),
884
+ ...(Number.isFinite(timestamp) ? { presentationMs: timestamp } : {}),
885
+ clockMs: now,
886
+ frameIndex,
887
+ frameMs,
888
+ });
742
889
  if (tnProductionSamples.length >= ${NATIVE_FRAME_SAMPLE_BATCH_SIZE}) {
743
890
  console.log("TN_PROD_FRAME_SAMPLES:" + JSON.stringify(tnProductionSamples));
744
891
  tnProductionSamples = [];
745
892
  }
746
893
  }
747
- if (tnProductionScreenshotRequestPath !== undefined) {
748
- const nativeHost = globalThis.__THREENATIVE_NATIVE__;
749
- const receive = nativeHost?.playtest?.receive;
750
- const capture = nativeHost?.captureScreenshot;
751
- if (typeof receive === "function" && typeof capture === "function") {
752
- const request = receive(tnProductionScreenshotRequestPath);
753
- if (typeof request === "string") {
754
- try {
755
- const payload = JSON.parse(request);
756
- if (typeof payload.path === "string") capture(payload.path);
757
- } catch {}
758
- }
759
- }
760
- }
761
894
  if (!inWarmup && tnProductionControl === "slow-native" && tnProductionSlowFramesRemaining > 0) {
762
895
  tnProductionBusyWait(${SLOW_FRAME_DELAY_MS});
763
896
  tnProductionSlowFramesRemaining -= 1;
@@ -810,7 +943,13 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
810
943
  tnProductionPost({ kind: "first-frame" });
811
944
  }
812
945
  if (!inWarmup && frameMs !== undefined) {
813
- tnProductionSamples.push({ ...tnProductionReadPerformance(), frameIndex, frameMs });
946
+ tnProductionSamples.push({
947
+ ...tnProductionReadPerformance(),
948
+ ...(Number.isFinite(timestamp) ? { presentationMs: timestamp } : {}),
949
+ clockMs: now,
950
+ frameIndex,
951
+ frameMs,
952
+ });
814
953
  if (tnProductionSamples.length >= ${FRAME_SAMPLE_BATCH_SIZE}) {
815
954
  tnProductionPost({ kind: "samples", samples: tnProductionSamples });
816
955
  tnProductionSamples = [];
@@ -834,7 +973,7 @@ async function installWebProfileEntry(project, markerUrl, control, warmupFrames
834
973
  if (!main.includes(markerImport)) await writeFile(mainPath, `${markerImport}\n${main}`);
835
974
  }
836
975
 
837
- async function createFrameMarkerServer() {
976
+ async function createFrameMarkerServer(port = 0) {
838
977
  const events = [];
839
978
  const waiters = [];
840
979
  const server = createServer((request, response) => {
@@ -860,7 +999,7 @@ async function createFrameMarkerServer() {
860
999
  });
861
1000
  await new Promise((resolve, reject) => {
862
1001
  server.once('error', reject);
863
- server.listen(0, '127.0.0.1', resolve);
1002
+ server.listen(port, '127.0.0.1', resolve);
864
1003
  });
865
1004
  const address = server.address();
866
1005
  if (address === null || typeof address === 'string') throw new ProductionEvidenceError('TN_PROD_MARKER_SERVER_FAILED', 'The first-frame marker server did not expose a TCP port.');
@@ -915,8 +1054,10 @@ async function normalizeRun(
915
1054
  };
916
1055
  }
917
1056
 
918
- function safeReport(report) {
919
- return {
1057
+ const REPORT_REDACTION_MESSAGE = 'TN_PROD_REDACTION: unsafe native report detail withheld.';
1058
+
1059
+ export function safeReport(report) {
1060
+ const safe = {
920
1061
  assertionResults: report.assertionResults,
921
1062
  diagnostics: report.diagnostics,
922
1063
  observations: report.observations,
@@ -924,6 +1065,35 @@ function safeReport(report) {
924
1065
  scenario: report.scenario,
925
1066
  target: report.target,
926
1067
  };
1068
+ try {
1069
+ return sanitizeManifest(safe);
1070
+ } catch {
1071
+ return sanitizeReportValue(safe);
1072
+ }
1073
+ }
1074
+
1075
+ function sanitizeReportValue(value) {
1076
+ if (value === undefined || value === null) return value;
1077
+ if (Array.isArray(value)) return value.map((nested) => sanitizeReportValue(nested));
1078
+ if (typeof value === 'object') {
1079
+ const sanitized = {};
1080
+ for (const [key, nested] of Object.entries(value)) {
1081
+ const candidate = sanitizeReportValue(nested);
1082
+ try {
1083
+ const checked = sanitizeManifest({ [key]: candidate });
1084
+ sanitized[key] = checked[key];
1085
+ } catch {
1086
+ // Privacy-sensitive fields are omitted from retained diagnostics; the verdict and safe
1087
+ // observations remain available for a fail-closed report.
1088
+ }
1089
+ }
1090
+ return sanitized;
1091
+ }
1092
+ try {
1093
+ return sanitizeManifest(value);
1094
+ } catch {
1095
+ return REPORT_REDACTION_MESSAGE;
1096
+ }
927
1097
  }
928
1098
 
929
1099
  function parsePlaytestReport(stdout) {
@@ -974,7 +1144,8 @@ function frameSeriesFromReport(report) {
974
1144
 
975
1145
  export function assembleEvidence({ context, native, options, performanceBounds, project, runId, startedAt, web }) {
976
1146
  const arms = [web, native].filter((arm) => arm !== undefined);
977
- const expectedRuns = options.coldStarts * options.repetitions;
1147
+ const regression = options.profile === REGRESSION_PROFILE;
1148
+ const expectedRuns = collectionLaunchPlan(options).filter((entry) => entry === 'steady').length;
978
1149
  const codes = [];
979
1150
  const rawArtifacts = [];
980
1151
  for (const arm of arms) {
@@ -1002,7 +1173,29 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1002
1173
  ...(webMetrics === undefined ? {} : { web: pairMetrics(webMetrics) }),
1003
1174
  ...(nativeMetrics === undefined ? {} : { native: pairMetrics(nativeMetrics) }),
1004
1175
  };
1005
- const artifactHashes = arms.map(({ artifactSha }) => artifactSha);
1176
+ const selectedMetrics = webMetrics ?? nativeMetrics ?? emptyMetrics();
1177
+ const readiness = regressionReadiness(arms, warmupFramesFor(options));
1178
+ const warmupReset = regressionWarmupReset(arms, warmupFramesFor(options));
1179
+ const motion = regressionMotion(arms);
1180
+ const pixels = regressionPixels(arms);
1181
+ if (regression) {
1182
+ metrics.clockSamplesMs = selectedMetrics.clockSamplesMs;
1183
+ metrics.clockSource = selectedMetrics.clockSource;
1184
+ metrics.hitchCount = selectedMetrics.hitchCount;
1185
+ metrics.presentationClockSource = selectedMetrics.presentationClockSource;
1186
+ metrics.presentationSamplesMs = selectedMetrics.presentationSamplesMs;
1187
+ metrics.sampleCount = selectedMetrics.sampleCount;
1188
+ metrics.worstFrameMs = selectedMetrics.worstFrameMs;
1189
+ metrics.motion = motion;
1190
+ metrics.pixels = pixels;
1191
+ const resources = resourceMetrics(arms);
1192
+ if (resources !== undefined) {
1193
+ metrics.battery = resources.battery;
1194
+ metrics.thermal = resources.thermal;
1195
+ }
1196
+ if (selectedMetrics.phaseP95Ms !== undefined) metrics.phaseP95Ms = selectedMetrics.phaseP95Ms;
1197
+ }
1198
+ const artifactHashes = arms.map(({ artifactSha, bundleSha }) => `${artifactSha}:${bundleSha ?? artifactSha}`);
1006
1199
  const target = options.target;
1007
1200
  const identity = identityFor(options, web, native, artifactHashes);
1008
1201
  const evidence = {
@@ -1016,6 +1209,10 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1016
1209
  maxP99FrameMs: 33,
1017
1210
  maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1018
1211
  minMeanFps: target.includes('physical') ? 59.4 : 60,
1212
+ ...(regression ? {
1213
+ minDurationSeconds: REGRESSION_COLLECTION_PROFILE.durationSeconds,
1214
+ minFrameSamples: REGRESSION_COLLECTION_PROFILE.minFrameSamples,
1215
+ } : {}),
1019
1216
  ...productionPerformanceBudget(performanceBounds),
1020
1217
  },
1021
1218
  command: profileCommand(options),
@@ -1025,8 +1222,12 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1025
1222
  coldStarts: options.coldStarts,
1026
1223
  ...(options.control === undefined ? {} : { control: options.control }),
1027
1224
  deviceSelected: options.device !== undefined,
1225
+ ...(options.hostedSoftware ? { performanceEvaluation: 'advisory' } : {}),
1226
+ profile: options.profile,
1227
+ ...(regression ? { readiness } : {}),
1028
1228
  renderSize: `${options.renderSize.width}x${options.renderSize.height}`,
1029
1229
  repetitions: options.repetitions,
1230
+ ...(regression ? { warmupReset } : {}),
1030
1231
  warmupSeconds: options.warmup,
1031
1232
  },
1032
1233
  identity,
@@ -1054,12 +1255,97 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1054
1255
  return evidence;
1055
1256
  }
1056
1257
 
1258
+ function allProfileRuns(arms) {
1259
+ return arms.flatMap(({ runs }) => runs);
1260
+ }
1261
+
1262
+ function passedAssertion(report, prefix) {
1263
+ return report?.assertionResults?.some(({ id, pass }) => id.startsWith(prefix) && pass === true) === true;
1264
+ }
1265
+
1266
+ function passedRuntimeReadyAssertion(report) {
1267
+ return report?.assertionResults?.some(({ details, id, pass }) =>
1268
+ pass === true
1269
+ && (id === 'diagnostics.runtimeReady' || (id === 'diagnostics' && details?.policy?.runtimeReady === true))
1270
+ ) === true;
1271
+ }
1272
+
1273
+ function regressionReadiness(arms, warmupFrames) {
1274
+ const reports = allProfileRuns(arms).map(({ report }) => report).filter(Boolean);
1275
+ const ready = reports.length > 0 && reports.every(passedRuntimeReadyAssertion);
1276
+ return { ready, sampleReset: regressionWarmupReset(arms, warmupFrames) };
1277
+ }
1278
+
1279
+ function regressionWarmupReset(arms, warmupFrames) {
1280
+ const runs = allProfileRuns(arms);
1281
+ return runs.length > 0 && runs.every(({ series }) => {
1282
+ if (!Array.isArray(series) || series.length === 0) return false;
1283
+ if (warmupFrames === 0) return true;
1284
+ const first = series[0];
1285
+ return Number.isFinite(first?.frameIndex) && first.frameIndex > warmupFrames;
1286
+ });
1287
+ }
1288
+
1289
+ function regressionMotion(arms) {
1290
+ const runs = allProfileRuns(arms);
1291
+ const moved = runs.length > 0 && runs.every(({ report }) =>
1292
+ (typeof report?.distance === 'number' && report.distance > 0)
1293
+ || (Array.isArray(report?.movementDelta) && report.movementDelta.some((value) => typeof value === 'number' && Math.abs(value) > 0))
1294
+ || passedAssertion(report, 'movement.'));
1295
+ return { moved, movingObjects: moved ? 1 : 0 };
1296
+ }
1297
+
1298
+ function regressionPixels(arms) {
1299
+ const runs = allProfileRuns(arms);
1300
+ const nonBlank = runs.length > 0 && runs.every(({ screenshot }) => screenshot !== undefined && isNonBlankFrame(screenshot));
1301
+ const changed = arms.length > 0 && arms.every(({ runs: armRuns, startups }) => {
1302
+ const startupScreenshot = startups.find(({ screenshot }) => screenshot !== undefined)?.screenshot;
1303
+ return startupScreenshot !== undefined
1304
+ && armRuns.some(({ screenshot }) => screenshot !== undefined && screenshotsDiffer(startupScreenshot, screenshot));
1305
+ });
1306
+ return { changed, nonBlank };
1307
+ }
1308
+
1309
+ function resourceMetrics(arms) {
1310
+ const observations = allProfileRuns(arms)
1311
+ .map(({ report }) => report?.observations?.deviceMetrics)
1312
+ .filter(Boolean);
1313
+ if (observations.length === 0) return undefined;
1314
+ const complete = observations.every((observation) =>
1315
+ observation.available === true
1316
+ && Array.isArray(observation.samples)
1317
+ && observation.samples.length >= 2
1318
+ && Array.isArray(observation.errors)
1319
+ && observation.errors.length === 0,
1320
+ );
1321
+ const verdicts = observations
1322
+ .map((observation) => observation.verdict)
1323
+ .filter((verdict) => verdict !== undefined);
1324
+ return {
1325
+ battery: {
1326
+ complete,
1327
+ samples: observations.reduce((count, observation) => count + (observation.samples?.length ?? 0), 0),
1328
+ },
1329
+ thermal: {
1330
+ complete,
1331
+ samples: observations.reduce((count, observation) => count + (observation.samples?.length ?? 0), 0),
1332
+ thermallyConfounded: verdicts.some((verdict) => verdict.thermallyConfounded === true),
1333
+ },
1334
+ };
1335
+ }
1336
+
1337
+ function screenshotsDiffer(left, right) {
1338
+ if (!Buffer.isBuffer(left) || !Buffer.isBuffer(right) || left.length !== right.length) return false;
1339
+ for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return true;
1340
+ return false;
1341
+ }
1342
+
1057
1343
  function productionPerformanceBudget(bounds) {
1058
1344
  if (bounds === undefined) return {};
1059
1345
  if (typeof bounds !== 'object' || bounds === null || Array.isArray(bounds)) {
1060
1346
  throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', 'The source performance bounds must be an object.');
1061
1347
  }
1062
- const keys = ['maxDrawCalls', 'maxFrameMsP95', 'maxTriangles'];
1348
+ const keys = ['maxDrawCalls', 'maxFrameMsP95', 'maxTriangles', 'minFps'];
1063
1349
  const unknown = Object.keys(bounds).filter((key) => !keys.includes(key));
1064
1350
  if (unknown.length > 0) {
1065
1351
  throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', `The source performance bounds contain unsupported keys: ${unknown.join(', ')}.`);
@@ -1093,35 +1379,96 @@ export function postWarmupFrameSamples(samples, warmupFrames = 0) {
1093
1379
  export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1094
1380
  const intervals = [];
1095
1381
  const frameIntervalsMs = [];
1382
+ const clockSamplesMs = [];
1383
+ const presentationSamplesMs = [];
1384
+ const runWindows = [];
1385
+ const phaseSamples = {};
1096
1386
  const startupSamplesMs = startups
1097
1387
  .filter(isSuccessfulStartupSample)
1098
1388
  .map(({ firstFrameMs }) => firstFrameMs);
1099
1389
  let timestampMs = 0;
1100
1390
  let sequence = 1;
1391
+ let sampleCount = 0;
1392
+ let hitchCount = 0;
1393
+ let worstFrameMs;
1394
+ let missingClock = false;
1395
+ let missingPresentationClock = false;
1101
1396
  for (const run of runs) {
1102
- for (const sample of postWarmupFrameSamples(run.series ?? [], warmupFrames)) {
1397
+ let clockOrigin;
1398
+ let presentationOrigin;
1399
+ const postWarmupSamples = postWarmupFrameSamples(run.series ?? [], warmupFrames);
1400
+ let runDurationMs = 0;
1401
+ let runSampleCount = 0;
1402
+ for (const sample of postWarmupSamples) {
1103
1403
  if (typeof sample?.frameMs !== 'number') {
1104
1404
  frameIntervalsMs.push(sample?.frameMs);
1105
1405
  continue;
1106
1406
  }
1107
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);
1413
+ if (Number.isFinite(sample.clockMs)) {
1414
+ clockOrigin ??= sample.clockMs;
1415
+ clockSamplesMs.push(timestampMs + sample.clockMs - clockOrigin);
1416
+ } else {
1417
+ missingClock = true;
1418
+ }
1419
+ if (Number.isFinite(sample.presentationMs)) {
1420
+ presentationOrigin ??= sample.presentationMs;
1421
+ presentationSamplesMs.push(timestampMs + sample.presentationMs - presentationOrigin);
1422
+ } else {
1423
+ missingPresentationClock = true;
1424
+ }
1425
+ if (sample.phases !== undefined && typeof sample.phases === 'object' && sample.phases !== null) {
1426
+ for (const [phase, value] of Object.entries(sample.phases)) {
1427
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) continue;
1428
+ const samples = phaseSamples[phase] ?? [];
1429
+ phaseSamples[phase] = samples;
1430
+ samples.push(value);
1431
+ }
1432
+ }
1108
1433
  intervals.push({
1109
1434
  ...(typeof sample.drawCalls === 'number' ? { drawCalls: sample.drawCalls } : {}),
1110
1435
  frameMs: sample.frameMs,
1436
+ ...(Number.isFinite(sample.clockMs) ? { clockMs: sample.clockMs } : {}),
1437
+ ...(Number.isFinite(sample.presentationMs) ? { presentationMs: sample.presentationMs } : {}),
1438
+ ...(sample.phases === undefined ? {} : { phases: sample.phases }),
1111
1439
  sequence: sequence++,
1112
1440
  timestampMs,
1113
1441
  ...(typeof sample.triangles === 'number' ? { triangles: sample.triangles } : {}),
1114
1442
  });
1115
1443
  timestampMs += sample.frameMs;
1116
1444
  }
1445
+ runWindows.push({ durationSeconds: runDurationMs / 1_000, sampleCount: runSampleCount });
1117
1446
  }
1447
+ const phaseP95ByName = Object.fromEntries(
1448
+ Object.entries(phaseSamples).map(([phase, samples]) => [phase, nearestRank(samples, 0.95)]),
1449
+ );
1118
1450
  return {
1451
+ ...(clockSamplesMs.length === 0 ? {} : { clockSamplesMs }),
1452
+ ...(sampleCount === 0 ? {} : { clockSource: missingClock ? 'missing' : 'monotonic-performance' }),
1119
1453
  ...(frameIntervalsMs.length === 0 ? {} : { frameIntervalsMs }),
1454
+ ...(hitchCount === 0 ? { hitchCount: 0 } : { hitchCount }),
1120
1455
  ...(intervals.length === 0 ? {} : { intervals }),
1456
+ ...(Object.keys(phaseP95ByName).length === 0 ? {} : {
1457
+ phaseP95ByName,
1458
+ ...(phaseP95ByName.render === undefined ? {} : { phaseP95Ms: phaseP95ByName.render }),
1459
+ }),
1460
+ ...(presentationSamplesMs.length === 0 ? {} : { presentationSamplesMs }),
1461
+ ...(runWindows.length === 0 ? {} : { runWindows }),
1462
+ ...(sampleCount === 0 ? {} : { presentationClockSource: missingPresentationClock ? 'missing' : 'raf-presentation', sampleCount, worstFrameMs }),
1121
1463
  ...(startupSamplesMs.length === 0 ? {} : { startupSamplesMs, startupMs: startupSamplesMs[0] }),
1122
1464
  ...(timestampMs === 0 ? {} : { durationSeconds: timestampMs / 1_000 }),
1123
1465
  ...(startupSamplesMs.length === 0 ? {} : { startupP95Ms: nearestRank(startupSamplesMs, 0.95) }),
1124
- ...(frameIntervalsMs.length === 0 ? {} : { meanFps: meanFps(frameIntervalsMs), p99FrameMs: nearestRank(frameIntervalsMs, 0.99) }),
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),
1471
+ }),
1125
1472
  ...(intervals.some(({ drawCalls }) => drawCalls !== undefined) ? { drawCalls: Math.max(...intervals.flatMap(({ drawCalls }) => drawCalls === undefined ? [] : [drawCalls])) } : {}),
1126
1473
  ...(intervals.some(({ triangles }) => triangles !== undefined) ? { triangles: Math.max(...intervals.flatMap(({ triangles }) => triangles === undefined ? [] : [triangles])) } : {}),
1127
1474
  };
@@ -1142,10 +1489,9 @@ function pairMetrics(metrics) {
1142
1489
 
1143
1490
  function identityFor(options, web, native, artifactHashes) {
1144
1491
  const common = {
1145
- deviceClass: options.device === undefined ? 'default-target' : 'selected-target',
1146
- hostClass: `${process.platform}-${process.arch}`,
1147
- osClass: process.platform,
1148
- refreshHz: 60,
1492
+ // 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 ?? {}),
1494
+ workloadHash: web?.workloadHash ?? native?.workloadHash,
1149
1495
  renderHeight: options.renderSize.height,
1150
1496
  renderWidth: options.renderSize.width,
1151
1497
  };
@@ -1158,7 +1504,52 @@ function identityFor(options, web, native, artifactHashes) {
1158
1504
  webProcess: web?.driverClass,
1159
1505
  };
1160
1506
  }
1161
- return { ...common, artifactSha256: artifactHashes[0], executableClass: web?.driverClass ?? native?.driverClass };
1507
+ return {
1508
+ ...common,
1509
+ artifactSha256: artifactHashes[0],
1510
+ ...(native === undefined ? {} : { nativeBinarySha256: native.artifactSha }),
1511
+ executableClass: web?.driverClass ?? native?.driverClass,
1512
+ };
1513
+ }
1514
+
1515
+ function steadyLaunchesAt(options, coldStart) {
1516
+ return options.profile === REGRESSION_PROFILE ? (coldStart === options.coldStarts - 1 ? 1 : 0) : options.repetitions;
1517
+ }
1518
+
1519
+ export function collectionLaunchPlan(options) {
1520
+ return Array.from({ length: options.coldStarts }, (_, index) => ['startup', ...Array(steadyLaunchesAt(options, index)).fill('steady')]).flat();
1521
+ }
1522
+
1523
+ export async function prepareNativeWorkload(project, target, options, execute = runCommand) {
1524
+ if (options.prebuiltArtifact !== undefined && target !== 'desktop') {
1525
+ const receipt = await readPrebuiltWorkload(options.prebuiltArtifact, target, options);
1526
+ return { status: 0, workloadHash: receipt.workloadHash, bundleSha: receipt.bundleSha256 };
1527
+ }
1528
+ // build:desktop compiles assets, the instrumented entry and UI, then packages the existing host.
1529
+ // THREENATIVE_RUNTIME_BINARY prevents a second native compile without omitting the game bundle.
1530
+ return execute('pnpm', ['run', `build:${target}`], project, {
1531
+ ...process.env,
1532
+ ...(options.prebuiltArtifact === undefined ? {} : { THREENATIVE_RUNTIME_BINARY: resolve(options.prebuiltArtifact) }),
1533
+ });
1534
+ }
1535
+
1536
+ export async function readPrebuiltWorkload(artifact, target, options) {
1537
+ try {
1538
+ const receipt = JSON.parse(await readFile(`${artifact}.production.json`, 'utf8'));
1539
+ if (receipt.target !== target || receipt.workload !== 'platformer-production' || receipt.instrumentationRevision !== 'productionEvidenceV1'
1540
+ || receipt.sourceSha !== options.sourceSha || !receipt.appId || !receipt.workloadHash
1541
+ || receipt.artifactSha256 !== await hashPath(artifact)) throw new Error('receipt identity mismatch');
1542
+ const bundle = target === 'ios'
1543
+ ? await readFile(join(artifact, 'native-smoke.js'))
1544
+ : (await execFileAsync('unzip', ['-p', artifact, 'assets/scripts/main.js'], { encoding: 'buffer' })).stdout;
1545
+ const appId = target === 'ios'
1546
+ ? (await execFileAsync('plutil', ['-extract', 'CFBundleIdentifier', 'raw', '-o', '-', join(artifact, 'Info.plist')])).stdout.trim()
1547
+ : (await execFileAsync('aapt', ['dump', 'badging', artifact])).stdout.match(/package: name='([^']+)'/u)?.[1];
1548
+ if (appId !== receipt.appId || sha256(bundle) !== receipt.bundleSha256 || !bundle.includes('TN_PROD_FRAME_SAMPLES:')) throw new Error('packaged workload mismatch');
1549
+ return receipt;
1550
+ } catch (error) {
1551
+ throw new ProductionEvidenceError('TN_PROD_PREBUILT_WORKLOAD', `Prebuilt ${target} requires a matching instrumented platformer receipt and packaged application identity: ${error.message}`);
1552
+ }
1162
1553
  }
1163
1554
 
1164
1555
  function markersFor(arms, codes) {
@@ -1192,6 +1583,8 @@ function profileCommand(options) {
1192
1583
  `--warmup ${options.warmup}`,
1193
1584
  `--repetitions ${options.repetitions}`,
1194
1585
  ...(options.device === undefined ? [] : ['--device <selected>']),
1586
+ ...(options.hostedSoftware ? ['--hosted-software'] : []),
1587
+ ...(options.prebuiltArtifact === undefined ? [] : ['--prebuilt-artifact <existing-build>']),
1195
1588
  ].join(' ');
1196
1589
  }
1197
1590
 
@@ -1408,6 +1801,11 @@ async function hashPath(path) {
1408
1801
  return sha256(Buffer.from(hashInput.join('\n')));
1409
1802
  }
1410
1803
 
1804
+ async function workloadHashFor(project, sourceHash) {
1805
+ if (!sourceHash) throw new ProductionEvidenceError('TN_PROD_WORKLOAD_IDENTITY', 'The workload source tree was not hashed before instrumentation.');
1806
+ return sha256(Buffer.from(`${sourceHash}:${await hashPath(join(project, 'public'))}`));
1807
+ }
1808
+
1411
1809
  async function listFiles(directory) {
1412
1810
  const entries = await readdir(directory, { withFileTypes: true });
1413
1811
  const files = [];
@@ -1487,7 +1885,7 @@ async function removeMailbox(root) {
1487
1885
  await Promise.all([
1488
1886
  rm(join(root, 'tn-playtest-request.json'), { force: true }),
1489
1887
  rm(join(root, 'tn-playtest-response.json'), { force: true }),
1490
- rm(join(root, 'tn-production-screenshot-request.json'), { force: true }),
1888
+ rm(join(root, 'tn-playtest-screenshot-request.txt'), { force: true }),
1491
1889
  ]);
1492
1890
  }
1493
1891