@threenative/runtime-native 0.3.1 → 0.3.3

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,732 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
6
+ import { release as osRelease } from 'node:os';
7
+ import { basename, join, resolve } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ export const CONSUMER_GAMEPLAY_SCENARIO = 'playtests/production-readiness.playtest.json';
11
+ export const CONSUMER_REQUIRED_TARGETS = ['desktop', 'android'];
12
+ const CONSUMER_ARTIFACT_HASH = /^[0-9a-f]{64}$/u;
13
+
14
+ function consumerError(code, detail) {
15
+ return new Error(`TN_STARTER_CONSUMER_${code}: ${detail}`);
16
+ }
17
+
18
+ function nonEmptyString(value) {
19
+ return typeof value === 'string' && value.trim().length > 0;
20
+ }
21
+
22
+ /**
23
+ * A scenario's `assert` key -> the family token every result id for it begins with. The row used to
24
+ * store only a COUNT, so `5 === 5` qualified a run that evaluated five assertions the scenario never
25
+ * declared, and a run that silently dropped three of five declared families still qualified with
26
+ * `assertions: 3` and nothing said so. Coverage is checked per declared family, not per id, because
27
+ * one `resources` block yields one result per entry; extra families are allowed, missing ones are not.
28
+ */
29
+ const CONSUMER_ASSERTION_FAMILIES = {
30
+ diagnostics: 'diagnostics',
31
+ movement: 'movement',
32
+ resources: 'resource',
33
+ visibility: 'visibility',
34
+ };
35
+
36
+ /** The family token of a result id: everything before the first dot. */
37
+ function consumerAssertionFamily(id) {
38
+ const dot = id.indexOf('.');
39
+ return dot === -1 ? id : id.slice(0, dot);
40
+ }
41
+
42
+ /** The families a scenario's assert block declares, as family tokens. Unknown keys are ignored. */
43
+ export function declaredConsumerAssertionFamilies(scenario) {
44
+ const block = scenario?.assert;
45
+ if (typeof block !== 'object' || block === null || Array.isArray(block)) return [];
46
+ return Object.keys(block)
47
+ .map((key) => CONSUMER_ASSERTION_FAMILIES[key])
48
+ .filter((family) => family !== undefined);
49
+ }
50
+
51
+ /** The session the run executed in, named rather than assumed: a headless Linux host is not X11. */
52
+ export function describeConsumerSession(platform = process.platform, environment = process.env) {
53
+ if (platform === 'android') return 'android';
54
+ if (platform === 'win32') return 'windows-dwm';
55
+ if (platform === 'darwin') return 'quartz';
56
+ if (platform === 'linux') {
57
+ if (environment.WAYLAND_DISPLAY) return 'wayland';
58
+ if (environment.DISPLAY) return 'x11';
59
+ return 'headless';
60
+ }
61
+ return platform;
62
+ }
63
+
64
+ /** Fail closed on a row that is structurally unreadable, before any value comparison. */
65
+ export function validateConsumerTargetRow(row) {
66
+ if (typeof row !== 'object' || row === null || Array.isArray(row)) {
67
+ throw consumerError('ROW_MALFORMED', 'a target row must be an object.');
68
+ }
69
+ for (const field of [
70
+ 'target',
71
+ 'os',
72
+ 'osVersion',
73
+ 'architecture',
74
+ 'session',
75
+ 'scenario',
76
+ 'applicationId',
77
+ 'artifactHash',
78
+ ]) {
79
+ if (!nonEmptyString(row[field])) {
80
+ throw consumerError('ROW_MALFORMED', `target row field '${field}' is missing or empty.`);
81
+ }
82
+ }
83
+ if (!CONSUMER_REQUIRED_TARGETS.includes(row.target)) {
84
+ throw consumerError('TARGET_UNSUPPORTED', `unknown consumer target '${row.target}'.`);
85
+ }
86
+ if (row.scenarioHash !== undefined && !CONSUMER_ARTIFACT_HASH.test(row.scenarioHash)) {
87
+ throw consumerError('ROW_MALFORMED', 'scenarioHash is not a sha256 hex digest.');
88
+ }
89
+ if (!CONSUMER_ARTIFACT_HASH.test(row.artifactHash)) {
90
+ throw consumerError(
91
+ 'ROW_MALFORMED',
92
+ `artifactHash '${row.artifactHash}' is not a sha256 hex digest.`,
93
+ );
94
+ }
95
+ if (typeof row.pass !== 'boolean') {
96
+ throw consumerError('ROW_MALFORMED', "target row field 'pass' is not a boolean.");
97
+ }
98
+ if (!Number.isSafeInteger(row.assertions) || row.assertions < 0) {
99
+ throw consumerError(
100
+ 'ROW_MALFORMED',
101
+ "target row field 'assertions' is not a non-negative integer.",
102
+ );
103
+ }
104
+ if (!Array.isArray(row.failures) || row.failures.some((failure) => !nonEmptyString(failure))) {
105
+ throw consumerError(
106
+ 'ROW_MALFORMED',
107
+ "target row field 'failures' must contain non-empty strings.",
108
+ );
109
+ }
110
+ // A row written before assertion ids existed is not malformed input, it is superseded evidence:
111
+ // it stored only a count, which is exactly what could not be trusted. Name that so an operator
112
+ // re-runs the target instead of hunting a corrupted file.
113
+ if (row.assertionIds === undefined) {
114
+ throw consumerError(
115
+ 'ROW_OUTDATED',
116
+ `the '${row.target}' row records no assertionIds, so it was written by an older verifier that stored only a count. Delete artifacts/native/consumer-targets.json, then re-run --consumer: the row file is validated before it is rewritten, so re-running alone cannot clear it.`,
117
+ );
118
+ }
119
+ if (!Array.isArray(row.assertionIds) || row.assertionIds.some((id) => !nonEmptyString(id))) {
120
+ throw consumerError(
121
+ 'ROW_MALFORMED',
122
+ "target row field 'assertionIds' must contain non-empty strings.",
123
+ );
124
+ }
125
+ if (new Set(row.assertionIds).size !== row.assertionIds.length) {
126
+ throw consumerError('ROW_MALFORMED', "target row field 'assertionIds' repeats an id.");
127
+ }
128
+ if (row.assertionIds.length !== row.assertions) {
129
+ throw consumerError(
130
+ 'ROW_MALFORMED',
131
+ `the '${row.target}' row counts ${row.assertions} assertions but names ${row.assertionIds.length}.`,
132
+ );
133
+ }
134
+ return row;
135
+ }
136
+
137
+ function assertConsumerIdentity(row, expected) {
138
+ if (
139
+ !nonEmptyString(expected?.scenario) ||
140
+ !nonEmptyString(expected?.applicationId) ||
141
+ !CONSUMER_ARTIFACT_HASH.test(expected?.artifactHash ?? '')
142
+ ) {
143
+ throw consumerError('ROW_MALFORMED', 'the expected consumer identity is incomplete.');
144
+ }
145
+ if (row.scenario !== expected.scenario) {
146
+ throw consumerError(
147
+ 'SCENARIO_MISMATCH',
148
+ `the '${row.target}' row ran '${row.scenario}', not the built consumer's '${expected.scenario}'; a substituted native-smoke subject is not this consumer.`,
149
+ );
150
+ }
151
+ if (row.artifactHash !== expected.artifactHash) {
152
+ throw consumerError(
153
+ 'ARTIFACT_MISMATCH',
154
+ `the '${row.target}' row's artifact ${row.artifactHash.slice(0, 12)} does not match the built consumer ${expected.artifactHash.slice(0, 12)}; a stale or substituted build is not this consumer.`,
155
+ );
156
+ }
157
+ if (row.applicationId !== expected.applicationId) {
158
+ throw consumerError(
159
+ 'APPLICATION_ID_MISMATCH',
160
+ `the '${row.target}' row's applicationId '${row.applicationId}' does not match the built consumer '${expected.applicationId}'.`,
161
+ );
162
+ }
163
+ if (
164
+ expected.scenarioHash !== undefined &&
165
+ (!CONSUMER_ARTIFACT_HASH.test(expected.scenarioHash) || row.scenarioHash !== expected.scenarioHash)
166
+ ) {
167
+ throw consumerError(
168
+ 'SCENARIO_MISMATCH',
169
+ 'the scenario bytes differ from the expected consumer scenario.',
170
+ );
171
+ }
172
+ }
173
+
174
+ export function qualifyConsumerTargetRow(row, expected) {
175
+ validateConsumerTargetRow(row);
176
+ assertConsumerIdentity(row, expected);
177
+ if (row.assertions === 0) {
178
+ throw consumerError(
179
+ 'NO_ASSERTIONS',
180
+ `the '${row.target}' run evaluated zero assertions, so a pass would prove nothing.`,
181
+ );
182
+ }
183
+ if (row.pass !== true || row.failures.length > 0) {
184
+ throw consumerError(
185
+ 'ASSERTION_FAILED',
186
+ `the '${row.target}' consumer run failed: ${row.failures.join('; ') || 'assertions did not pass'}.`,
187
+ );
188
+ }
189
+ return row;
190
+ }
191
+
192
+ export function assertConsumerTargetRows(rows, options) {
193
+ const targets = options?.targets ?? CONSUMER_REQUIRED_TARGETS;
194
+ if (
195
+ !Array.isArray(rows) ||
196
+ !Array.isArray(targets) ||
197
+ targets.length === 0 ||
198
+ targets.some((target) => !CONSUMER_REQUIRED_TARGETS.includes(target)) ||
199
+ new Set(targets).size !== targets.length
200
+ ) {
201
+ throw consumerError(
202
+ 'ROW_MALFORMED',
203
+ 'required targets must be a non-empty, unique supported target list.',
204
+ );
205
+ }
206
+ const validated = rows.map(validateConsumerTargetRow);
207
+ const seen = new Set();
208
+ for (const row of validated) {
209
+ if (seen.has(row.target)) {
210
+ throw consumerError('ROW_DUPLICATE', `more than one consumer row claims '${row.target}'.`);
211
+ }
212
+ seen.add(row.target);
213
+ }
214
+ const qualified = targets.map((target) => {
215
+ const row = validated.find((candidate) => candidate.target === target);
216
+ if (row === undefined) {
217
+ throw consumerError(
218
+ 'ROW_MISSING',
219
+ `no consumer gameplay row was recorded for target '${target}'.`,
220
+ );
221
+ }
222
+ const expected =
223
+ options?.expectedByTarget === undefined ? options : options.expectedByTarget[target];
224
+ return qualifyConsumerTargetRow(row, expected);
225
+ });
226
+ // "One game, two targets" is only true if both targets evaluated the SAME assertions. Equal
227
+ // counts are not that: a target that dropped one family and gained an unrelated id still counts
228
+ // the same. Compare the id sets, so a degraded target cannot hide behind its sibling's evidence.
229
+ const [first, ...rest] = qualified;
230
+ for (const row of rest) {
231
+ const a = [...first.assertionIds].sort().join(',');
232
+ const b = [...row.assertionIds].sort().join(',');
233
+ if (a !== b) {
234
+ throw consumerError(
235
+ 'ASSERTION_SET_MISMATCH',
236
+ `'${row.target}' evaluated [${b}] but '${first.target}' evaluated [${a}]; the same scenario must prove the same assertions on every target.`,
237
+ );
238
+ }
239
+ }
240
+ return qualified;
241
+ }
242
+
243
+ export function parseConsumerPlaytestReport(stdout, target, declaredFamilies = []) {
244
+ let parsed;
245
+ try {
246
+ parsed = JSON.parse(stdout);
247
+ } catch (error) {
248
+ throw consumerError(
249
+ 'ROW_MALFORMED',
250
+ `the '${target}' playtest runner emitted no JSON report: ${error instanceof Error ? error.message : String(error)}.`,
251
+ );
252
+ }
253
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
254
+ throw consumerError('ROW_MALFORMED', `the '${target}' playtest report is not an object.`);
255
+ }
256
+ const rawDiagnostics = parsed.diagnostics === undefined ? [] : parsed.diagnostics;
257
+ if (!Array.isArray(rawDiagnostics) || rawDiagnostics.some((item) => !nonEmptyString(item?.code))) {
258
+ throw consumerError('ROW_MALFORMED', 'the playtest diagnostics are malformed.');
259
+ }
260
+ const diagnostics = rawDiagnostics.map((item) => item.code);
261
+ if (diagnostics.some((code) => code.endsWith('UNSUPPORTED_ON_TARGET'))) {
262
+ throw consumerError(
263
+ 'SCENARIO_NOT_CROSS_TARGET',
264
+ `the '${target}' runner cannot evaluate this scenario; use the harness's target-aware diagnostics policy.`,
265
+ );
266
+ }
267
+ if (parsed.target !== target) {
268
+ throw consumerError('TARGET_MISMATCH', `the report names '${String(parsed.target)}', not '${target}'.`);
269
+ }
270
+ if (typeof parsed.pass !== 'boolean') {
271
+ throw consumerError('ROW_MALFORMED', 'the playtest verdict must be a boolean.');
272
+ }
273
+ if (!Array.isArray(parsed.assertionResults) || parsed.assertionResults.length === 0) {
274
+ throw consumerError('NO_ASSERTIONS', `the '${target}' run evaluated zero assertions.`);
275
+ }
276
+ const failures = [];
277
+ for (const result of parsed.assertionResults) {
278
+ if (
279
+ typeof result !== 'object' ||
280
+ result === null ||
281
+ Array.isArray(result) ||
282
+ !nonEmptyString(result.id) ||
283
+ typeof result.pass !== 'boolean'
284
+ ) {
285
+ throw consumerError(
286
+ 'ROW_MALFORMED',
287
+ 'every assertion must name its id and boolean result.',
288
+ );
289
+ }
290
+ if (result.details?.reason === 'not-evaluated') {
291
+ throw consumerError('NO_ASSERTIONS', `assertion '${result.id}' was not evaluated.`);
292
+ }
293
+ if (!result.pass) failures.push(result.id);
294
+ }
295
+ if (parsed.assertionResults.every((result) => result.id === 'diagnostics')) {
296
+ throw consumerError('NO_ASSERTIONS', 'diagnostics alone do not prove consumer gameplay.');
297
+ }
298
+ const assertionIds = [...new Set(parsed.assertionResults.map((result) => result.id))].sort();
299
+ const evaluated = new Set(assertionIds.map(consumerAssertionFamily));
300
+ for (const family of declaredFamilies) {
301
+ if (!evaluated.has(family)) {
302
+ throw consumerError(
303
+ 'ASSERTION_FAMILY_MISSING',
304
+ `the '${target}' run evaluated [${assertionIds.join(', ')}] but the scenario declares '${family}'; a run cannot qualify on assertions the scenario never declared.`,
305
+ );
306
+ }
307
+ }
308
+ for (const diagnostic of rawDiagnostics) {
309
+ if (!['error', 'warning', 'info'].includes(diagnostic.severity)) {
310
+ throw consumerError(
311
+ 'ROW_MALFORMED',
312
+ `diagnostic '${diagnostic.code}' has no valid severity.`,
313
+ );
314
+ }
315
+ if (diagnostic.severity === 'error') failures.push(diagnostic.code);
316
+ }
317
+ return {
318
+ assertionIds,
319
+ assertions: assertionIds.length,
320
+ diagnostics,
321
+ failures,
322
+ pass: parsed.pass && failures.length === 0,
323
+ };
324
+ }
325
+
326
+ function readConsumerApplicationId(projectRoot) {
327
+ const config = join(projectRoot, 'threenative.config.ts');
328
+ if (!existsSync(config)) {
329
+ throw consumerError(
330
+ 'APPLICATION_ID_MISSING',
331
+ `${config} is absent, so the built consumer's application id cannot be read.`,
332
+ );
333
+ }
334
+ const match = /id\s*:\s*["'`]([^"'`]+)["'`]/u.exec(readFileSync(config, 'utf8'));
335
+ if (match === null || match[1].includes('__')) {
336
+ throw consumerError('APPLICATION_ID_MISSING', `no concrete app.id was found in ${config}.`);
337
+ }
338
+ return match[1];
339
+ }
340
+
341
+ function consumerArtifactFiles(root, predicate) {
342
+ const files = [];
343
+ const stack = [root];
344
+ while (stack.length > 0) {
345
+ const directory = stack.pop();
346
+ let entries;
347
+ try {
348
+ entries = readdirSync(directory, { withFileTypes: true });
349
+ } catch (error) {
350
+ if (error?.code === 'ENOENT') continue;
351
+ throw consumerError('ARTIFACT_UNREADABLE', `${directory}: ${error.message}`);
352
+ }
353
+ for (const entry of entries) {
354
+ const file = join(directory, entry.name);
355
+ if (entry.isDirectory()) {
356
+ if (entry.name === 'node_modules') continue;
357
+ stack.push(file);
358
+ } else if (entry.isFile() && predicate(file)) {
359
+ files.push(file);
360
+ }
361
+ }
362
+ }
363
+ return files.sort();
364
+ }
365
+
366
+ function discoverConsumerArtifact(projectRoot, target) {
367
+ if (target === 'desktop') {
368
+ const manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
369
+ const name = basename(String(manifest.name ?? 'starter').replace(/^@[^/]+\//u, ''));
370
+ return join(
371
+ projectRoot,
372
+ 'dist-native',
373
+ `${name}${process.platform === 'win32' ? '.exe' : ''}`,
374
+ );
375
+ }
376
+ const apks = consumerArtifactFiles(join(projectRoot, 'dist-native'), (file) => file.endsWith('.apk'));
377
+ if (apks.length === 0) {
378
+ throw consumerError(
379
+ 'ARTIFACT_MISSING',
380
+ `no .apk was found under ${join(projectRoot, 'dist-native')}; build the Android consumer first.`,
381
+ );
382
+ }
383
+ if (apks.length !== 1) {
384
+ throw consumerError(
385
+ 'ARTIFACT_AMBIGUOUS',
386
+ 'multiple APKs exist; select the built consumer with --artifact.',
387
+ );
388
+ }
389
+ return apks[0];
390
+ }
391
+
392
+ function adbDeviceIdentity(run) {
393
+ const probe = (property) => {
394
+ const value = run(['shell', 'getprop', property]).trim();
395
+ if (!value) {
396
+ throw consumerError('DEVICE_IDENTITY_UNREADABLE', `adb returned no ${property}.`);
397
+ }
398
+ return value;
399
+ };
400
+ return {
401
+ architecture: probe('ro.product.cpu.abi'),
402
+ osVersion: `${probe('ro.build.version.release')} (API ${probe('ro.build.version.sdk')})`,
403
+ };
404
+ }
405
+
406
+ function assertInstalledConsumerArtifact(run, applicationId, artifactHash) {
407
+ if (!/^[A-Za-z0-9_.-]+$/u.test(applicationId)) {
408
+ throw consumerError(
409
+ 'APPLICATION_ID_MISMATCH',
410
+ 'the Android application id is not a safe package name.',
411
+ );
412
+ }
413
+ const installed = run(['shell', 'pm', 'path', applicationId]).trim();
414
+ const match = /^package:(\/[A-Za-z0-9_./+=~-]+\.apk)$/u.exec(installed);
415
+ if (match === null) {
416
+ throw consumerError(
417
+ 'ARTIFACT_MISMATCH',
418
+ `cannot identify one installed APK for '${applicationId}'.`,
419
+ );
420
+ }
421
+ const actual = run(['shell', 'sha256sum', match[1]]).trim().split(/\s+/u)[0];
422
+ if (actual !== artifactHash) {
423
+ throw consumerError(
424
+ 'ARTIFACT_MISMATCH',
425
+ `installed '${applicationId}' does not match the supplied APK.`,
426
+ );
427
+ }
428
+ }
429
+
430
+ function recordConsumerTargetRow(projectRoot, row, target = row?.target) {
431
+ const directory = join(projectRoot, 'artifacts', 'native');
432
+ mkdirSync(directory, { recursive: true });
433
+ const file = join(directory, 'consumer-targets.json');
434
+ let rows = [];
435
+ if (existsSync(file)) {
436
+ let parsed;
437
+ try {
438
+ parsed = JSON.parse(readFileSync(file, 'utf8'));
439
+ } catch (error) {
440
+ throw consumerError(
441
+ 'ROW_MALFORMED',
442
+ `${file} is not readable JSON: ${error instanceof Error ? error.message : String(error)}`,
443
+ );
444
+ }
445
+ if (!Array.isArray(parsed)) {
446
+ throw consumerError('ROW_MALFORMED', `${file} is not a row array; refusing to overwrite it.`);
447
+ }
448
+ rows = parsed.map(validateConsumerTargetRow);
449
+ if (new Set(rows.map((candidate) => candidate.target)).size !== rows.length) {
450
+ throw consumerError('ROW_DUPLICATE', `${file} contains duplicate target rows.`);
451
+ }
452
+ }
453
+ rows = rows.filter((candidate) => candidate.target !== target);
454
+ if (row !== undefined) rows.push(validateConsumerTargetRow(row));
455
+ writeFileSync(file, `${JSON.stringify(rows, null, 2)}\n`);
456
+ return file;
457
+ }
458
+
459
+ function defaultConsumerRunner(
460
+ command,
461
+ args,
462
+ cwd,
463
+ timeoutMs = Number(process.env.TN_STARTER_CONSUMER_TIMEOUT_MS ?? 900_000),
464
+ ) {
465
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
466
+ throw consumerError('RUNNER_FAILED', 'the consumer timeout must be a positive integer.');
467
+ }
468
+ const result = spawnSync(command, args, {
469
+ cwd,
470
+ encoding: 'utf8',
471
+ maxBuffer: 64 * 1024 * 1024,
472
+ timeout: timeoutMs,
473
+ });
474
+ return { ...result, stderr: result.stderr ?? '', stdout: result.stdout ?? '' };
475
+ }
476
+
477
+ export function verifyStarterConsumerGameplay(options = {}) {
478
+ const target = options.target;
479
+ if (!CONSUMER_REQUIRED_TARGETS.includes(target)) {
480
+ throw consumerError(
481
+ 'TARGET_UNSUPPORTED',
482
+ `unsupported distributed target '${String(target)}'.`,
483
+ );
484
+ }
485
+ const projectRoot = resolve(options.project ?? process.cwd());
486
+ recordConsumerTargetRow(projectRoot, undefined, target);
487
+ const scenario = options.scenario ?? CONSUMER_GAMEPLAY_SCENARIO;
488
+ if (scenario !== CONSUMER_GAMEPLAY_SCENARIO) {
489
+ throw consumerError('SCENARIO_MISMATCH', `this gate requires '${CONSUMER_GAMEPLAY_SCENARIO}'.`);
490
+ }
491
+ const scenarioPath = join(projectRoot, scenario);
492
+ if (!existsSync(scenarioPath)) {
493
+ throw consumerError('SCENARIO_MISSING', `the required consumer scenario is absent: ${scenarioPath}`);
494
+ }
495
+ const applicationId = options.applicationId ?? readConsumerApplicationId(projectRoot);
496
+ const artifact = resolve(
497
+ projectRoot,
498
+ options.artifact ?? discoverConsumerArtifact(projectRoot, target),
499
+ );
500
+ if (!existsSync(artifact)) {
501
+ throw consumerError('ARTIFACT_MISSING', `${artifact} does not exist; build the consumer first.`);
502
+ }
503
+ const hashFile = (file) => createHash('sha256').update(readFileSync(file)).digest('hex');
504
+ const artifactHash = hashFile(artifact);
505
+ const scenarioHash = hashFile(scenarioPath);
506
+ let declaredFamilies = [];
507
+ try {
508
+ declaredFamilies = declaredConsumerAssertionFamilies(JSON.parse(readFileSync(scenarioPath, 'utf8')));
509
+ } catch (error) {
510
+ throw consumerError(
511
+ 'SCENARIO_MALFORMED',
512
+ `the consumer scenario ${scenarioPath} is not readable JSON: ${error instanceof Error ? error.message : String(error)}.`,
513
+ );
514
+ }
515
+ if (declaredFamilies.length === 0) {
516
+ throw consumerError(
517
+ 'NO_ASSERTIONS',
518
+ `the consumer scenario ${scenarioPath} declares no recognised assertion family, so no run against it can prove gameplay.`,
519
+ );
520
+ }
521
+ const cli = join(
522
+ projectRoot,
523
+ 'node_modules',
524
+ '@threenative',
525
+ 'playtest',
526
+ 'dist',
527
+ 'runner',
528
+ 'cli.js',
529
+ );
530
+ if (!existsSync(cli)) {
531
+ throw consumerError('RUNNER_MISSING', `the installed consumer runner is absent: ${cli}`);
532
+ }
533
+ const expected = options.expected ?? { applicationId, artifactHash, scenario, scenarioHash };
534
+ assertConsumerIdentity({ applicationId, artifactHash, scenario, scenarioHash }, expected);
535
+ const android = target === 'android';
536
+ const device = options.device ?? process.env.TN_ANDROID_SERIAL ?? 'emulator-5554';
537
+ const adb = options.adb ?? process.env.ADB ?? 'adb';
538
+ const deviceRunner =
539
+ options.deviceRunner ??
540
+ ((command, args, cwd) => defaultConsumerRunner(command, args, cwd, 120_000));
541
+ const runAdb = (args, code = 'DEVICE_IDENTITY_UNREADABLE') => {
542
+ const result = deviceRunner(adb, ['-s', device, ...args], projectRoot);
543
+ if (result.error || result.signal || result.status !== 0) {
544
+ throw consumerError(
545
+ code,
546
+ `${args.join(' ')}: ${result.error?.message ?? result.stderr ?? 'adb failed'}`,
547
+ );
548
+ }
549
+ return result.stdout ?? '';
550
+ };
551
+ const deviceIdentity =
552
+ android && (options.osVersion === undefined || options.architecture === undefined)
553
+ ? adbDeviceIdentity(runAdb)
554
+ : undefined;
555
+ const row = {
556
+ applicationId,
557
+ architecture: options.architecture ?? deviceIdentity?.architecture ?? process.arch,
558
+ artifactHash,
559
+ assertionIds: [],
560
+ assertions: 0,
561
+ failures: ['consumer run has not completed'],
562
+ os: options.os ?? (android ? 'android' : process.platform),
563
+ osVersion: options.osVersion ?? deviceIdentity?.osVersion ?? osRelease(),
564
+ pass: false,
565
+ scenario,
566
+ scenarioHash,
567
+ session:
568
+ options.session ??
569
+ (android
570
+ ? String(device).startsWith('emulator-')
571
+ ? 'android-emulator'
572
+ : 'android-device'
573
+ : describeConsumerSession(process.platform)),
574
+ target,
575
+ };
576
+ recordConsumerTargetRow(projectRoot, row);
577
+ const args = [
578
+ cli,
579
+ scenario,
580
+ '--target',
581
+ target,
582
+ '--project',
583
+ projectRoot,
584
+ '--artifacts',
585
+ join(projectRoot, 'artifacts', 'native', `consumer-${target}`),
586
+ ];
587
+ if (android) {
588
+ args.push(
589
+ '--device',
590
+ device,
591
+ '--adb',
592
+ adb,
593
+ '--package',
594
+ applicationId,
595
+ '--activity',
596
+ options.activity ?? 'com.threenative.runtime.MystralActivity',
597
+ );
598
+ } else {
599
+ args.push('--executable', artifact, '--host-arg', '--windowed');
600
+ }
601
+ try {
602
+ if (android) {
603
+ runAdb(['install', '-r', '--no-streaming', artifact], 'INSTALL_FAILED');
604
+ assertInstalledConsumerArtifact(runAdb, applicationId, artifactHash);
605
+ }
606
+ const result = (options.runner ?? defaultConsumerRunner)(process.execPath, args, projectRoot);
607
+ const log = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
608
+ writeFileSync(join(projectRoot, 'artifacts', 'native', `consumer-${target}.log`), log);
609
+ writeFileSync(
610
+ join(projectRoot, 'artifacts', 'native', `consumer-${target}.stdout.json`),
611
+ result.stdout ?? '',
612
+ );
613
+ if (result.error || result.signal || !Number.isInteger(result.status)) {
614
+ throw consumerError(
615
+ 'RUNNER_FAILED',
616
+ `the '${target}' process did not complete: ${result.error?.message ?? result.signal ?? result.status}.`,
617
+ );
618
+ }
619
+ const report = parseConsumerPlaytestReport(result.stdout ?? '', target, declaredFamilies);
620
+ Object.assign(row, {
621
+ assertionIds: report.assertionIds,
622
+ assertions: report.assertions,
623
+ failures: report.failures,
624
+ pass: report.pass,
625
+ log: log.slice(-4000),
626
+ });
627
+ if (result.status !== 0 && report.pass) {
628
+ throw consumerError(
629
+ 'RUNNER_FAILED',
630
+ `the '${target}' runner reported pass but exited ${result.status}.`,
631
+ );
632
+ }
633
+ if (hashFile(artifact) !== artifactHash) {
634
+ throw consumerError('ARTIFACT_MISMATCH', 'the consumer artifact changed during the run.');
635
+ }
636
+ if (hashFile(scenarioPath) !== scenarioHash) {
637
+ throw consumerError('SCENARIO_MISMATCH', 'the consumer scenario changed during the run.');
638
+ }
639
+ if (android) assertInstalledConsumerArtifact(runAdb, applicationId, artifactHash);
640
+ qualifyConsumerTargetRow(row, expected);
641
+ recordConsumerTargetRow(projectRoot, row);
642
+ return { expected, row };
643
+ } catch (error) {
644
+ row.pass = false;
645
+ row.failures = [error instanceof Error ? error.message : String(error)];
646
+ recordConsumerTargetRow(projectRoot, row);
647
+ throw error;
648
+ }
649
+ }
650
+
651
+ function optionValue(name, fallback) {
652
+ const index = process.argv.indexOf(name);
653
+ return index === -1 ? fallback : process.argv[index + 1];
654
+ }
655
+
656
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
657
+ try {
658
+ if (process.argv.includes('--qualify-existing')) {
659
+ // `--target desktop,android` qualifies both in ONE call, which is the only way the
660
+ // cross-target assertion-set check can fire. With a single target it never runs, and
661
+ // "one game, one scenario, the same assertions everywhere" would rest on a human
662
+ // comparing two rows by eye.
663
+ const targets = optionValue('--target', 'desktop')
664
+ .split(',')
665
+ .map((value) => value.trim())
666
+ .filter((value) => value.length > 0);
667
+ for (const target of targets) {
668
+ if (!CONSUMER_REQUIRED_TARGETS.includes(target)) {
669
+ throw consumerError('TARGET_UNSUPPORTED', `unsupported distributed target '${target}'.`);
670
+ }
671
+ }
672
+ if (new Set(targets).size !== targets.length) {
673
+ throw consumerError('ROW_DUPLICATE', `--target names the same target twice: ${targets.join(',')}.`);
674
+ }
675
+ const artifactOverride = optionValue('--artifact', undefined);
676
+ if (artifactOverride !== undefined && targets.length > 1) {
677
+ throw consumerError(
678
+ 'TARGET_UNSUPPORTED',
679
+ '--artifact names one file, so it cannot be used with more than one --target.',
680
+ );
681
+ }
682
+ const project = resolve(optionValue('--project', process.cwd()));
683
+ const applicationId = optionValue('--application-id', undefined) ?? readConsumerApplicationId(project);
684
+ const scenarioHash = createHash('sha256')
685
+ .update(readFileSync(join(project, CONSUMER_GAMEPLAY_SCENARIO)))
686
+ .digest('hex');
687
+ const expectedByTarget = {};
688
+ const described = [];
689
+ for (const target of targets) {
690
+ const artifact = resolve(
691
+ project,
692
+ artifactOverride ?? discoverConsumerArtifact(project, target),
693
+ );
694
+ const artifactHash = createHash('sha256').update(readFileSync(artifact)).digest('hex');
695
+ expectedByTarget[target] = {
696
+ applicationId,
697
+ artifactHash,
698
+ scenario: CONSUMER_GAMEPLAY_SCENARIO,
699
+ scenarioHash,
700
+ };
701
+ described.push(`${target} ${artifactHash.slice(0, 12)}`);
702
+ }
703
+ const file = join(project, 'artifacts', 'native', 'consumer-targets.json');
704
+ if (!existsSync(file)) {
705
+ throw consumerError('ROW_MISSING', `${file} is absent; run --consumer first.`);
706
+ }
707
+ const rows = JSON.parse(readFileSync(file, 'utf8'));
708
+ assertConsumerTargetRows(rows, { expectedByTarget, targets });
709
+ console.log(
710
+ `existing consumer rows match the built consumer: ${described.join(', ')}${targets.length > 1 ? ' (identical assertion sets)' : ''}`,
711
+ );
712
+ process.exit(0);
713
+ }
714
+ const { row } = verifyStarterConsumerGameplay({
715
+ adb: optionValue('--adb', undefined),
716
+ activity: optionValue('--activity', undefined),
717
+ applicationId: optionValue('--application-id', undefined),
718
+ artifact: optionValue('--artifact', undefined),
719
+ device: optionValue('--device', undefined),
720
+ project: optionValue('--project', process.cwd()),
721
+ scenario: optionValue('--scenario', CONSUMER_GAMEPLAY_SCENARIO),
722
+ target: optionValue('--target', 'desktop'),
723
+ });
724
+ console.log(
725
+ `consumer gameplay qualified on ${row.target}: ${row.assertions} assertions, artifact ${row.artifactHash.slice(0, 12)}, app ${row.applicationId}`,
726
+ );
727
+ process.exit(0);
728
+ } catch (error) {
729
+ console.error(error instanceof Error ? error.message : String(error));
730
+ process.exit(1);
731
+ }
732
+ }