@threenative/runtime-native 0.2.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.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { createServer } from 'node:http';
4
- import { execFile, spawn } from 'node:child_process';
4
+ import { execFile, execFileSync, spawn } from 'node:child_process';
5
5
  import { existsSync } from 'node:fs';
6
6
  import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
7
7
  import { createRequire } from 'node:module';
@@ -11,14 +11,17 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
11
11
  import { promisify } from 'node:util';
12
12
  import { PNG } from 'pngjs';
13
13
  import { readAndroidConfig } from './package-android.mjs';
14
+ import { suppressPlayProtectOnAdbInstalls } from './device-preflight.mjs';
14
15
 
15
16
  import {
16
17
  PRODUCTION_EVIDENCE_VERSION,
17
18
  ProductionEvidenceError,
19
+ REGRESSION_COLLECTION_PROFILE,
18
20
  meanFps,
19
21
  nearestRank,
20
22
  sha256,
21
23
  writeProductionEvidence,
24
+ sanitizeManifest,
22
25
  } from './production-evidence.mjs';
23
26
 
24
27
  const execFileAsync = promisify(execFile);
@@ -51,6 +54,8 @@ const FRAME_SAMPLE_BATCH_SIZE = 30;
51
54
  // Android logcat truncates long lines, so native samples use a smaller JSON batch.
52
55
  const NATIVE_FRAME_SAMPLE_BATCH_SIZE = 5;
53
56
  const DESKTOP_SCREENSHOT_TIMEOUT_MS = 5_000;
57
+ const PRODUCTION_PROFILE = 'production';
58
+ const REGRESSION_PROFILE = 'regression';
54
59
 
55
60
  function installedPackageFile(packageName, file) {
56
61
  try {
@@ -85,40 +90,61 @@ export function parseProductionArgs(argv = process.argv.slice(2)) {
85
90
  control: undefined,
86
91
  device: undefined,
87
92
  duration: 60,
93
+ hostedSoftware: false,
88
94
  out: '.runtime/prd064/production',
95
+ prebuiltArtifact: undefined,
89
96
  physicalEvidence: undefined,
90
- renderSize: { height: 1080, width: 1920 },
97
+ profile: PRODUCTION_PROFILE,
98
+ renderSize: undefined,
91
99
  repetitions: 3,
92
100
  sourceSha: undefined,
93
101
  target: undefined,
94
102
  warmup: 60,
95
103
  };
104
+ const explicit = new Set();
96
105
  for (let index = 0; index < argv.length; index += 1) {
97
106
  const flag = argv[index];
98
107
  if (flag === '--') continue;
99
- if (flag === '--audio-evidence') options.audioEvidence = nextValue(argv, ++index, flag);
100
- else if (flag === '--cold-starts') options.coldStarts = positiveInteger(nextValue(argv, ++index, flag), flag);
101
- else if (flag === '--config') options.config = nextValue(argv, ++index, flag);
102
- else if (flag === '--control') options.control = nextValue(argv, ++index, flag);
103
- else if (flag === '--device') options.device = nextValue(argv, ++index, flag);
104
- else if (flag === '--duration') options.duration = positiveNumber(nextValue(argv, ++index, flag), flag);
105
- else if (flag === '--out') options.out = nextValue(argv, ++index, flag);
106
- else if (flag === '--physical-evidence') options.physicalEvidence = nextValue(argv, ++index, flag);
107
- else if (flag === '--render-size') options.renderSize = parseRenderSize(nextValue(argv, ++index, flag));
108
- else if (flag === '--repetitions') options.repetitions = positiveInteger(nextValue(argv, ++index, flag), flag);
109
- else if (flag === '--source-sha') options.sourceSha = nextValue(argv, ++index, flag);
110
- else if (flag === '--target') options.target = nextValue(argv, ++index, flag);
111
- 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); }
112
125
  else if (flag === '--help') return { ...options, help: true };
113
126
  else throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', `Unknown production profile option '${flag}'.`);
114
127
  }
115
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
+ }
116
136
  return validateProductionOptions(options);
117
137
  }
118
138
 
119
139
  export function validateProductionOptions(input) {
120
140
  const options = normalizeOptions(input);
121
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
+ }
122
148
  if (!supportedTargets.has(options.target)) {
123
149
  throw new ProductionEvidenceError('TN_PROD_TARGET_UNSUPPORTED', `Production target '${options.target}' is not supported.`);
124
150
  }
@@ -137,6 +163,9 @@ export function validateProductionOptions(input) {
137
163
  if (physicalTargets.has(options.target) && options.device === undefined) {
138
164
  throw new ProductionEvidenceError('TN_PROD_DEVICE_REQUIRED', `Target '${options.target}' requires --device.`);
139
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
+ }
140
169
  if (options.target === 'desktop-pair' && options.control === 'slow-native') return options;
141
170
  if (options.control === 'slow-native' && options.target !== 'desktop-pair') {
142
171
  throw new ProductionEvidenceError('TN_PROD_CONTROL_UNSUPPORTED', "The 'slow-native' control requires --target desktop-pair.");
@@ -157,6 +186,7 @@ export async function runProductionProfile(input, dependencies = {}) {
157
186
  const sourceState = await currentSourceState();
158
187
  const requiredSourceSha = sourceState.sha;
159
188
  const sourceSha = options.sourceSha ?? requiredSourceSha;
189
+ options.sourceSha = sourceSha;
160
190
  const runId = `${options.target}-${Date.now()}`;
161
191
  const physicalEvidence = await readPhysicalEvidence(options.physicalEvidence);
162
192
  const audioEvidence = await readOptionalArtifact(options.audioEvidence);
@@ -189,6 +219,7 @@ export async function collectProduction(options, context, runId) {
189
219
  const startedAt = new Date().toISOString();
190
220
  try {
191
221
  await scaffoldPlatformer(project, tools);
222
+ tools.workloadSourceHash = await hashPath(join(project, 'src'));
192
223
  const scenarios = await writeRunScenarios(project, options);
193
224
  const artifactsRoot = join(project, 'artifacts', 'production');
194
225
  await mkdir(artifactsRoot, { recursive: true });
@@ -216,20 +247,28 @@ export async function collectProduction(options, context, runId) {
216
247
  function normalizeOptions(input = {}) {
217
248
  const renderSize = typeof input.renderSize === 'string' ? parseRenderSize(input.renderSize) : input.renderSize;
218
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 };
219
255
  return {
220
256
  audioEvidence: input.audioEvidence,
221
- coldStarts: input.coldStarts ?? 1,
257
+ coldStarts: input.coldStarts ?? (regression ? REGRESSION_COLLECTION_PROFILE.coldStarts : 1),
222
258
  control: input.control,
223
259
  device: input.device,
224
- duration: input.duration ?? 60,
260
+ duration: input.duration ?? (regression ? REGRESSION_COLLECTION_PROFILE.durationSeconds : 60),
261
+ hostedSoftware: input.hostedSoftware === true,
225
262
  help: input.help,
226
- 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),
227
265
  physicalEvidence: input.physicalEvidence,
228
- renderSize: renderSize ?? { height: 1080, width: 1920 },
229
- repetitions: input.repetitions ?? 3,
266
+ renderSize: renderSize ?? defaultRenderSize,
267
+ profile,
268
+ repetitions: input.repetitions ?? (regression ? 1 : 3),
230
269
  sourceSha: input.sourceSha,
231
270
  target,
232
- warmup: input.warmup ?? 60,
271
+ warmup: input.warmup ?? (regression ? 5 : 60),
233
272
  };
234
273
  }
235
274
 
@@ -243,13 +282,16 @@ async function scaffoldPlatformer(project, tools) {
243
282
  const packageSource = async (name, directory) => [name, await packLocalPackage(directory, packageArchiveRoot)];
244
283
  const localSources = [];
245
284
  if (inRepositoryCheckout) {
246
- localSources.push(await packageSource('@threenative/core', join(repositoryRoot, 'packages/core')));
247
- localSources.push(await packageSource('@threenative/physics', join(repositoryRoot, 'packages/physics')));
248
- localSources.push(await packageSource('@threenative/playtest', join(repositoryRoot, 'packages/playtest')));
249
- localSources.push(await packageSource('@threenative/runtime-native', join(repositoryRoot, 'packages/runtime-native')));
250
- localSources.push(await packageSource('@threenative/ui', join(repositoryRoot, 'packages/ui')));
251
- localSources.push(await packageSource('@threenative/studio', join(repositoryRoot, 'packages/studio')));
252
- localSources.push(await packageSource('create-threenative', join(repositoryRoot, 'packages/create-threenative')));
285
+ for (const workspacePackage of localWorkspacePackages()) {
286
+ localSources.push(
287
+ await packageSource(workspacePackage.name, join(repositoryRoot, workspacePackage.directory)),
288
+ );
289
+ }
290
+ const studioDirectory = join(repositoryRoot, 'packages/studio');
291
+ if (existsSync(join(studioDirectory, 'package.json'))) {
292
+ // Studio is a private cross-checkout extra, not a workspace package in this repository.
293
+ localSources.push(await packageSource('@threenative/studio', studioDirectory));
294
+ }
253
295
  }
254
296
  const args = [
255
297
  tools.scaffoldCli,
@@ -263,6 +305,17 @@ async function scaffoldPlatformer(project, tools) {
263
305
  }
264
306
  }
265
307
 
308
+ function localWorkspacePackages() {
309
+ const output = execFileSync(
310
+ 'pnpm',
311
+ ['exec', 'tsx', join(repositoryRoot, 'scripts/workspace-packages.ts'), '--json'],
312
+ { cwd: repositoryRoot, encoding: 'utf8' },
313
+ );
314
+ const packages = JSON.parse(output);
315
+ if (!Array.isArray(packages)) throw new Error('TN_WORKSPACE_PACKAGE_DERIVATION_INVALID: expected an array.');
316
+ return packages.filter((item) => item && typeof item.name === 'string' && typeof item.directory === 'string');
317
+ }
318
+
266
319
  async function packLocalPackage(directory, destination) {
267
320
  const before = new Set(await readdir(destination));
268
321
  const result = await runCommand('pnpm', ['pack', '--pack-destination', destination], directory);
@@ -273,19 +326,28 @@ async function packLocalPackage(directory, destination) {
273
326
  }
274
327
 
275
328
  function packageSourceFlag(name) {
276
- return name === '@threenative/core'
277
- ? '--core-package'
278
- : name === '@threenative/physics'
279
- ? '--physics-package'
280
- : name === '@threenative/playtest'
281
- ? '--playtest-package'
282
- : name === '@threenative/runtime-native'
283
- ? '--runtime-native-package'
284
- : name === '@threenative/ui'
285
- ? '--ui-package'
286
- : name === '@threenative/studio'
287
- ? '--studio-package'
288
- : '--cli-package';
329
+ if (name === 'create-threenative') return '--cli-package';
330
+ if (name === 'threenative-blender-mcp') return '--blender-mcp-package';
331
+ if (name === 'threenative-engine-mcp') return '--engine-mcp-package';
332
+ if (name.startsWith('@threenative/')) {
333
+ const suffix = name.slice('@threenative/'.length);
334
+ return `--threenative-${suffix}-package`;
335
+ }
336
+ throw new Error(`TN_PROD_PACKAGE_FLAG_UNSUPPORTED: ${name}`);
337
+ }
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
+ };
289
351
  }
290
352
 
291
353
  export async function writeRunScenarios(project, options) {
@@ -294,9 +356,12 @@ export async function writeRunScenarios(project, options) {
294
356
  ? source.assert
295
357
  : {};
296
358
  const { performance: performanceBounds, ...playtestAssertions } = sourceAssertions;
297
- const workloadAssertions = Object.keys(playtestAssertions).length === 0
359
+ const baseWorkloadAssertions = Object.keys(playtestAssertions).length === 0
298
360
  ? { diagnostics: { noConsoleErrors: true, runtimeReady: true } }
299
361
  : playtestAssertions;
362
+ const workloadAssertions = options.profile === REGRESSION_PROFILE
363
+ ? { ...baseWorkloadAssertions, movement: { entity: 'player', minDistance: 0.1 } }
364
+ : baseWorkloadAssertions;
300
365
  const { assert: _sourceAssertions, ...scenarioSource } = source;
301
366
  const workloadFrames = Math.max(1, Math.ceil(options.duration * 60));
302
367
  const warmupFrames = Math.max(0, Math.ceil(options.warmup * 60));
@@ -332,10 +397,15 @@ export async function writeRunScenarios(project, options) {
332
397
  };
333
398
  const nativeWorkload = {
334
399
  ...workload,
335
- 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
+ },
336
406
  steps: nativeWorkloadSteps,
337
407
  };
338
- const nativeStartup = { ...startup, artifacts: { screenshots: 'after' } };
408
+ const nativeStartup = { ...startup, assert: nativeDiagnostics(startup.assert), artifacts: { screenshots: 'after' } };
339
409
  const workloadPath = join(project, 'playtests/production-performance.run.playtest.json');
340
410
  const startupPath = join(project, 'playtests/production-startup.run.playtest.json');
341
411
  const nativeWorkloadPath = join(project, 'playtests/production-performance.native.playtest.json');
@@ -354,7 +424,7 @@ export async function writeRunScenarios(project, options) {
354
424
  }
355
425
 
356
426
  async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
357
- const markerServer = await createFrameMarkerServer();
427
+ const markerServer = await createFrameMarkerServer(options.profile === REGRESSION_PROFILE ? 41778 : 0);
358
428
  try {
359
429
  await installWebProfileEntry(project, markerServer.url, options.control, warmupFramesFor(options));
360
430
  const build = await runCommand('pnpm', ['run', 'build:web'], project);
@@ -365,7 +435,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
365
435
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
366
436
  const startup = await runWebScenario(project, scenarios.startupPath, join(artifactsRoot, `web-startup-${coldStart + 1}`), markerServer, tools.playtestCli);
367
437
  startups.push(startup);
368
- for (let repetition = 0; repetition < options.repetitions; repetition += 1) {
438
+ for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
369
439
  runs.push(await runWebScenario(
370
440
  project,
371
441
  scenarios.workloadPath,
@@ -377,6 +447,7 @@ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
377
447
  }
378
448
  return {
379
449
  artifactSha,
450
+ workloadHash: await workloadHashFor(project, tools.workloadSourceHash),
380
451
  applicationClass: 'platformer-web-build',
381
452
  driverClass: 'playwright-chromium-webgpu',
382
453
  kind: 'web',
@@ -398,7 +469,7 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
398
469
  '--artifacts', relativeArtifact,
399
470
  '--browser-recipe', 'webgpu',
400
471
  '--project', project,
401
- '--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`,
402
473
  '--timeout', '30000',
403
474
  '--url', `http://127.0.0.1:${port}`,
404
475
  ];
@@ -421,7 +492,7 @@ async function runWebScenario(project, scenarioPath, artifactDirectory, markerSe
421
492
  async function collectNative(project, scenarios, artifactsRoot, options, tools) {
422
493
  const target = options.target === 'desktop-pair' || options.target === 'desktop' ? 'desktop' : options.target.startsWith('ios') ? 'ios' : 'android';
423
494
  await installNativeProfileEntry(project, target, options);
424
- const build = await runCommand('pnpm', ['run', `build:${target}`], project);
495
+ const build = await prepareNativeWorkload(project, target, options);
425
496
  if (build.status !== 0) {
426
497
  const details = [build.stdout, build.stderr]
427
498
  .filter((value) => typeof value === 'string' && value.trim().length > 0)
@@ -432,14 +503,14 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
432
503
  `The scaffolded platformer ${target} build failed.${details.length === 0 ? '' : `\n${details.slice(-4_000)}`}`,
433
504
  );
434
505
  }
435
- const artifactPath = await nativeArtifactPath(project, target);
506
+ const artifactPath = options.prebuiltArtifact ?? await nativeArtifactPath(project, target);
436
507
  const artifactSha = await hashPath(artifactPath);
437
508
  const runs = [];
438
509
  const startups = [];
439
510
  for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
440
511
  const startup = await runNativeScenario(project, target, scenarios.nativeStartupPath, join(artifactsRoot, `native-startup-${coldStart + 1}`), options, artifactPath, tools);
441
512
  startups.push(startup);
442
- for (let repetition = 0; repetition < options.repetitions; repetition += 1) {
513
+ for (let repetition = 0; repetition < steadyLaunchesAt(options, coldStart); repetition += 1) {
443
514
  runs.push(await runNativeScenario(
444
515
  project,
445
516
  target,
@@ -453,6 +524,8 @@ async function collectNative(project, scenarios, artifactsRoot, options, tools)
453
524
  }
454
525
  return {
455
526
  artifactSha,
527
+ workloadHash: build.workloadHash ?? await workloadHashFor(project, tools.workloadSourceHash),
528
+ bundleSha: build.bundleSha ?? await hashPath(join(project, '.threenative/build/game.js')),
456
529
  applicationClass: `platformer-${target}-build`,
457
530
  driverClass: `threenative-${target}-runtime`,
458
531
  kind: target,
@@ -473,9 +546,12 @@ async function runNativeScenario(project, target, scenarioPath, artifactDirector
473
546
  if (target === 'android') await installAndroidArtifact(artifactPath, options.device);
474
547
  // The game declares its identity in `threenative.config.ts` and packaging resolves it; profiling
475
548
  // launches whatever packaging shipped, so it reads the id from there instead of restating one.
476
- 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;
477
552
  const config = {
478
553
  android: { activity: 'com.threenative.runtime.MystralActivity', packageName: appId },
554
+ allowSoftwareAdapter: options.hostedSoftware,
479
555
  artifactDirectory,
480
556
  device: options.device,
481
557
  headless: true,
@@ -521,15 +597,11 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
521
597
  await removeMailbox(mailboxRoot);
522
598
  const requestPath = join(mailboxRoot, 'tn-playtest-request.json');
523
599
  const responsePath = join(mailboxRoot, 'tn-playtest-response.json');
524
- const screenshotRequestPath = join(mailboxRoot, 'tn-production-screenshot-request.json');
525
600
  const runner = await import(pathToFileURL(modulePath).href);
526
- const mailbox = {
527
- read: async (path) => readFile(path, 'utf8').catch((error) => error?.code === 'ENOENT' ? undefined : Promise.reject(error)),
528
- remove: async (path) => rm(path, { force: true }).catch(() => undefined),
529
- write: async (path, contents) => writeFile(path, contents, 'utf8'),
530
- };
531
- const innerTransport = new runner.DeviceMailboxTransport(mailbox, { request: requestPath, response: responsePath });
532
- 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);
533
605
  const transport = {
534
606
  capabilities: innerTransport.capabilities,
535
607
  call: innerTransport.call.bind(innerTransport),
@@ -541,12 +613,13 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
541
613
  waitForBridge: innerTransport.waitForBridge.bind(innerTransport),
542
614
  };
543
615
  const config = {
616
+ allowSoftwareAdapter: options.hostedSoftware,
544
617
  artifactDirectory,
545
618
  headless: true,
546
619
  projectPath: project,
547
620
  scenarioPath: relative(project, scenarioPath),
548
621
  target: 'android',
549
- timeoutMs: 30_000,
622
+ timeoutMs,
550
623
  trace: false,
551
624
  url: 'http://127.0.0.1:41777',
552
625
  };
@@ -568,24 +641,51 @@ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory
568
641
  firstFrameMsFromReport(report, startedAt),
569
642
  frameSeriesFromReport(report),
570
643
  );
571
- } catch {
572
- await driver.stop();
573
- 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);
574
652
  }
575
653
  }
576
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
+
577
675
  export function profileConfigPath(project, configPath = undefined) {
578
676
  return configPath ?? join(project, '.threenative', 'build', 'config.json');
579
677
  }
580
678
 
581
- function createDesktopDriver(artifactPath, project, options, screenshotRequestPath) {
679
+ function createDesktopDriver(artifactPath, project, options, mailboxRoot) {
582
680
  let child;
583
681
  let output = '';
682
+ let stopping;
683
+ const screenshotRequestPath = join(mailboxRoot, 'tn-playtest-screenshot-request.txt');
584
684
  return {
585
685
  captureConsole: async () => output.split(/\r?\n/u).filter(Boolean).map((text) => ({ text, type: /\b(?:Error|FAILED|FATAL)\b/u.test(text) ? 'error' : 'log' })),
586
686
  isAlive: async () => child !== undefined && child.exitCode === null,
587
687
  launch: async () => {
588
- child = spawnNative(artifactPath, project, options);
688
+ child = spawnNative(artifactPath, project, options, mailboxRoot);
589
689
  child.stdout?.on('data', (chunk) => { output += chunk.toString(); });
590
690
  child.stderr?.on('data', (chunk) => { output += chunk.toString(); });
591
691
  await new Promise((resolve, reject) => {
@@ -598,7 +698,7 @@ function createDesktopDriver(artifactPath, project, options, screenshotRequestPa
598
698
  removeFile: async (path) => rm(path, { force: true }).catch(() => undefined),
599
699
  screenshot: async (path) => {
600
700
  const temporary = `${screenshotRequestPath}.tmp`;
601
- await writeFile(temporary, JSON.stringify({ path }), 'utf8');
701
+ await writeFile(temporary, path, 'utf8');
602
702
  await rename(temporary, screenshotRequestPath);
603
703
  const deadline = Date.now() + DESKTOP_SCREENSHOT_TIMEOUT_MS;
604
704
  while (Date.now() < deadline) {
@@ -608,16 +708,56 @@ function createDesktopDriver(artifactPath, project, options, screenshotRequestPa
608
708
  throw new Error('TN_PROD_NATIVE_SCREENSHOT_UNAVAILABLE');
609
709
  },
610
710
  stop: async () => {
611
- if (child === undefined || child.exitCode !== null) return;
612
- if (process.platform === 'win32') child.kill();
613
- else process.kill(-child.pid, 'SIGTERM');
614
- 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;
615
755
  },
616
756
  writeFile: async (path, contents) => writeFile(path, contents, 'utf8'),
617
757
  };
618
758
  }
619
759
 
620
- function spawnNative(artifactPath, project, options) {
760
+ function spawnNative(artifactPath, project, options, mailboxRoot) {
621
761
  const bundle = join(project, '.threenative/build/game.js');
622
762
  const nativeArgs = [
623
763
  'run',
@@ -631,34 +771,44 @@ function spawnNative(artifactPath, project, options) {
631
771
  return spawn(command, args, {
632
772
  cwd: project,
633
773
  detached: process.platform !== 'win32',
634
- 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 },
635
775
  stdio: ['ignore', 'pipe', 'pipe'],
636
776
  });
637
777
  }
638
778
 
639
- async function installNativeProfileEntry(project, target, options) {
779
+ export async function installNativeProfileEntry(project, target, options) {
640
780
  const entryPath = join(project, 'src/profile-native-entry.ts');
641
- 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`;
642
784
  const mailbox = target === 'desktop'
643
- ? `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`
644
786
  : '';
645
- const screenshotRequestPath = target === 'desktop' ? join(mailboxRoot, 'tn-production-screenshot-request.json') : undefined;
646
- 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);
647
789
  await writeFile(entryPath, source);
648
- await setNativeProfileEntry(project, 'src/profile-native-entry.ts');
790
+ await setNativeProfileEntry(project, 'src/profile-native-entry.ts', target);
649
791
  }
650
792
 
651
- export async function setNativeProfileEntry(project, entry) {
793
+ export async function setNativeProfileEntry(project, entry, target) {
652
794
  const configPath = join(project, 'threenative.config.ts');
653
795
  const packagePath = join(project, 'package.json');
654
796
  const config = await readFile(configPath, 'utf8').catch(() => undefined);
655
797
  if (config !== undefined) {
656
- const rendered = config.replace(
798
+ const withEntry = config.replace(
657
799
  /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu,
658
800
  `$1"${entry}"$2`,
659
801
  );
802
+ const rendered = target === 'desktop'
803
+ ? withEntry.replace(
804
+ /(\bui\s*:\s*\{\s*renderer\s*:\s*)["'][^"']*["']/mu,
805
+ `$1"native"`,
806
+ )
807
+ : withEntry;
660
808
  if (rendered !== config) {
661
809
  await writeFile(configPath, rendered);
810
+ }
811
+ if (withEntry !== config) {
662
812
  const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
663
813
  if (packageJson.threenative?.nativeEntry !== undefined) {
664
814
  delete packageJson.threenative.nativeEntry;
@@ -684,6 +834,7 @@ const tnProductionReadPerformance = () => {
684
834
  const performance = snapshot.performance;
685
835
  return {
686
836
  ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
837
+ ...(performance?.phases !== undefined ? { phases: performance.phases } : {}),
687
838
  ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
688
839
  };
689
840
  } catch {
@@ -693,11 +844,10 @@ const tnProductionReadPerformance = () => {
693
844
  `;
694
845
  }
695
846
 
696
- export function nativeFrameInstrumentation(control, warmupFrames = 0, screenshotRequestPath = undefined) {
847
+ export function nativeFrameInstrumentation(control, warmupFrames = 0) {
697
848
  return `
698
849
  const tnProductionControl = ${JSON.stringify(control ?? '')};
699
850
  const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
700
- const tnProductionScreenshotRequestPath = ${JSON.stringify(screenshotRequestPath)};
701
851
  const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
702
852
  if (typeof tnProductionRequestAnimationFrame !== "function") {
703
853
  throw new Error("TN_PROD_NATIVE_RAF_UNAVAILABLE: native host did not provide requestAnimationFrame.");
@@ -729,26 +879,18 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
729
879
  console.log("TN_PROD_FIRST_NONBLANK_FRAME:" + Date.now());
730
880
  }
731
881
  if (!inWarmup && frameMs !== undefined) {
732
- tnProductionSamples.push({ ...tnProductionReadPerformance(), frameIndex, frameMs });
882
+ tnProductionSamples.push({
883
+ ...tnProductionReadPerformance(),
884
+ ...(Number.isFinite(timestamp) ? { presentationMs: timestamp } : {}),
885
+ clockMs: now,
886
+ frameIndex,
887
+ frameMs,
888
+ });
733
889
  if (tnProductionSamples.length >= ${NATIVE_FRAME_SAMPLE_BATCH_SIZE}) {
734
890
  console.log("TN_PROD_FRAME_SAMPLES:" + JSON.stringify(tnProductionSamples));
735
891
  tnProductionSamples = [];
736
892
  }
737
893
  }
738
- if (tnProductionScreenshotRequestPath !== undefined) {
739
- const nativeHost = globalThis.__THREENATIVE_NATIVE__;
740
- const receive = nativeHost?.playtest?.receive;
741
- const capture = nativeHost?.captureScreenshot;
742
- if (typeof receive === "function" && typeof capture === "function") {
743
- const request = receive(tnProductionScreenshotRequestPath);
744
- if (typeof request === "string") {
745
- try {
746
- const payload = JSON.parse(request);
747
- if (typeof payload.path === "string") capture(payload.path);
748
- } catch {}
749
- }
750
- }
751
- }
752
894
  if (!inWarmup && tnProductionControl === "slow-native" && tnProductionSlowFramesRemaining > 0) {
753
895
  tnProductionBusyWait(${SLOW_FRAME_DELAY_MS});
754
896
  tnProductionSlowFramesRemaining -= 1;
@@ -801,7 +943,13 @@ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFra
801
943
  tnProductionPost({ kind: "first-frame" });
802
944
  }
803
945
  if (!inWarmup && frameMs !== undefined) {
804
- tnProductionSamples.push({ ...tnProductionReadPerformance(), frameIndex, frameMs });
946
+ tnProductionSamples.push({
947
+ ...tnProductionReadPerformance(),
948
+ ...(Number.isFinite(timestamp) ? { presentationMs: timestamp } : {}),
949
+ clockMs: now,
950
+ frameIndex,
951
+ frameMs,
952
+ });
805
953
  if (tnProductionSamples.length >= ${FRAME_SAMPLE_BATCH_SIZE}) {
806
954
  tnProductionPost({ kind: "samples", samples: tnProductionSamples });
807
955
  tnProductionSamples = [];
@@ -825,7 +973,7 @@ async function installWebProfileEntry(project, markerUrl, control, warmupFrames
825
973
  if (!main.includes(markerImport)) await writeFile(mainPath, `${markerImport}\n${main}`);
826
974
  }
827
975
 
828
- async function createFrameMarkerServer() {
976
+ async function createFrameMarkerServer(port = 0) {
829
977
  const events = [];
830
978
  const waiters = [];
831
979
  const server = createServer((request, response) => {
@@ -851,7 +999,7 @@ async function createFrameMarkerServer() {
851
999
  });
852
1000
  await new Promise((resolve, reject) => {
853
1001
  server.once('error', reject);
854
- server.listen(0, '127.0.0.1', resolve);
1002
+ server.listen(port, '127.0.0.1', resolve);
855
1003
  });
856
1004
  const address = server.address();
857
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.');
@@ -906,8 +1054,10 @@ async function normalizeRun(
906
1054
  };
907
1055
  }
908
1056
 
909
- function safeReport(report) {
910
- return {
1057
+ const REPORT_REDACTION_MESSAGE = 'TN_PROD_REDACTION: unsafe native report detail withheld.';
1058
+
1059
+ export function safeReport(report) {
1060
+ const safe = {
911
1061
  assertionResults: report.assertionResults,
912
1062
  diagnostics: report.diagnostics,
913
1063
  observations: report.observations,
@@ -915,6 +1065,35 @@ function safeReport(report) {
915
1065
  scenario: report.scenario,
916
1066
  target: report.target,
917
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
+ }
918
1097
  }
919
1098
 
920
1099
  function parsePlaytestReport(stdout) {
@@ -928,7 +1107,6 @@ function parsePlaytestReport(stdout) {
928
1107
  try {
929
1108
  return JSON.parse(line);
930
1109
  } catch {
931
- continue;
932
1110
  }
933
1111
  }
934
1112
  }
@@ -959,7 +1137,6 @@ function frameSeriesFromReport(report) {
959
1137
  const batch = JSON.parse(line.slice(offset + prefix.length));
960
1138
  if (Array.isArray(batch)) series.push(...batch);
961
1139
  } catch {
962
- continue;
963
1140
  }
964
1141
  }
965
1142
  return series.length === 0 ? undefined : series;
@@ -967,7 +1144,8 @@ function frameSeriesFromReport(report) {
967
1144
 
968
1145
  export function assembleEvidence({ context, native, options, performanceBounds, project, runId, startedAt, web }) {
969
1146
  const arms = [web, native].filter((arm) => arm !== undefined);
970
- const expectedRuns = options.coldStarts * options.repetitions;
1147
+ const regression = options.profile === REGRESSION_PROFILE;
1148
+ const expectedRuns = collectionLaunchPlan(options).filter((entry) => entry === 'steady').length;
971
1149
  const codes = [];
972
1150
  const rawArtifacts = [];
973
1151
  for (const arm of arms) {
@@ -995,7 +1173,29 @@ export function assembleEvidence({ context, native, options, performanceBounds,
995
1173
  ...(webMetrics === undefined ? {} : { web: pairMetrics(webMetrics) }),
996
1174
  ...(nativeMetrics === undefined ? {} : { native: pairMetrics(nativeMetrics) }),
997
1175
  };
998
- 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}`);
999
1199
  const target = options.target;
1000
1200
  const identity = identityFor(options, web, native, artifactHashes);
1001
1201
  const evidence = {
@@ -1009,6 +1209,10 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1009
1209
  maxP99FrameMs: 33,
1010
1210
  maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1011
1211
  minMeanFps: target.includes('physical') ? 59.4 : 60,
1212
+ ...(regression ? {
1213
+ minDurationSeconds: REGRESSION_COLLECTION_PROFILE.durationSeconds,
1214
+ minFrameSamples: REGRESSION_COLLECTION_PROFILE.minFrameSamples,
1215
+ } : {}),
1012
1216
  ...productionPerformanceBudget(performanceBounds),
1013
1217
  },
1014
1218
  command: profileCommand(options),
@@ -1018,8 +1222,12 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1018
1222
  coldStarts: options.coldStarts,
1019
1223
  ...(options.control === undefined ? {} : { control: options.control }),
1020
1224
  deviceSelected: options.device !== undefined,
1225
+ ...(options.hostedSoftware ? { performanceEvaluation: 'advisory' } : {}),
1226
+ profile: options.profile,
1227
+ ...(regression ? { readiness } : {}),
1021
1228
  renderSize: `${options.renderSize.width}x${options.renderSize.height}`,
1022
1229
  repetitions: options.repetitions,
1230
+ ...(regression ? { warmupReset } : {}),
1023
1231
  warmupSeconds: options.warmup,
1024
1232
  },
1025
1233
  identity,
@@ -1047,12 +1255,97 @@ export function assembleEvidence({ context, native, options, performanceBounds,
1047
1255
  return evidence;
1048
1256
  }
1049
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
+
1050
1343
  function productionPerformanceBudget(bounds) {
1051
1344
  if (bounds === undefined) return {};
1052
1345
  if (typeof bounds !== 'object' || bounds === null || Array.isArray(bounds)) {
1053
1346
  throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', 'The source performance bounds must be an object.');
1054
1347
  }
1055
- const keys = ['maxDrawCalls', 'maxFrameMsP95', 'maxTriangles'];
1348
+ const keys = ['maxDrawCalls', 'maxFrameMsP95', 'maxTriangles', 'minFps'];
1056
1349
  const unknown = Object.keys(bounds).filter((key) => !keys.includes(key));
1057
1350
  if (unknown.length > 0) {
1058
1351
  throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', `The source performance bounds contain unsupported keys: ${unknown.join(', ')}.`);
@@ -1086,35 +1379,96 @@ export function postWarmupFrameSamples(samples, warmupFrames = 0) {
1086
1379
  export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1087
1380
  const intervals = [];
1088
1381
  const frameIntervalsMs = [];
1382
+ const clockSamplesMs = [];
1383
+ const presentationSamplesMs = [];
1384
+ const runWindows = [];
1385
+ const phaseSamples = {};
1089
1386
  const startupSamplesMs = startups
1090
1387
  .filter(isSuccessfulStartupSample)
1091
1388
  .map(({ firstFrameMs }) => firstFrameMs);
1092
1389
  let timestampMs = 0;
1093
1390
  let sequence = 1;
1391
+ let sampleCount = 0;
1392
+ let hitchCount = 0;
1393
+ let worstFrameMs;
1394
+ let missingClock = false;
1395
+ let missingPresentationClock = false;
1094
1396
  for (const run of runs) {
1095
- 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) {
1096
1403
  if (typeof sample?.frameMs !== 'number') {
1097
1404
  frameIntervalsMs.push(sample?.frameMs);
1098
1405
  continue;
1099
1406
  }
1100
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
+ }
1101
1433
  intervals.push({
1102
1434
  ...(typeof sample.drawCalls === 'number' ? { drawCalls: sample.drawCalls } : {}),
1103
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 }),
1104
1439
  sequence: sequence++,
1105
1440
  timestampMs,
1106
1441
  ...(typeof sample.triangles === 'number' ? { triangles: sample.triangles } : {}),
1107
1442
  });
1108
1443
  timestampMs += sample.frameMs;
1109
1444
  }
1445
+ runWindows.push({ durationSeconds: runDurationMs / 1_000, sampleCount: runSampleCount });
1110
1446
  }
1447
+ const phaseP95ByName = Object.fromEntries(
1448
+ Object.entries(phaseSamples).map(([phase, samples]) => [phase, nearestRank(samples, 0.95)]),
1449
+ );
1111
1450
  return {
1451
+ ...(clockSamplesMs.length === 0 ? {} : { clockSamplesMs }),
1452
+ ...(sampleCount === 0 ? {} : { clockSource: missingClock ? 'missing' : 'monotonic-performance' }),
1112
1453
  ...(frameIntervalsMs.length === 0 ? {} : { frameIntervalsMs }),
1454
+ ...(hitchCount === 0 ? { hitchCount: 0 } : { hitchCount }),
1113
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 }),
1114
1463
  ...(startupSamplesMs.length === 0 ? {} : { startupSamplesMs, startupMs: startupSamplesMs[0] }),
1115
1464
  ...(timestampMs === 0 ? {} : { durationSeconds: timestampMs / 1_000 }),
1116
1465
  ...(startupSamplesMs.length === 0 ? {} : { startupP95Ms: nearestRank(startupSamplesMs, 0.95) }),
1117
- ...(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
+ }),
1118
1472
  ...(intervals.some(({ drawCalls }) => drawCalls !== undefined) ? { drawCalls: Math.max(...intervals.flatMap(({ drawCalls }) => drawCalls === undefined ? [] : [drawCalls])) } : {}),
1119
1473
  ...(intervals.some(({ triangles }) => triangles !== undefined) ? { triangles: Math.max(...intervals.flatMap(({ triangles }) => triangles === undefined ? [] : [triangles])) } : {}),
1120
1474
  };
@@ -1135,10 +1489,9 @@ function pairMetrics(metrics) {
1135
1489
 
1136
1490
  function identityFor(options, web, native, artifactHashes) {
1137
1491
  const common = {
1138
- deviceClass: options.device === undefined ? 'default-target' : 'selected-target',
1139
- hostClass: `${process.platform}-${process.arch}`,
1140
- osClass: process.platform,
1141
- 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,
1142
1495
  renderHeight: options.renderSize.height,
1143
1496
  renderWidth: options.renderSize.width,
1144
1497
  };
@@ -1151,7 +1504,52 @@ function identityFor(options, web, native, artifactHashes) {
1151
1504
  webProcess: web?.driverClass,
1152
1505
  };
1153
1506
  }
1154
- 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
+ }
1155
1553
  }
1156
1554
 
1157
1555
  function markersFor(arms, codes) {
@@ -1185,6 +1583,8 @@ function profileCommand(options) {
1185
1583
  `--warmup ${options.warmup}`,
1186
1584
  `--repetitions ${options.repetitions}`,
1187
1585
  ...(options.device === undefined ? [] : ['--device <selected>']),
1586
+ ...(options.hostedSoftware ? ['--hosted-software'] : []),
1587
+ ...(options.prebuiltArtifact === undefined ? [] : ['--prebuilt-artifact <existing-build>']),
1188
1588
  ].join(' ');
1189
1589
  }
1190
1590
 
@@ -1380,6 +1780,12 @@ async function playtestRunnerPath(project, tools) {
1380
1780
  }
1381
1781
 
1382
1782
  async function installAndroidArtifact(apk, device) {
1783
+ // The Play Protect verifier dialog is modal and swallows the install, so an unattended
1784
+ // lane behind it proves nothing. Suppress before the install, as every install lane must.
1785
+ const serial = device ?? String(execFileSync('adb', ['get-serialno'], { encoding: 'utf8' })).trim();
1786
+ suppressPlayProtectOnAdbInstalls(serial, {
1787
+ adb: (adbArgs) => String(execFileSync('adb', ['-s', serial, ...adbArgs], { encoding: 'utf8' })),
1788
+ });
1383
1789
  const args = [...(device === undefined ? [] : ['-s', device]), 'install', '-r', apk];
1384
1790
  const result = await runCommand('adb', args, commandRoot);
1385
1791
  if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_ANDROID_INSTALL_FAILED', 'Installing the scaffolded Android platformer failed.');
@@ -1395,6 +1801,11 @@ async function hashPath(path) {
1395
1801
  return sha256(Buffer.from(hashInput.join('\n')));
1396
1802
  }
1397
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
+
1398
1809
  async function listFiles(directory) {
1399
1810
  const entries = await readdir(directory, { withFileTypes: true });
1400
1811
  const files = [];
@@ -1474,7 +1885,7 @@ async function removeMailbox(root) {
1474
1885
  await Promise.all([
1475
1886
  rm(join(root, 'tn-playtest-request.json'), { force: true }),
1476
1887
  rm(join(root, 'tn-playtest-response.json'), { force: true }),
1477
- rm(join(root, 'tn-production-screenshot-request.json'), { force: true }),
1888
+ rm(join(root, 'tn-playtest-screenshot-request.txt'), { force: true }),
1478
1889
  ]);
1479
1890
  }
1480
1891
 
@@ -1512,6 +1923,21 @@ function positiveInteger(value, flag) {
1512
1923
  }
1513
1924
 
1514
1925
  if (process.argv[1] && new URL(`file://${process.argv[1]}`).pathname === new URL(import.meta.url).pathname) {
1926
+ // Gate records are an engine-repository artefact, not something a published install owns. A
1927
+ // package-relative specifier here would ship inside the tarball and die ERR_MODULE_NOT_FOUND on
1928
+ // an installed copy, so the path is resolved against the checkout and its absence is named.
1929
+ const gateRecords = resolve(scriptDirectory, '../../../scripts/gate-records.mjs');
1930
+ if (!existsSync(gateRecords)) {
1931
+ throw new ProductionEvidenceError(
1932
+ 'TN_PROD_GATE_RECORDS_MISSING',
1933
+ `pnpm profile:production records its gate phases through ${gateRecords}, which does not exist. This command runs from a ThreeNative engine checkout, not from an installed @threenative/runtime-native.`,
1934
+ );
1935
+ }
1936
+ const { createGateRecorder } = await import(pathToFileURL(gateRecords).href);
1937
+ const gateRecorder = await createGateRecorder({
1938
+ phase: 'profile-production',
1939
+ command: ['pnpm profile:production', ...process.argv.slice(2)].join(' '),
1940
+ });
1515
1941
  try {
1516
1942
  const result = await runProductionProfile(parseProductionArgs());
1517
1943
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
@@ -1521,5 +1947,8 @@ if (process.argv[1] && new URL(`file://${process.argv[1]}`).pathname === new URL
1521
1947
  const message = error instanceof Error ? error.message : String(error);
1522
1948
  process.stderr.write(`${JSON.stringify({ codes: [code], message, status: 'BLOCKED', exitCode: 2 }, null, 2)}\n`);
1523
1949
  process.exitCode = 2;
1950
+ } finally {
1951
+ // main() communicates its own result through process.exitCode; record what actually ran.
1952
+ await gateRecorder.finish(process.exitCode ?? 0);
1524
1953
  }
1525
1954
  }