@threenative/runtime-native 0.2.0

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.
@@ -0,0 +1,1525 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { createServer } from 'node:http';
4
+ import { execFile, spawn } from 'node:child_process';
5
+ import { existsSync } from 'node:fs';
6
+ import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
7
+ import { createRequire } from 'node:module';
8
+ import { tmpdir } from 'node:os';
9
+ import { basename, dirname, join, relative, resolve } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { promisify } from 'node:util';
12
+ import { PNG } from 'pngjs';
13
+ import { readAndroidConfig } from './package-android.mjs';
14
+
15
+ import {
16
+ PRODUCTION_EVIDENCE_VERSION,
17
+ ProductionEvidenceError,
18
+ meanFps,
19
+ nearestRank,
20
+ sha256,
21
+ writeProductionEvidence,
22
+ } from './production-evidence.mjs';
23
+
24
+ const execFileAsync = promisify(execFile);
25
+ const scriptDirectory = dirname(fileURLToPath(import.meta.url));
26
+ const repositoryRoot = resolve(scriptDirectory, '../../..');
27
+ const inRepositoryCheckout = existsSync(join(repositoryRoot, 'pnpm-workspace.yaml'));
28
+ const commandRoot = inRepositoryCheckout ? repositoryRoot : process.cwd();
29
+ const packageRequire = createRequire(import.meta.url);
30
+ const platformerScenario = 'playtests/performance.playtest.json';
31
+ const nativeTargets = new Set(['android', 'android-physical', 'desktop', 'ios', 'ios-physical']);
32
+ const physicalTargets = new Set(['android-physical', 'ios-physical']);
33
+ const supportedTargets = new Set(['android', 'android-physical', 'desktop', 'desktop-pair', 'fixture', 'ios', 'ios-physical', 'web']);
34
+ const supportedControls = new Set([
35
+ 'claimed-audio-missing-evidence',
36
+ 'dirty-checkout',
37
+ 'disallowed-identifiers',
38
+ 'early-exit',
39
+ 'memory-growth',
40
+ 'missing-marker',
41
+ 'slow-native',
42
+ 'slow-path',
43
+ 'slow-startup',
44
+ 'stale-source-sha',
45
+ 'substitute-emulator-provenance',
46
+ ]);
47
+ const SLOW_FRAME_DELAY_MS = 50;
48
+ const SLOW_FRAME_COUNT = 60;
49
+ const SLOW_STARTUP_DELAY_MS = 5_100;
50
+ const FRAME_SAMPLE_BATCH_SIZE = 30;
51
+ // Android logcat truncates long lines, so native samples use a smaller JSON batch.
52
+ const NATIVE_FRAME_SAMPLE_BATCH_SIZE = 5;
53
+ const DESKTOP_SCREENSHOT_TIMEOUT_MS = 5_000;
54
+
55
+ function installedPackageFile(packageName, file) {
56
+ try {
57
+ return join(dirname(packageRequire.resolve(`${packageName}/package.json`)), file);
58
+ } catch {
59
+ return undefined;
60
+ }
61
+ }
62
+
63
+ export function resolveProductionTools() {
64
+ const localScaffold = join(repositoryRoot, 'packages/create-threenative/dist/index.js');
65
+ const localPlaytest = join(repositoryRoot, 'packages/playtest/dist/runner/cli.js');
66
+ const localRunner = join(repositoryRoot, 'packages/playtest/dist/runner/index.js');
67
+ return {
68
+ playtestCli: inRepositoryCheckout && existsSync(localPlaytest)
69
+ ? localPlaytest
70
+ : installedPackageFile('@threenative/playtest', 'dist/runner/cli.js'),
71
+ playtestRunner: inRepositoryCheckout && existsSync(localRunner)
72
+ ? localRunner
73
+ : installedPackageFile('@threenative/playtest', 'dist/runner/index.js'),
74
+ scaffoldCli: inRepositoryCheckout && existsSync(localScaffold)
75
+ ? localScaffold
76
+ : installedPackageFile('create-threenative', 'dist/index.js'),
77
+ };
78
+ }
79
+
80
+ export function parseProductionArgs(argv = process.argv.slice(2)) {
81
+ const options = {
82
+ audioEvidence: undefined,
83
+ coldStarts: 1,
84
+ config: undefined,
85
+ control: undefined,
86
+ device: undefined,
87
+ duration: 60,
88
+ out: '.runtime/prd064/production',
89
+ physicalEvidence: undefined,
90
+ renderSize: { height: 1080, width: 1920 },
91
+ repetitions: 3,
92
+ sourceSha: undefined,
93
+ target: undefined,
94
+ warmup: 60,
95
+ };
96
+ for (let index = 0; index < argv.length; index += 1) {
97
+ const flag = argv[index];
98
+ 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);
112
+ else if (flag === '--help') return { ...options, help: true };
113
+ else throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', `Unknown production profile option '${flag}'.`);
114
+ }
115
+ if (options.target === undefined) throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', 'Production profile requires --target.');
116
+ return validateProductionOptions(options);
117
+ }
118
+
119
+ export function validateProductionOptions(input) {
120
+ const options = normalizeOptions(input);
121
+ if (options.help) return options;
122
+ if (!supportedTargets.has(options.target)) {
123
+ throw new ProductionEvidenceError('TN_PROD_TARGET_UNSUPPORTED', `Production target '${options.target}' is not supported.`);
124
+ }
125
+ if (options.control !== undefined && !supportedControls.has(options.control)) {
126
+ throw new ProductionEvidenceError('TN_PROD_CONTROL_UNSUPPORTED', `Production control '${options.control}' is not supported.`);
127
+ }
128
+ if (options.target === 'fixture' && options.control === undefined) {
129
+ throw new ProductionEvidenceError('TN_PROD_FIXTURE_CONTROL_REQUIRED', 'The fixture target is available only as an explicit negative control.');
130
+ }
131
+ if (options.device !== undefined && !nativeTargets.has(options.target)) {
132
+ throw new ProductionEvidenceError('TN_PROD_DEVICE_UNSUPPORTED', `--device is not valid for target '${options.target}'.`);
133
+ }
134
+ if ((options.target === 'android' || options.target === 'android-physical') && options.device === undefined) {
135
+ throw new ProductionEvidenceError('TN_PROD_DEVICE_REQUIRED', `Target '${options.target}' requires --device so the selected device is recorded and driven.`);
136
+ }
137
+ if (physicalTargets.has(options.target) && options.device === undefined) {
138
+ throw new ProductionEvidenceError('TN_PROD_DEVICE_REQUIRED', `Target '${options.target}' requires --device.`);
139
+ }
140
+ if (options.target === 'desktop-pair' && options.control === 'slow-native') return options;
141
+ if (options.control === 'slow-native' && options.target !== 'desktop-pair') {
142
+ throw new ProductionEvidenceError('TN_PROD_CONTROL_UNSUPPORTED', "The 'slow-native' control requires --target desktop-pair.");
143
+ }
144
+ if (options.target === 'fixture' && options.device !== undefined) {
145
+ throw new ProductionEvidenceError('TN_PROD_DEVICE_UNSUPPORTED', 'Fixture controls cannot accept --device.');
146
+ }
147
+ if (nativeTargets.has(options.target) && options.target !== 'desktop' && options.target !== 'desktop-pair'
148
+ && (options.renderSize.width !== 1920 || options.renderSize.height !== 1080)) {
149
+ throw new ProductionEvidenceError('TN_PROD_RENDER_SIZE_UNSUPPORTED', `--render-size is not controllable for target '${options.target}'.`);
150
+ }
151
+ return options;
152
+ }
153
+
154
+ export async function runProductionProfile(input, dependencies = {}) {
155
+ const options = validateProductionOptions(input);
156
+ if (options.help) return { help: true, status: 'PASS', exitCode: 0 };
157
+ const sourceState = await currentSourceState();
158
+ const requiredSourceSha = sourceState.sha;
159
+ const sourceSha = options.sourceSha ?? requiredSourceSha;
160
+ const runId = `${options.target}-${Date.now()}`;
161
+ const physicalEvidence = await readPhysicalEvidence(options.physicalEvidence);
162
+ const audioEvidence = await readOptionalArtifact(options.audioEvidence);
163
+ const context = { audioEvidence, physicalEvidence, requiredSourceSha, sourceSha, sourceState };
164
+ const collected = options.target === 'fixture'
165
+ ? await createFixtureControlEvidence(options, context, runId)
166
+ : await (dependencies.collectProduction ?? collectProduction)(options, context, runId);
167
+ const evidence = applyNegativeControl(collected, options.control);
168
+ const result = await writeProductionEvidence(evidence, options.out, { requiredSourceSha });
169
+ return { ...result.manifest, manifestPath: result.manifestPath };
170
+ }
171
+
172
+ export async function collectProduction(options, context, runId) {
173
+ const tools = resolveProductionTools();
174
+ if (tools.scaffoldCli === undefined || !await fileExists(tools.scaffoldCli)) {
175
+ throw new ProductionEvidenceError(
176
+ 'TN_PROD_SCAFFOLDER_UNAVAILABLE',
177
+ "The installed 'create-threenative' package does not expose its built scaffolder; install it or run the repository build first.",
178
+ );
179
+ }
180
+ if (tools.playtestCli === undefined || !await fileExists(tools.playtestCli)) {
181
+ throw new ProductionEvidenceError(
182
+ 'TN_PROD_PLAYTEST_UNAVAILABLE',
183
+ "The installed '@threenative/playtest' package does not expose its built runner; install it or run the repository build first.",
184
+ );
185
+ }
186
+
187
+ const temporaryRoot = await mkdtemp(join(tmpdir(), 'threenative-production-'));
188
+ const project = join(temporaryRoot, 'platformer');
189
+ const startedAt = new Date().toISOString();
190
+ try {
191
+ await scaffoldPlatformer(project, tools);
192
+ const scenarios = await writeRunScenarios(project, options);
193
+ const artifactsRoot = join(project, 'artifacts', 'production');
194
+ await mkdir(artifactsRoot, { recursive: true });
195
+ const web = options.target === 'web' || options.target === 'desktop-pair'
196
+ ? await collectWeb(project, scenarios, artifactsRoot, options, tools)
197
+ : undefined;
198
+ const native = nativeTargets.has(options.target) || options.target === 'desktop-pair'
199
+ ? await collectNative(project, scenarios, artifactsRoot, options, tools)
200
+ : undefined;
201
+ return assembleEvidence({
202
+ context,
203
+ native,
204
+ options,
205
+ performanceBounds: scenarios.performanceBounds,
206
+ project,
207
+ runId,
208
+ startedAt,
209
+ web,
210
+ });
211
+ } finally {
212
+ await rm(temporaryRoot, { force: true, recursive: true });
213
+ }
214
+ }
215
+
216
+ function normalizeOptions(input = {}) {
217
+ const renderSize = typeof input.renderSize === 'string' ? parseRenderSize(input.renderSize) : input.renderSize;
218
+ const target = input.target === 'desktop-web' ? 'web' : input.target;
219
+ return {
220
+ audioEvidence: input.audioEvidence,
221
+ coldStarts: input.coldStarts ?? 1,
222
+ control: input.control,
223
+ device: input.device,
224
+ duration: input.duration ?? 60,
225
+ help: input.help,
226
+ out: input.out ?? '.runtime/prd064/production',
227
+ physicalEvidence: input.physicalEvidence,
228
+ renderSize: renderSize ?? { height: 1080, width: 1920 },
229
+ repetitions: input.repetitions ?? 3,
230
+ sourceSha: input.sourceSha,
231
+ target,
232
+ warmup: input.warmup ?? 60,
233
+ };
234
+ }
235
+
236
+ function warmupFramesFor(options) {
237
+ return Math.max(0, Math.ceil((options.warmup ?? 0) * 60));
238
+ }
239
+
240
+ async function scaffoldPlatformer(project, tools) {
241
+ const packageArchiveRoot = join(project, '..', 'package-archives');
242
+ await mkdir(packageArchiveRoot, { recursive: true });
243
+ const packageSource = async (name, directory) => [name, await packLocalPackage(directory, packageArchiveRoot)];
244
+ const localSources = [];
245
+ 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')));
253
+ }
254
+ const args = [
255
+ tools.scaffoldCli,
256
+ project,
257
+ '--template', 'platformer',
258
+ ...localSources.flatMap(([name, source]) => [packageSourceFlag(name), source]),
259
+ ];
260
+ const result = await runCommand(process.execPath, args, commandRoot);
261
+ if (result.status !== 0) {
262
+ throw new ProductionEvidenceError('TN_PROD_SCAFFOLD_FAILED', 'Scaffolding the production platformer failed.');
263
+ }
264
+ }
265
+
266
+ async function packLocalPackage(directory, destination) {
267
+ const before = new Set(await readdir(destination));
268
+ const result = await runCommand('pnpm', ['pack', '--pack-destination', destination], directory);
269
+ if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' failed.`);
270
+ const archive = (await readdir(destination)).find((entry) => entry.endsWith('.tgz') && !before.has(entry));
271
+ if (archive === undefined) throw new ProductionEvidenceError('TN_PROD_PACKAGE_ARCHIVE_FAILED', `Packing local package '${basename(directory)}' produced no archive.`);
272
+ return join(destination, archive);
273
+ }
274
+
275
+ 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';
289
+ }
290
+
291
+ export async function writeRunScenarios(project, options) {
292
+ const source = JSON.parse(await readFile(join(project, platformerScenario), 'utf8'));
293
+ const sourceAssertions = source.assert && typeof source.assert === 'object' && !Array.isArray(source.assert)
294
+ ? source.assert
295
+ : {};
296
+ const { performance: performanceBounds, ...playtestAssertions } = sourceAssertions;
297
+ const workloadAssertions = Object.keys(playtestAssertions).length === 0
298
+ ? { diagnostics: { noConsoleErrors: true, runtimeReady: true } }
299
+ : playtestAssertions;
300
+ const { assert: _sourceAssertions, ...scenarioSource } = source;
301
+ const workloadFrames = Math.max(1, Math.ceil(options.duration * 60));
302
+ const warmupFrames = Math.max(0, Math.ceil(options.warmup * 60));
303
+ const workload = {
304
+ ...scenarioSource,
305
+ assert: workloadAssertions,
306
+ artifacts: { screenshots: 'after' },
307
+ steps: [
308
+ { holdFrames: Math.min(60, workloadFrames), kind: 'input', press: 'ArrowRight', release: true },
309
+ { kind: 'wait', release: true, waitFrames: workloadFrames },
310
+ ],
311
+ viewport: options.renderSize,
312
+ warmupFrames,
313
+ };
314
+ const nativeTarget = options.target === 'desktop' || options.target === 'desktop-pair' ? 'desktop' : 'device';
315
+ const nativeWorkloadSteps = nativeTarget === 'device'
316
+ ? [
317
+ { holdFrames: Math.min(60, workloadFrames), kind: 'input', press: 'ArrowRight', release: true },
318
+ ...Array.from({ length: Math.max(0, workloadFrames - Math.min(60, workloadFrames)) }, () => ({
319
+ kind: 'wait',
320
+ release: true,
321
+ waitFrames: 1,
322
+ })),
323
+ ]
324
+ : workload.steps;
325
+ const startup = {
326
+ ...scenarioSource,
327
+ assert: { diagnostics: { noConsoleErrors: true, runtimeReady: true } },
328
+ artifacts: { screenshots: 'after' },
329
+ steps: [{ kind: 'wait', release: true, waitFrames: 1 }],
330
+ viewport: options.renderSize,
331
+ warmupFrames: 0,
332
+ };
333
+ const nativeWorkload = {
334
+ ...workload,
335
+ artifacts: { screenshots: nativeTarget === 'desktop' ? 'after' : false },
336
+ steps: nativeWorkloadSteps,
337
+ };
338
+ const nativeStartup = { ...startup, artifacts: { screenshots: 'after' } };
339
+ const workloadPath = join(project, 'playtests/production-performance.run.playtest.json');
340
+ const startupPath = join(project, 'playtests/production-startup.run.playtest.json');
341
+ const nativeWorkloadPath = join(project, 'playtests/production-performance.native.playtest.json');
342
+ const nativeStartupPath = join(project, 'playtests/production-startup.native.playtest.json');
343
+ await writeFile(workloadPath, `${JSON.stringify(workload, null, 2)}\n`);
344
+ await writeFile(startupPath, `${JSON.stringify(startup, null, 2)}\n`);
345
+ await writeFile(nativeWorkloadPath, `${JSON.stringify(nativeWorkload, null, 2)}\n`);
346
+ await writeFile(nativeStartupPath, `${JSON.stringify(nativeStartup, null, 2)}\n`);
347
+ return {
348
+ ...(performanceBounds === undefined ? {} : { performanceBounds }),
349
+ nativeStartupPath,
350
+ nativeWorkloadPath,
351
+ startupPath,
352
+ workloadPath,
353
+ };
354
+ }
355
+
356
+ async function collectWeb(project, scenarios, artifactsRoot, options, tools) {
357
+ const markerServer = await createFrameMarkerServer();
358
+ try {
359
+ await installWebProfileEntry(project, markerServer.url, options.control, warmupFramesFor(options));
360
+ const build = await runCommand('pnpm', ['run', 'build:web'], project);
361
+ if (build.status !== 0) throw new ProductionEvidenceError('TN_PROD_WEB_BUILD_FAILED', 'The scaffolded platformer web build failed.');
362
+ const artifactSha = await hashPath(join(project, 'dist'));
363
+ const runs = [];
364
+ const startups = [];
365
+ for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
366
+ const startup = await runWebScenario(project, scenarios.startupPath, join(artifactsRoot, `web-startup-${coldStart + 1}`), markerServer, tools.playtestCli);
367
+ startups.push(startup);
368
+ for (let repetition = 0; repetition < options.repetitions; repetition += 1) {
369
+ runs.push(await runWebScenario(
370
+ project,
371
+ scenarios.workloadPath,
372
+ join(artifactsRoot, `web-${coldStart + 1}-${repetition + 1}`),
373
+ markerServer,
374
+ tools.playtestCli,
375
+ ));
376
+ }
377
+ }
378
+ return {
379
+ artifactSha,
380
+ applicationClass: 'platformer-web-build',
381
+ driverClass: 'playwright-chromium-webgpu',
382
+ kind: 'web',
383
+ runs,
384
+ startups,
385
+ };
386
+ } finally {
387
+ await markerServer.close();
388
+ }
389
+ }
390
+
391
+ async function runWebScenario(project, scenarioPath, artifactDirectory, markerServer, playtestCli) {
392
+ await mkdir(artifactDirectory, { recursive: true });
393
+ const port = await availablePort();
394
+ const relativeArtifact = relative(project, artifactDirectory);
395
+ const args = [
396
+ playtestCli,
397
+ relative(project, scenarioPath),
398
+ '--artifacts', relativeArtifact,
399
+ '--browser-recipe', 'webgpu',
400
+ '--project', project,
401
+ '--server-command', `pnpm dev --host 127.0.0.1 --port ${port} --strictPort`,
402
+ '--timeout', '30000',
403
+ '--url', `http://127.0.0.1:${port}`,
404
+ ];
405
+ const command = await browserCommand(args);
406
+ const markerIndex = markerServer.length;
407
+ const startedAt = performance.now();
408
+ const result = await runCommand(command.command, command.args, commandRoot, undefined, 180_000);
409
+ const markers = await markerServer.waitFor(markerIndex, 1_000);
410
+ const report = parsePlaytestReport(result.stdout);
411
+ return normalizeRun(
412
+ result,
413
+ artifactDirectory,
414
+ 'web',
415
+ report,
416
+ markers?.firstFrame === undefined ? undefined : markers.firstFrame.receivedAt - startedAt,
417
+ markers?.samples ?? [],
418
+ );
419
+ }
420
+
421
+ async function collectNative(project, scenarios, artifactsRoot, options, tools) {
422
+ const target = options.target === 'desktop-pair' || options.target === 'desktop' ? 'desktop' : options.target.startsWith('ios') ? 'ios' : 'android';
423
+ await installNativeProfileEntry(project, target, options);
424
+ const build = await runCommand('pnpm', ['run', `build:${target}`], project);
425
+ if (build.status !== 0) {
426
+ const details = [build.stdout, build.stderr]
427
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
428
+ .join('\n')
429
+ .trim();
430
+ throw new ProductionEvidenceError(
431
+ `TN_PROD_${target.toUpperCase()}_BUILD_FAILED`,
432
+ `The scaffolded platformer ${target} build failed.${details.length === 0 ? '' : `\n${details.slice(-4_000)}`}`,
433
+ );
434
+ }
435
+ const artifactPath = await nativeArtifactPath(project, target);
436
+ const artifactSha = await hashPath(artifactPath);
437
+ const runs = [];
438
+ const startups = [];
439
+ for (let coldStart = 0; coldStart < options.coldStarts; coldStart += 1) {
440
+ const startup = await runNativeScenario(project, target, scenarios.nativeStartupPath, join(artifactsRoot, `native-startup-${coldStart + 1}`), options, artifactPath, tools);
441
+ startups.push(startup);
442
+ for (let repetition = 0; repetition < options.repetitions; repetition += 1) {
443
+ runs.push(await runNativeScenario(
444
+ project,
445
+ target,
446
+ scenarios.nativeWorkloadPath,
447
+ join(artifactsRoot, `native-${coldStart + 1}-${repetition + 1}`),
448
+ options,
449
+ artifactPath,
450
+ tools,
451
+ ));
452
+ }
453
+ }
454
+ return {
455
+ artifactSha,
456
+ applicationClass: `platformer-${target}-build`,
457
+ driverClass: `threenative-${target}-runtime`,
458
+ kind: target,
459
+ runs,
460
+ startups,
461
+ };
462
+ }
463
+
464
+ async function runNativeScenario(project, target, scenarioPath, artifactDirectory, options, artifactPath, tools) {
465
+ await mkdir(artifactDirectory, { recursive: true });
466
+ if (target === 'desktop') {
467
+ return await runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools);
468
+ }
469
+ const modulePath = await playtestRunnerPath(project, tools);
470
+ if (modulePath === undefined) {
471
+ return { elapsedMs: undefined, report: undefined, screenshot: undefined, series: undefined, status: 2 };
472
+ }
473
+ if (target === 'android') await installAndroidArtifact(artifactPath, options.device);
474
+ // The game declares its identity in `threenative.config.ts` and packaging resolves it; profiling
475
+ // 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;
477
+ const config = {
478
+ android: { activity: 'com.threenative.runtime.MystralActivity', packageName: appId },
479
+ artifactDirectory,
480
+ device: options.device,
481
+ headless: true,
482
+ ios: {
483
+ appPath: target === 'ios' ? artifactPath : undefined,
484
+ bundleId: appId,
485
+ transport: options.target === 'ios-physical' ? 'device' : 'simulator',
486
+ },
487
+ projectPath: project,
488
+ scenarioPath: relative(project, scenarioPath),
489
+ target,
490
+ timeoutMs: 30_000,
491
+ trace: false,
492
+ url: 'http://127.0.0.1:41777',
493
+ };
494
+ const runner = await import(pathToFileURL(modulePath).href);
495
+ const started = performance.now();
496
+ const startedAt = Date.now();
497
+ try {
498
+ const report = target === 'android'
499
+ ? await runner.runAndroidPlaytest(config)
500
+ : await runner.runIosPlaytest(config);
501
+ return normalizeRun(
502
+ { durationMs: performance.now() - started, status: report.pass ? 0 : 1 },
503
+ artifactDirectory,
504
+ target,
505
+ report,
506
+ firstFrameMsFromReport(report, startedAt),
507
+ frameSeriesFromReport(report),
508
+ );
509
+ } catch {
510
+ return { elapsedMs: performance.now() - started, report: undefined, screenshot: undefined, series: undefined, status: 2 };
511
+ }
512
+ }
513
+
514
+ async function runDesktopBridgeScenario(project, scenarioPath, artifactDirectory, options, artifactPath, tools) {
515
+ const modulePath = await playtestRunnerPath(project, tools);
516
+ if (modulePath === undefined) {
517
+ return { elapsedMs: undefined, report: undefined, screenshot: undefined, series: undefined, status: 2 };
518
+ }
519
+ const mailboxRoot = join(project, '.runtime-mailbox');
520
+ await mkdir(mailboxRoot, { recursive: true });
521
+ await removeMailbox(mailboxRoot);
522
+ const requestPath = join(mailboxRoot, 'tn-playtest-request.json');
523
+ const responsePath = join(mailboxRoot, 'tn-playtest-response.json');
524
+ const screenshotRequestPath = join(mailboxRoot, 'tn-production-screenshot-request.json');
525
+ 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);
533
+ const transport = {
534
+ capabilities: innerTransport.capabilities,
535
+ call: innerTransport.call.bind(innerTransport),
536
+ close: innerTransport.close.bind(innerTransport),
537
+ start: async () => {
538
+ await innerTransport.start();
539
+ await driver.launch();
540
+ },
541
+ waitForBridge: innerTransport.waitForBridge.bind(innerTransport),
542
+ };
543
+ const config = {
544
+ artifactDirectory,
545
+ headless: true,
546
+ projectPath: project,
547
+ scenarioPath: relative(project, scenarioPath),
548
+ target: 'android',
549
+ timeoutMs: 30_000,
550
+ trace: false,
551
+ url: 'http://127.0.0.1:41777',
552
+ };
553
+ const started = performance.now();
554
+ const startedAt = Date.now();
555
+ try {
556
+ const report = await runner.runDevicePlaytest(config, {
557
+ driver,
558
+ mailboxPaths: { request: requestPath, response: responsePath },
559
+ name: 'desktop',
560
+ processName: 'threenative-platformer-desktop',
561
+ transport,
562
+ });
563
+ return normalizeRun(
564
+ { durationMs: performance.now() - started, status: report.pass ? 0 : 1 },
565
+ artifactDirectory,
566
+ 'desktop',
567
+ report,
568
+ firstFrameMsFromReport(report, startedAt),
569
+ frameSeriesFromReport(report),
570
+ );
571
+ } catch {
572
+ await driver.stop();
573
+ return { elapsedMs: performance.now() - started, report: undefined, screenshot: undefined, series: undefined, status: 2 };
574
+ }
575
+ }
576
+
577
+ export function profileConfigPath(project, configPath = undefined) {
578
+ return configPath ?? join(project, '.threenative', 'build', 'config.json');
579
+ }
580
+
581
+ function createDesktopDriver(artifactPath, project, options, screenshotRequestPath) {
582
+ let child;
583
+ let output = '';
584
+ return {
585
+ captureConsole: async () => output.split(/\r?\n/u).filter(Boolean).map((text) => ({ text, type: /\b(?:Error|FAILED|FATAL)\b/u.test(text) ? 'error' : 'log' })),
586
+ isAlive: async () => child !== undefined && child.exitCode === null,
587
+ launch: async () => {
588
+ child = spawnNative(artifactPath, project, options);
589
+ child.stdout?.on('data', (chunk) => { output += chunk.toString(); });
590
+ child.stderr?.on('data', (chunk) => { output += chunk.toString(); });
591
+ await new Promise((resolve, reject) => {
592
+ child.once('spawn', resolve);
593
+ child.once('error', reject);
594
+ });
595
+ },
596
+ prepare: async () => undefined,
597
+ readFile: async (path) => readFile(path, 'utf8').catch((error) => error?.code === 'ENOENT' ? undefined : Promise.reject(error)),
598
+ removeFile: async (path) => rm(path, { force: true }).catch(() => undefined),
599
+ screenshot: async (path) => {
600
+ const temporary = `${screenshotRequestPath}.tmp`;
601
+ await writeFile(temporary, JSON.stringify({ path }), 'utf8');
602
+ await rename(temporary, screenshotRequestPath);
603
+ const deadline = Date.now() + DESKTOP_SCREENSHOT_TIMEOUT_MS;
604
+ while (Date.now() < deadline) {
605
+ if (await nonBlankPng(path)) return;
606
+ await new Promise((resolve) => setTimeout(resolve, 25));
607
+ }
608
+ throw new Error('TN_PROD_NATIVE_SCREENSHOT_UNAVAILABLE');
609
+ },
610
+ 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));
615
+ },
616
+ writeFile: async (path, contents) => writeFile(path, contents, 'utf8'),
617
+ };
618
+ }
619
+
620
+ function spawnNative(artifactPath, project, options) {
621
+ const bundle = join(project, '.threenative/build/game.js');
622
+ const nativeArgs = [
623
+ 'run',
624
+ bundle,
625
+ '--width', String(options.renderSize.width),
626
+ '--height', String(options.renderSize.height),
627
+ '--headless',
628
+ ];
629
+ const command = process.platform === 'linux' && process.env.DISPLAY === undefined ? 'xvfb-run' : artifactPath;
630
+ const args = command === 'xvfb-run' ? ['-a', '-s', '-screen 0 1600x900x24', artifactPath, ...nativeArgs] : nativeArgs;
631
+ return spawn(command, args, {
632
+ cwd: project,
633
+ detached: process.platform !== 'win32',
634
+ env: { ...process.env, SDL_VIDEODRIVER: process.platform === 'linux' ? 'x11' : process.env.SDL_VIDEODRIVER },
635
+ stdio: ['ignore', 'pipe', 'pipe'],
636
+ });
637
+ }
638
+
639
+ async function installNativeProfileEntry(project, target, options) {
640
+ const entryPath = join(project, 'src/profile-native-entry.ts');
641
+ const mailboxRoot = join(project, '.runtime-mailbox');
642
+ 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`
644
+ : '';
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`;
647
+ await writeFile(entryPath, source);
648
+ await setNativeProfileEntry(project, 'src/profile-native-entry.ts');
649
+ }
650
+
651
+ export async function setNativeProfileEntry(project, entry) {
652
+ const configPath = join(project, 'threenative.config.ts');
653
+ const packagePath = join(project, 'package.json');
654
+ const config = await readFile(configPath, 'utf8').catch(() => undefined);
655
+ if (config !== undefined) {
656
+ const rendered = config.replace(
657
+ /^(\s*nativeEntry\s*:\s*)["'][^"']*["'](,?.*)$/mu,
658
+ `$1"${entry}"$2`,
659
+ );
660
+ if (rendered !== config) {
661
+ await writeFile(configPath, rendered);
662
+ const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
663
+ if (packageJson.threenative?.nativeEntry !== undefined) {
664
+ delete packageJson.threenative.nativeEntry;
665
+ if (Object.keys(packageJson.threenative).length === 0) delete packageJson.threenative;
666
+ await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
667
+ }
668
+ return;
669
+ }
670
+ }
671
+ const packageJson = JSON.parse(await readFile(packagePath, 'utf8'));
672
+ packageJson.threenative = { ...packageJson.threenative, nativeEntry: entry };
673
+ await writeFile(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
674
+ }
675
+
676
+ function productionPerformanceReader() {
677
+ return `
678
+ const tnProductionReadPerformance = () => {
679
+ const bridge = globalThis.__THREENATIVE_PLAYTEST_BRIDGE__;
680
+ if (typeof bridge?.sample !== "function") return {};
681
+ try {
682
+ const snapshot = bridge.sample({});
683
+ if (snapshot === null || typeof snapshot !== "object" || typeof snapshot.then === "function") return {};
684
+ const performance = snapshot.performance;
685
+ return {
686
+ ...(Number.isFinite(performance?.drawCalls) ? { drawCalls: performance.drawCalls } : {}),
687
+ ...(Number.isFinite(performance?.triangles) ? { triangles: performance.triangles } : {}),
688
+ };
689
+ } catch {
690
+ return {};
691
+ }
692
+ };
693
+ `;
694
+ }
695
+
696
+ export function nativeFrameInstrumentation(control, warmupFrames = 0, screenshotRequestPath = undefined) {
697
+ return `
698
+ const tnProductionControl = ${JSON.stringify(control ?? '')};
699
+ const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
700
+ const tnProductionScreenshotRequestPath = ${JSON.stringify(screenshotRequestPath)};
701
+ const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
702
+ if (typeof tnProductionRequestAnimationFrame !== "function") {
703
+ throw new Error("TN_PROD_NATIVE_RAF_UNAVAILABLE: native host did not provide requestAnimationFrame.");
704
+ }
705
+ let tnProductionFirstFrame = true;
706
+ let tnProductionFrameIndex = 0;
707
+ let tnProductionPreviousFrame;
708
+ let tnProductionSamples = [];
709
+ let tnProductionSlowFramesRemaining = ${SLOW_FRAME_COUNT};
710
+ const tnProductionBusyWait = (milliseconds) => {
711
+ const deadline = performance.now() + milliseconds;
712
+ while (performance.now() < deadline) {}
713
+ };
714
+ ${productionPerformanceReader()}
715
+ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
716
+ const frameIndex = tnProductionFrameIndex++;
717
+ const inWarmup = frameIndex < tnProductionWarmupFrames;
718
+ if (frameIndex === tnProductionWarmupFrames) {
719
+ tnProductionPreviousFrame = undefined;
720
+ tnProductionSamples = [];
721
+ }
722
+ if (tnProductionFirstFrame && tnProductionControl === "slow-startup") tnProductionBusyWait(${SLOW_STARTUP_DELAY_MS});
723
+ const now = performance.now();
724
+ const frameMs = inWarmup || tnProductionPreviousFrame === undefined ? undefined : now - tnProductionPreviousFrame;
725
+ tnProductionPreviousFrame = now;
726
+ callback(timestamp);
727
+ if (tnProductionFirstFrame) {
728
+ tnProductionFirstFrame = false;
729
+ console.log("TN_PROD_FIRST_NONBLANK_FRAME:" + Date.now());
730
+ }
731
+ if (!inWarmup && frameMs !== undefined) {
732
+ tnProductionSamples.push({ ...tnProductionReadPerformance(), frameIndex, frameMs });
733
+ if (tnProductionSamples.length >= ${NATIVE_FRAME_SAMPLE_BATCH_SIZE}) {
734
+ console.log("TN_PROD_FRAME_SAMPLES:" + JSON.stringify(tnProductionSamples));
735
+ tnProductionSamples = [];
736
+ }
737
+ }
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
+ if (!inWarmup && tnProductionControl === "slow-native" && tnProductionSlowFramesRemaining > 0) {
753
+ tnProductionBusyWait(${SLOW_FRAME_DELAY_MS});
754
+ tnProductionSlowFramesRemaining -= 1;
755
+ }
756
+ });
757
+ `;
758
+ }
759
+
760
+ export function webFrameInstrumentation(markerUrl, control, warmupFrames = 0) {
761
+ return `
762
+ const tnProductionControl = ${JSON.stringify(control ?? '')};
763
+ const tnProductionWarmupFrames = ${Math.max(0, Math.floor(warmupFrames))};
764
+ const tnProductionMarkerUrl = ${JSON.stringify(markerUrl)};
765
+ const tnProductionRequestAnimationFrame = globalThis.requestAnimationFrame;
766
+ if (typeof tnProductionRequestAnimationFrame !== "function") {
767
+ throw new Error("TN_PROD_WEB_RAF_UNAVAILABLE: browser host did not provide requestAnimationFrame.");
768
+ }
769
+ let tnProductionFirstFrame = true;
770
+ let tnProductionFrameIndex = 0;
771
+ let tnProductionPreviousFrame;
772
+ let tnProductionSamples = [];
773
+ let tnProductionSlowFramesRemaining = ${SLOW_FRAME_COUNT};
774
+ const tnProductionBusyWait = (milliseconds) => {
775
+ const deadline = performance.now() + milliseconds;
776
+ while (performance.now() < deadline) {}
777
+ };
778
+ const tnProductionPost = (payload) => {
779
+ void fetch(tnProductionMarkerUrl, {
780
+ body: JSON.stringify(payload),
781
+ keepalive: true,
782
+ method: "POST",
783
+ mode: "no-cors",
784
+ }).catch(() => undefined);
785
+ };
786
+ ${productionPerformanceReader()}
787
+ globalThis.requestAnimationFrame = (callback) => tnProductionRequestAnimationFrame((timestamp) => {
788
+ const frameIndex = tnProductionFrameIndex++;
789
+ const inWarmup = frameIndex < tnProductionWarmupFrames;
790
+ if (frameIndex === tnProductionWarmupFrames) {
791
+ tnProductionPreviousFrame = undefined;
792
+ tnProductionSamples = [];
793
+ }
794
+ if (tnProductionFirstFrame && tnProductionControl === "slow-startup") tnProductionBusyWait(${SLOW_STARTUP_DELAY_MS});
795
+ const now = performance.now();
796
+ const frameMs = inWarmup || tnProductionPreviousFrame === undefined ? undefined : now - tnProductionPreviousFrame;
797
+ tnProductionPreviousFrame = now;
798
+ callback(timestamp);
799
+ if (tnProductionFirstFrame) {
800
+ tnProductionFirstFrame = false;
801
+ tnProductionPost({ kind: "first-frame" });
802
+ }
803
+ if (!inWarmup && frameMs !== undefined) {
804
+ tnProductionSamples.push({ ...tnProductionReadPerformance(), frameIndex, frameMs });
805
+ if (tnProductionSamples.length >= ${FRAME_SAMPLE_BATCH_SIZE}) {
806
+ tnProductionPost({ kind: "samples", samples: tnProductionSamples });
807
+ tnProductionSamples = [];
808
+ }
809
+ }
810
+ if (!inWarmup && tnProductionControl === "slow-path" && tnProductionSlowFramesRemaining > 0) {
811
+ tnProductionBusyWait(${SLOW_FRAME_DELAY_MS});
812
+ tnProductionSlowFramesRemaining -= 1;
813
+ }
814
+ });
815
+ `;
816
+ }
817
+
818
+ async function installWebProfileEntry(project, markerUrl, control, warmupFrames = 0) {
819
+ const markerPath = join(project, 'src/profile-production-marker.ts');
820
+ const mainPath = join(project, 'src/main.ts');
821
+ const markerImport = 'import "./profile-production-marker.js";';
822
+ const main = await readFile(mainPath, 'utf8');
823
+ const source = webFrameInstrumentation(markerUrl, control, warmupFrames);
824
+ await writeFile(markerPath, source);
825
+ if (!main.includes(markerImport)) await writeFile(mainPath, `${markerImport}\n${main}`);
826
+ }
827
+
828
+ async function createFrameMarkerServer() {
829
+ const events = [];
830
+ const waiters = [];
831
+ const server = createServer((request, response) => {
832
+ if (request.method !== 'POST') {
833
+ response.writeHead(405).end();
834
+ return;
835
+ }
836
+ const chunks = [];
837
+ request.on('data', (chunk) => chunks.push(chunk));
838
+ request.on('end', () => {
839
+ let payload = {};
840
+ try {
841
+ payload = JSON.parse(Buffer.concat(chunks).toString('utf8'));
842
+ } catch {
843
+ // The request is still a first-frame signal even if the optional batch is malformed.
844
+ }
845
+ const event = { ...payload, receivedAt: performance.now() };
846
+ events.push(event);
847
+ for (const waiter of waiters.splice(0)) waiter();
848
+ response.setHeader('access-control-allow-origin', '*');
849
+ response.writeHead(204).end();
850
+ });
851
+ });
852
+ await new Promise((resolve, reject) => {
853
+ server.once('error', reject);
854
+ server.listen(0, '127.0.0.1', resolve);
855
+ });
856
+ const address = server.address();
857
+ 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.');
858
+ return {
859
+ close: () => new Promise((resolve) => server.close(() => resolve())),
860
+ get length() { return events.length; },
861
+ url: `http://127.0.0.1:${address.port}/first-frame`,
862
+ waitFor: async (from, timeoutMs) => {
863
+ if (events.length > from) return markerEvents(events.slice(from));
864
+ await new Promise((resolve) => {
865
+ const timer = setTimeout(resolve, timeoutMs);
866
+ const waiter = () => {
867
+ clearTimeout(timer);
868
+ resolve();
869
+ };
870
+ waiters.push(waiter);
871
+ });
872
+ return markerEvents(events.slice(from));
873
+ },
874
+ };
875
+ }
876
+
877
+ function markerEvents(events) {
878
+ const firstFrame = events.find(({ kind }) => kind === 'first-frame');
879
+ const samples = events.flatMap(({ kind, samples: batch }) => kind === 'samples' && Array.isArray(batch) ? batch : []);
880
+ return { firstFrame, samples };
881
+ }
882
+
883
+ async function normalizeRun(
884
+ result,
885
+ artifactDirectory,
886
+ kind,
887
+ report = undefined,
888
+ firstFrameMs = undefined,
889
+ collectedSeries = [],
890
+ ) {
891
+ const reportSeries = report?.observations?.visual?.runtimeDiagnosticsSeries;
892
+ const performanceSeries = report?.observations?.performanceSeries;
893
+ const consoleSeries = frameSeriesFromReport(report);
894
+ const series = [collectedSeries, reportSeries, performanceSeries, consoleSeries]
895
+ .find((candidate) => Array.isArray(candidate) && candidate.length > 0);
896
+ const screenshotPath = join(artifactDirectory, 'after.png');
897
+ const screenshot = await nonBlankPng(screenshotPath) ? await readFile(screenshotPath) : undefined;
898
+ return {
899
+ elapsedMs: result.durationMs,
900
+ ...(Number.isFinite(firstFrameMs) ? { firstFrameMs } : {}),
901
+ kind,
902
+ report: report === undefined ? undefined : safeReport(report),
903
+ screenshot,
904
+ series: Array.isArray(series) ? series : undefined,
905
+ status: result.status,
906
+ };
907
+ }
908
+
909
+ function safeReport(report) {
910
+ return {
911
+ assertionResults: report.assertionResults,
912
+ diagnostics: report.diagnostics,
913
+ observations: report.observations,
914
+ pass: report.pass,
915
+ scenario: report.scenario,
916
+ target: report.target,
917
+ };
918
+ }
919
+
920
+ function parsePlaytestReport(stdout) {
921
+ const text = typeof stdout === 'string' ? stdout.trim() : '';
922
+ if (text.length === 0) return undefined;
923
+ try {
924
+ return JSON.parse(text);
925
+ } catch {
926
+ for (const line of text.split(/\r?\n/u).reverse()) {
927
+ if (!line.trim().startsWith('{')) continue;
928
+ try {
929
+ return JSON.parse(line);
930
+ } catch {
931
+ continue;
932
+ }
933
+ }
934
+ }
935
+ return undefined;
936
+ }
937
+
938
+ function reportConsoleLines(report) {
939
+ return (report?.observations?.console ?? [])
940
+ .map((entry) => typeof entry?.text === 'string' ? entry.text : '')
941
+ .filter(Boolean);
942
+ }
943
+
944
+ function firstFrameMsFromReport(report, startedAt) {
945
+ const line = reportConsoleLines(report).find((entry) => entry.includes('TN_PROD_FIRST_NONBLANK_FRAME:'));
946
+ const timestamp = line === undefined ? undefined : Number(line.split('TN_PROD_FIRST_NONBLANK_FRAME:').at(-1));
947
+ if (!Number.isFinite(timestamp)) return undefined;
948
+ const elapsed = timestamp - startedAt;
949
+ return elapsed >= 0 ? elapsed : undefined;
950
+ }
951
+
952
+ function frameSeriesFromReport(report) {
953
+ const series = [];
954
+ for (const line of reportConsoleLines(report)) {
955
+ const prefix = 'TN_PROD_FRAME_SAMPLES:';
956
+ const offset = line.indexOf(prefix);
957
+ if (offset === -1) continue;
958
+ try {
959
+ const batch = JSON.parse(line.slice(offset + prefix.length));
960
+ if (Array.isArray(batch)) series.push(...batch);
961
+ } catch {
962
+ continue;
963
+ }
964
+ }
965
+ return series.length === 0 ? undefined : series;
966
+ }
967
+
968
+ export function assembleEvidence({ context, native, options, performanceBounds, project, runId, startedAt, web }) {
969
+ const arms = [web, native].filter((arm) => arm !== undefined);
970
+ const expectedRuns = options.coldStarts * options.repetitions;
971
+ const codes = [];
972
+ const rawArtifacts = [];
973
+ for (const arm of arms) {
974
+ if (arm.runs.some(({ series }) => !Array.isArray(series) || series.length === 0)) codes.push('TN_PROD_RENDER_SAMPLES_INCOMPLETE');
975
+ if (arm.startups.length !== options.coldStarts || arm.startups.some((sample) => !isSuccessfulStartupSample(sample))) {
976
+ codes.push('TN_PROD_STARTUP_SAMPLES_INCOMPLETE');
977
+ }
978
+ if (arm.runs.length !== expectedRuns || arm.runs.some(({ report, status }) => status !== 0 || report?.pass !== true)) {
979
+ codes.push('TN_PROD_PLAYTEST_FAILED');
980
+ }
981
+ for (const [index, run] of arm.runs.entries()) {
982
+ if (run.screenshot !== undefined) rawArtifacts.push({ content: run.screenshot, label: `production-render-${arm.kind}-${index + 1}` });
983
+ if (run.report !== undefined) rawArtifacts.push({ content: JSON.stringify(run.report), label: `production-playtest-${arm.kind}-${index + 1}` });
984
+ }
985
+ for (const [index, startup] of arm.startups.entries()) {
986
+ if (startup.screenshot !== undefined) rawArtifacts.push({ content: startup.screenshot, label: `production-first-frame-${arm.kind}-${index + 1}` });
987
+ if (startup.report !== undefined) rawArtifacts.push({ content: JSON.stringify(startup.report), label: `production-startup-${arm.kind}-${index + 1}` });
988
+ }
989
+ }
990
+ const metricsByArm = new Map(arms.map((arm) => [arm.kind, aggregateMetrics(arm.runs, arm.startups, warmupFramesFor(options))]));
991
+ const webMetrics = metricsByArm.get('web');
992
+ const nativeMetrics = metricsByArm.get('desktop') ?? metricsByArm.get('android') ?? metricsByArm.get('ios');
993
+ const metrics = {
994
+ ...(webMetrics ?? nativeMetrics ?? emptyMetrics()),
995
+ ...(webMetrics === undefined ? {} : { web: pairMetrics(webMetrics) }),
996
+ ...(nativeMetrics === undefined ? {} : { native: pairMetrics(nativeMetrics) }),
997
+ };
998
+ const artifactHashes = arms.map(({ artifactSha }) => artifactSha);
999
+ const target = options.target;
1000
+ const identity = identityFor(options, web, native, artifactHashes);
1001
+ const evidence = {
1002
+ artifact: {
1003
+ applicationClass: target === 'desktop-pair' ? 'platformer-desktop-pair' : arms[0]?.applicationClass ?? 'platformer-production',
1004
+ sha256: sha256(Buffer.from(artifactHashes.join(':'))),
1005
+ signed: context.physicalEvidence.physicalEvidenceClass === 'physical-hardware',
1006
+ },
1007
+ artifacts: [],
1008
+ budget: {
1009
+ maxP99FrameMs: 33,
1010
+ maxStartupMs: target.includes('physical') ? 8_000 : 5_000,
1011
+ minMeanFps: target.includes('physical') ? 59.4 : 60,
1012
+ ...productionPerformanceBudget(performanceBounds),
1013
+ },
1014
+ command: profileCommand(options),
1015
+ codes: [...new Set(codes)],
1016
+ evidenceClasses: ['production'],
1017
+ execution: {
1018
+ coldStarts: options.coldStarts,
1019
+ ...(options.control === undefined ? {} : { control: options.control }),
1020
+ deviceSelected: options.device !== undefined,
1021
+ renderSize: `${options.renderSize.width}x${options.renderSize.height}`,
1022
+ repetitions: options.repetitions,
1023
+ warmupSeconds: options.warmup,
1024
+ },
1025
+ identity,
1026
+ markers: markersFor(arms, codes),
1027
+ metrics,
1028
+ physical: physicalEvidenceFor(options, context),
1029
+ rawArtifacts,
1030
+ runId,
1031
+ source: {
1032
+ dirty: context.sourceState.dirty,
1033
+ ...(context.sourceState.diffSha === undefined ? {} : { diffSha: context.sourceState.diffSha }),
1034
+ sha: context.sourceSha,
1035
+ },
1036
+ target,
1037
+ timestamps: { endedAt: new Date().toISOString(), startedAt },
1038
+ version: PRODUCTION_EVIDENCE_VERSION,
1039
+ };
1040
+ if (options.audioEvidence !== undefined) {
1041
+ evidence.audioClaim = 'claimed';
1042
+ if (context.audioEvidence.audioEvidenceHash !== undefined) evidence.audioEvidenceSha256 = context.audioEvidence.audioEvidenceHash;
1043
+ } else {
1044
+ evidence.audioClaim = 'excluded-by-target-support-matrix';
1045
+ }
1046
+ if (target.includes('physical')) evidence.evidenceClasses = ['production', context.physicalEvidence.physicalEvidenceClass ?? 'missing-physical-evidence'];
1047
+ return evidence;
1048
+ }
1049
+
1050
+ function productionPerformanceBudget(bounds) {
1051
+ if (bounds === undefined) return {};
1052
+ if (typeof bounds !== 'object' || bounds === null || Array.isArray(bounds)) {
1053
+ throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', 'The source performance bounds must be an object.');
1054
+ }
1055
+ const keys = ['maxDrawCalls', 'maxFrameMsP95', 'maxTriangles'];
1056
+ const unknown = Object.keys(bounds).filter((key) => !keys.includes(key));
1057
+ if (unknown.length > 0) {
1058
+ throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', `The source performance bounds contain unsupported keys: ${unknown.join(', ')}.`);
1059
+ }
1060
+ return Object.fromEntries(keys.flatMap((key) => {
1061
+ const value = bounds[key];
1062
+ if (value === undefined) return [];
1063
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {
1064
+ throw new ProductionEvidenceError('TN_PROD_PERFORMANCE_BUDGET_INVALID', `The source performance bound '${key}' must be a finite non-negative number.`);
1065
+ }
1066
+ return [[key, value]];
1067
+ }));
1068
+ }
1069
+
1070
+ export function isSuccessfulStartupSample(sample) {
1071
+ return sample?.status === 0
1072
+ && sample?.report?.pass === true
1073
+ && isNonBlankFrame(sample.screenshot)
1074
+ && Number.isFinite(sample.firstFrameMs)
1075
+ && sample.firstFrameMs >= 0;
1076
+ }
1077
+
1078
+ export function postWarmupFrameSamples(samples, warmupFrames = 0) {
1079
+ if (!Array.isArray(samples)) return [];
1080
+ const boundary = Math.max(0, Math.floor(warmupFrames));
1081
+ if (boundary === 0) return samples;
1082
+ if (!samples.some((sample) => Number.isFinite(sample?.frameIndex))) return samples.slice(boundary);
1083
+ return samples.filter((sample) => Number.isFinite(sample?.frameIndex) && sample.frameIndex > boundary);
1084
+ }
1085
+
1086
+ export function aggregateMetrics(runs, startups, warmupFrames = 0) {
1087
+ const intervals = [];
1088
+ const frameIntervalsMs = [];
1089
+ const startupSamplesMs = startups
1090
+ .filter(isSuccessfulStartupSample)
1091
+ .map(({ firstFrameMs }) => firstFrameMs);
1092
+ let timestampMs = 0;
1093
+ let sequence = 1;
1094
+ for (const run of runs) {
1095
+ for (const sample of postWarmupFrameSamples(run.series ?? [], warmupFrames)) {
1096
+ if (typeof sample?.frameMs !== 'number') {
1097
+ frameIntervalsMs.push(sample?.frameMs);
1098
+ continue;
1099
+ }
1100
+ frameIntervalsMs.push(sample.frameMs);
1101
+ intervals.push({
1102
+ ...(typeof sample.drawCalls === 'number' ? { drawCalls: sample.drawCalls } : {}),
1103
+ frameMs: sample.frameMs,
1104
+ sequence: sequence++,
1105
+ timestampMs,
1106
+ ...(typeof sample.triangles === 'number' ? { triangles: sample.triangles } : {}),
1107
+ });
1108
+ timestampMs += sample.frameMs;
1109
+ }
1110
+ }
1111
+ return {
1112
+ ...(frameIntervalsMs.length === 0 ? {} : { frameIntervalsMs }),
1113
+ ...(intervals.length === 0 ? {} : { intervals }),
1114
+ ...(startupSamplesMs.length === 0 ? {} : { startupSamplesMs, startupMs: startupSamplesMs[0] }),
1115
+ ...(timestampMs === 0 ? {} : { durationSeconds: timestampMs / 1_000 }),
1116
+ ...(startupSamplesMs.length === 0 ? {} : { startupP95Ms: nearestRank(startupSamplesMs, 0.95) }),
1117
+ ...(frameIntervalsMs.length === 0 ? {} : { meanFps: meanFps(frameIntervalsMs), p99FrameMs: nearestRank(frameIntervalsMs, 0.99) }),
1118
+ ...(intervals.some(({ drawCalls }) => drawCalls !== undefined) ? { drawCalls: Math.max(...intervals.flatMap(({ drawCalls }) => drawCalls === undefined ? [] : [drawCalls])) } : {}),
1119
+ ...(intervals.some(({ triangles }) => triangles !== undefined) ? { triangles: Math.max(...intervals.flatMap(({ triangles }) => triangles === undefined ? [] : [triangles])) } : {}),
1120
+ };
1121
+ }
1122
+
1123
+ function emptyMetrics() {
1124
+ return { frameIntervalsMs: [], intervals: [], startupSamplesMs: [] };
1125
+ }
1126
+
1127
+ function pairMetrics(metrics) {
1128
+ return {
1129
+ meanFps: metrics.meanFps,
1130
+ p50FrameMs: nearestRank(metrics.frameIntervalsMs, 0.5),
1131
+ p95FrameMs: nearestRank(metrics.frameIntervalsMs, 0.95),
1132
+ p99FrameMs: metrics.p99FrameMs ?? nearestRank(metrics.frameIntervalsMs, 0.99),
1133
+ };
1134
+ }
1135
+
1136
+ function identityFor(options, web, native, artifactHashes) {
1137
+ const common = {
1138
+ deviceClass: options.device === undefined ? 'default-target' : 'selected-target',
1139
+ hostClass: `${process.platform}-${process.arch}`,
1140
+ osClass: process.platform,
1141
+ refreshHz: 60,
1142
+ renderHeight: options.renderSize.height,
1143
+ renderWidth: options.renderSize.width,
1144
+ };
1145
+ if (options.target === 'desktop-pair') {
1146
+ return {
1147
+ ...common,
1148
+ nativeArtifactSha256: native?.artifactSha,
1149
+ nativeProcess: native?.driverClass,
1150
+ webArtifactSha256: web?.artifactSha,
1151
+ webProcess: web?.driverClass,
1152
+ };
1153
+ }
1154
+ return { ...common, artifactSha256: artifactHashes[0], executableClass: web?.driverClass ?? native?.driverClass };
1155
+ }
1156
+
1157
+ function markersFor(arms, codes) {
1158
+ const allRuns = arms.flatMap(({ runs }) => runs);
1159
+ const allStartups = arms.flatMap(({ startups }) => startups);
1160
+ const workloadSamplesComplete = allRuns.length > 0 && allRuns.every(({ series }) => Array.isArray(series) && series.length > 0);
1161
+ const startupSamplesComplete = allStartups.length > 0 && allStartups.every(isSuccessfulStartupSample);
1162
+ const clean = allRuns.length > 0 && allRuns.every(({ status, report }) => status === 0 && report?.pass === true);
1163
+ return [
1164
+ 'run-start',
1165
+ ...(workloadSamplesComplete && !codes.includes('TN_PROD_RENDER_SAMPLES_INCOMPLETE') ? ['first-workload-frame'] : []),
1166
+ ...(startupSamplesComplete && clean ? ['clean-end'] : []),
1167
+ ];
1168
+ }
1169
+
1170
+ function physicalEvidenceFor(options, context) {
1171
+ if (!options.target.includes('physical')) return undefined;
1172
+ return {
1173
+ evidenceSha256: context.physicalEvidence.physicalEvidenceHash,
1174
+ modelClass: context.physicalEvidence.physicalEvidenceClass ?? 'missing-physical-evidence',
1175
+ provenance: context.physicalEvidence.physicalEvidenceClass ?? 'missing',
1176
+ };
1177
+ }
1178
+
1179
+ function profileCommand(options) {
1180
+ return [
1181
+ 'pnpm profile:production --',
1182
+ `--target ${options.target}`,
1183
+ `--render-size ${options.renderSize.width}x${options.renderSize.height}`,
1184
+ `--cold-starts ${options.coldStarts}`,
1185
+ `--warmup ${options.warmup}`,
1186
+ `--repetitions ${options.repetitions}`,
1187
+ ...(options.device === undefined ? [] : ['--device <selected>']),
1188
+ ].join(' ');
1189
+ }
1190
+
1191
+ async function createFixtureControlEvidence(options, context, runId) {
1192
+ const intervals = await collectFixtureFrameSeries(options.control);
1193
+ const startups = [];
1194
+ for (let index = 0; index < options.coldStarts; index += 1) startups.push(await collectFixtureStartup(options.control));
1195
+ const run = { report: { pass: true }, screenshot: fixtureFrame(), series: intervals, status: 0 };
1196
+ const metrics = {
1197
+ ...aggregateMetrics([run], startups),
1198
+ durationSeconds: options.duration,
1199
+ memory: { complete: true, growthBytes: 0, highWaterBytes: 1, first15MedianBytes: 1, last15MedianBytes: 1, slopeBytesPerMinute: 0 },
1200
+ thermal: { complete: true, samples: 1 },
1201
+ };
1202
+ return {
1203
+ artifact: { applicationClass: 'fixture-negative-control', sha256: sha256(Buffer.from('fixture-negative-control')), signed: false },
1204
+ artifacts: [],
1205
+ budget: { maxP99FrameMs: 33, maxStartupMs: 5_000, minMeanFps: 60 },
1206
+ command: profileCommand(options),
1207
+ evidenceClasses: ['negative-control'],
1208
+ execution: {
1209
+ coldStarts: options.coldStarts,
1210
+ deviceSelected: false,
1211
+ fixtureControl: true,
1212
+ renderSize: `${options.renderSize.width}x${options.renderSize.height}`,
1213
+ repetitions: options.repetitions,
1214
+ warmupSeconds: options.warmup,
1215
+ },
1216
+ identity: { driverClass: 'fixture-control', hostClass: 'fixture-control', osClass: 'fixture-control' },
1217
+ markers: markersFor([{ runs: [run], startups }], []),
1218
+ metrics,
1219
+ rawArtifacts: [
1220
+ { content: fixtureFrame(), label: 'fixture-first-frame' },
1221
+ { content: JSON.stringify({ control: options.control, metrics }), label: 'explicit-negative-control' },
1222
+ ],
1223
+ runId,
1224
+ source: { dirty: context.sourceState.dirty, ...(context.sourceState.diffSha === undefined ? {} : { diffSha: context.sourceState.diffSha }), sha: context.sourceSha },
1225
+ target: 'fixture',
1226
+ timestamps: { endedAt: new Date().toISOString(), startedAt: new Date().toISOString() },
1227
+ version: PRODUCTION_EVIDENCE_VERSION,
1228
+ };
1229
+ }
1230
+
1231
+ async function collectFixtureFrameSeries(control) {
1232
+ const intervals = Array.from({ length: 120 }, (_, index) => ({
1233
+ frameMs: 16.5,
1234
+ sequence: index + 1,
1235
+ timestampMs: index * 16.5,
1236
+ }));
1237
+ if (control !== 'slow-path') return intervals;
1238
+ for (const index of [intervals.length - 2, intervals.length - 1]) {
1239
+ const startedAt = performance.now();
1240
+ await new Promise((resolve) => setTimeout(resolve, SLOW_FRAME_DELAY_MS));
1241
+ intervals[index].frameMs = Math.max(SLOW_FRAME_DELAY_MS, performance.now() - startedAt);
1242
+ intervals[index].timestampMs = intervals[index - 1].timestampMs + intervals[index - 1].frameMs;
1243
+ }
1244
+ return intervals;
1245
+ }
1246
+
1247
+ async function collectFixtureStartup(control) {
1248
+ const delayMs = control === 'slow-startup' ? SLOW_STARTUP_DELAY_MS : 120;
1249
+ const marker = 'TN_PROD_FIRST_NONBLANK_FRAME';
1250
+ const startedAt = performance.now();
1251
+ let firstFrameAt;
1252
+ let output = '';
1253
+ const child = spawn(process.execPath, ['-e', `setTimeout(() => process.stdout.write(${JSON.stringify(`${marker}\n`)}), ${delayMs})`], {
1254
+ stdio: ['ignore', 'pipe', 'ignore'],
1255
+ });
1256
+ child.stdout?.on('data', (chunk) => {
1257
+ output += chunk.toString();
1258
+ if (firstFrameAt === undefined && output.includes(marker)) firstFrameAt = performance.now();
1259
+ });
1260
+ const status = await new Promise((resolve) => {
1261
+ const timer = setTimeout(() => {
1262
+ child.kill('SIGKILL');
1263
+ resolve(2);
1264
+ }, delayMs + 2_000);
1265
+ child.once('error', () => {
1266
+ clearTimeout(timer);
1267
+ resolve(2);
1268
+ });
1269
+ child.once('exit', (code) => {
1270
+ clearTimeout(timer);
1271
+ resolve(code ?? 2);
1272
+ });
1273
+ });
1274
+ const firstFrameMs = firstFrameAt === undefined ? undefined : firstFrameAt - startedAt;
1275
+ const report = status === 0 && output.includes(marker) ? { pass: true } : undefined;
1276
+ return {
1277
+ firstFrameMs,
1278
+ report,
1279
+ screenshot: report === undefined ? undefined : fixtureFrame(),
1280
+ status,
1281
+ };
1282
+ }
1283
+
1284
+ function fixtureFrame() {
1285
+ const png = new PNG({ height: 2, width: 2 });
1286
+ for (let index = 0; index < png.data.length; index += 4) {
1287
+ png.data[index] = index === 0 ? 255 : 32;
1288
+ png.data[index + 1] = index === 0 ? 255 : 64;
1289
+ png.data[index + 2] = index === 0 ? 255 : 96;
1290
+ png.data[index + 3] = 255;
1291
+ }
1292
+ return PNG.sync.write(png);
1293
+ }
1294
+
1295
+ function applyNegativeControl(input, control) {
1296
+ if (control === undefined) return input;
1297
+ const evidence = {
1298
+ ...input,
1299
+ codes: [...(input.codes ?? [])],
1300
+ evidenceClasses: [...new Set([...(input.evidenceClasses ?? []), 'negative-control'])],
1301
+ execution: { ...input.execution, control },
1302
+ control,
1303
+ };
1304
+ if (control === 'missing-marker') evidence.markers = evidence.markers.filter((marker) => marker !== 'first-workload-frame');
1305
+ if (control === 'early-exit') evidence.markers = evidence.markers.filter((marker) => marker !== 'clean-end');
1306
+ if (control === 'stale-source-sha') evidence.source = { ...evidence.source, sha: 'e38439c' };
1307
+ if (control === 'dirty-checkout') {
1308
+ evidence.source = { ...evidence.source, dirty: true };
1309
+ delete evidence.source.diffSha;
1310
+ }
1311
+ if (control === 'memory-growth') {
1312
+ evidence.metrics = {
1313
+ ...evidence.metrics,
1314
+ memory: { first15MedianBytes: 100, last15MedianBytes: 200, growthBytes: 128, slopeBytesPerMinute: 512 * 1024 },
1315
+ };
1316
+ }
1317
+ if (control === 'substitute-emulator-provenance') {
1318
+ evidence.physical = { ...(evidence.physical ?? {}), provenance: 'android-emulator' };
1319
+ }
1320
+ if (control === 'claimed-audio-missing-evidence') {
1321
+ evidence.audioClaim = 'claimed';
1322
+ delete evidence.audioEvidenceSha256;
1323
+ }
1324
+ if (control === 'disallowed-identifiers') evidence.identity = { ...evidence.identity, serial: 'negative-control' };
1325
+ return evidence;
1326
+ }
1327
+
1328
+ async function currentSourceState() {
1329
+ try {
1330
+ const [{ stdout: sha }, { stdout: status }, { stdout: diff }] = await Promise.all([
1331
+ execFileAsync('git', ['rev-parse', 'HEAD'], { cwd: commandRoot }),
1332
+ execFileAsync('git', ['status', '--porcelain'], { cwd: commandRoot }),
1333
+ execFileAsync('git', ['diff', 'HEAD'], { cwd: commandRoot }),
1334
+ ]);
1335
+ const dirty = status.trim().length > 0;
1336
+ return { dirty, ...(dirty ? { diffSha: sha256(Buffer.from(diff)) } : {}), sha: sha.trim() };
1337
+ } catch {
1338
+ return { dirty: true, diffSha: sha256(Buffer.from('source-state-unavailable')), sha: '0000000' };
1339
+ }
1340
+ }
1341
+
1342
+ async function readPhysicalEvidence(path) {
1343
+ if (path === undefined) return {};
1344
+ try {
1345
+ const content = await readFile(path);
1346
+ const text = content.toString('utf8').toLowerCase();
1347
+ return {
1348
+ physicalEvidenceClass: /emulator|simulator/u.test(text) ? 'android-emulator' : 'physical-hardware',
1349
+ physicalEvidenceHash: sha256(content),
1350
+ };
1351
+ } catch {
1352
+ return { physicalEvidenceClass: 'missing', physicalEvidenceHash: undefined };
1353
+ }
1354
+ }
1355
+
1356
+ async function readOptionalArtifact(path) {
1357
+ if (path === undefined) return {};
1358
+ try {
1359
+ return { audioEvidenceHash: sha256(await readFile(path)) };
1360
+ } catch {
1361
+ return {};
1362
+ }
1363
+ }
1364
+
1365
+ async function nativeArtifactPath(project, target) {
1366
+ const directory = join(project, 'dist-native');
1367
+ const entries = await readdir(directory);
1368
+ const candidate = entries.find((entry) => target === 'ios' ? entry.endsWith('.app') : target === 'android' ? entry.endsWith('.apk') : true);
1369
+ if (candidate === undefined) throw new ProductionEvidenceError('TN_PROD_NATIVE_ARTIFACT_MISSING', `The scaffolded ${target} build produced no native artifact.`);
1370
+ return join(directory, candidate);
1371
+ }
1372
+
1373
+ async function playtestRunnerPath(project, tools) {
1374
+ const candidates = [
1375
+ tools.playtestRunner,
1376
+ join(project, 'node_modules/@threenative/playtest/dist/runner/index.js'),
1377
+ ].filter(Boolean);
1378
+ for (const candidate of candidates) if (await fileExists(candidate)) return candidate;
1379
+ return undefined;
1380
+ }
1381
+
1382
+ async function installAndroidArtifact(apk, device) {
1383
+ const args = [...(device === undefined ? [] : ['-s', device]), 'install', '-r', apk];
1384
+ const result = await runCommand('adb', args, commandRoot);
1385
+ if (result.status !== 0) throw new ProductionEvidenceError('TN_PROD_ANDROID_INSTALL_FAILED', 'Installing the scaffolded Android platformer failed.');
1386
+ }
1387
+
1388
+ async function hashPath(path) {
1389
+ const details = await stat(path).catch(() => undefined);
1390
+ if (details === undefined) throw new ProductionEvidenceError('TN_PROD_ARTIFACT_MISSING', `Production artifact '${basename(path)}' is missing.`);
1391
+ if (details.isFile()) return sha256(await readFile(path));
1392
+ const files = await listFiles(path);
1393
+ const hashInput = [];
1394
+ for (const file of files) hashInput.push(`${relative(path, file)}\0${sha256(await readFile(file))}`);
1395
+ return sha256(Buffer.from(hashInput.join('\n')));
1396
+ }
1397
+
1398
+ async function listFiles(directory) {
1399
+ const entries = await readdir(directory, { withFileTypes: true });
1400
+ const files = [];
1401
+ for (const entry of entries) {
1402
+ const path = join(directory, entry.name);
1403
+ if (entry.isDirectory()) files.push(...await listFiles(path));
1404
+ else if (entry.isFile()) files.push(path);
1405
+ }
1406
+ return files.sort();
1407
+ }
1408
+
1409
+ async function nonBlankPng(path) {
1410
+ try {
1411
+ return isNonBlankFrame(await readFile(path));
1412
+ } catch {
1413
+ return false;
1414
+ }
1415
+ }
1416
+
1417
+ function isNonBlankFrame(value) {
1418
+ if (!Buffer.isBuffer(value)) return false;
1419
+ try {
1420
+ const png = PNG.sync.read(value);
1421
+ const colors = new Set();
1422
+ let opaque = 0;
1423
+ for (let index = 0; index < png.data.length; index += 4) {
1424
+ if (png.data[index + 3] !== 0) opaque += 1;
1425
+ colors.add(`${png.data[index]},${png.data[index + 1]},${png.data[index + 2]},${png.data[index + 3]}`);
1426
+ }
1427
+ return opaque > 0 && colors.size > 1;
1428
+ } catch {
1429
+ return false;
1430
+ }
1431
+ }
1432
+
1433
+ async function browserCommand(args) {
1434
+ if (process.platform !== 'linux' || process.env.DISPLAY !== undefined) return { args, command: process.execPath };
1435
+ const result = await runCommand('which', ['xvfb-run'], commandRoot);
1436
+ if (result.status !== 0) return { args, command: process.execPath };
1437
+ return { args: ['-a', '-s', '-screen 0 1600x900x24', process.execPath, ...args], command: 'xvfb-run' };
1438
+ }
1439
+
1440
+ async function availablePort() {
1441
+ const server = createServer();
1442
+ await new Promise((resolve, reject) => {
1443
+ server.once('error', reject);
1444
+ server.listen(0, '127.0.0.1', resolve);
1445
+ });
1446
+ const address = server.address();
1447
+ await new Promise((resolve) => server.close(resolve));
1448
+ if (address === null || typeof address === 'string') throw new ProductionEvidenceError('TN_PROD_PORT_UNAVAILABLE', 'Could not allocate a local playtest port.');
1449
+ return address.port;
1450
+ }
1451
+
1452
+ async function runCommand(command, args, cwd, env = undefined, timeout = 120_000) {
1453
+ const started = performance.now();
1454
+ try {
1455
+ const result = await execFileAsync(command, args, {
1456
+ cwd,
1457
+ encoding: 'utf8',
1458
+ env: env ?? process.env,
1459
+ maxBuffer: 32 * 1024 * 1024,
1460
+ timeout,
1461
+ });
1462
+ return { durationMs: performance.now() - started, status: 0, stderr: result.stderr, stdout: result.stdout };
1463
+ } catch (error) {
1464
+ return {
1465
+ durationMs: performance.now() - started,
1466
+ status: typeof error?.code === 'number' ? error.code : 2,
1467
+ stderr: error?.stderr ?? '',
1468
+ stdout: error?.stdout ?? '',
1469
+ };
1470
+ }
1471
+ }
1472
+
1473
+ async function removeMailbox(root) {
1474
+ await Promise.all([
1475
+ rm(join(root, 'tn-playtest-request.json'), { force: true }),
1476
+ rm(join(root, 'tn-playtest-response.json'), { force: true }),
1477
+ rm(join(root, 'tn-production-screenshot-request.json'), { force: true }),
1478
+ ]);
1479
+ }
1480
+
1481
+ async function fileExists(path) {
1482
+ return await stat(path).then(() => true).catch(() => false);
1483
+ }
1484
+
1485
+ function parseRenderSize(value) {
1486
+ const match = /^(\d+)x(\d+)$/u.exec(value);
1487
+ if (match === null) throw new ProductionEvidenceError('TN_PROD_RENDER_SIZE_INVALID', `--render-size must use WIDTHxHEIGHT, received '${value}'.`);
1488
+ const width = Number(match[1]);
1489
+ const height = Number(match[2]);
1490
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0) {
1491
+ throw new ProductionEvidenceError('TN_PROD_RENDER_SIZE_INVALID', `--render-size must contain positive dimensions, received '${value}'.`);
1492
+ }
1493
+ return { height, width };
1494
+ }
1495
+
1496
+ function nextValue(argv, index, flag) {
1497
+ const value = argv[index];
1498
+ if (value === undefined || value.startsWith('--')) throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', `${flag} requires a value.`);
1499
+ return value;
1500
+ }
1501
+
1502
+ function positiveNumber(value, flag) {
1503
+ const parsed = Number(value);
1504
+ if (!Number.isFinite(parsed) || parsed <= 0) throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', `${flag} requires a positive number.`);
1505
+ return parsed;
1506
+ }
1507
+
1508
+ function positiveInteger(value, flag) {
1509
+ const parsed = Number(value);
1510
+ if (!Number.isInteger(parsed) || parsed <= 0) throw new ProductionEvidenceError('TN_PROD_CLI_USAGE', `${flag} requires a positive integer.`);
1511
+ return parsed;
1512
+ }
1513
+
1514
+ if (process.argv[1] && new URL(`file://${process.argv[1]}`).pathname === new URL(import.meta.url).pathname) {
1515
+ try {
1516
+ const result = await runProductionProfile(parseProductionArgs());
1517
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1518
+ process.exitCode = result.exitCode ?? 0;
1519
+ } catch (error) {
1520
+ const code = error instanceof ProductionEvidenceError ? error.code : 'TN_PROD_EVIDENCE_INVALID';
1521
+ const message = error instanceof Error ? error.message : String(error);
1522
+ process.stderr.write(`${JSON.stringify({ codes: [code], message, status: 'BLOCKED', exitCode: 2 }, null, 2)}\n`);
1523
+ process.exitCode = 2;
1524
+ }
1525
+ }