@threenative/runtime-native 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/README.md +63 -0
- package/android/README.md +2 -2
- package/android/app/build.gradle.kts +177 -30
- package/android/app/src/main/AndroidManifest.xml +8 -1
- package/android/app/src/main/java/com/mystral/engine/MystralActivity.java +190 -2
- package/android/app/src/main/java/com/mystral/engine/TnUiOverlay.java +261 -0
- package/android/app/src/main/res/values/branding.xml +12 -0
- package/android/app/src/main/res/values/themes.xml +2 -0
- package/android/gradle.properties +1 -1
- package/package.json +44 -8
- package/scripts/asset-preflight.mjs +442 -0
- package/scripts/bundle.mjs +178 -48
- package/scripts/check-source-list.mjs +90 -0
- package/scripts/device-preflight.mjs +456 -0
- package/scripts/install-prebuilt.mjs +326 -30
- package/scripts/package-android.mjs +414 -23
- package/scripts/package-desktop.mjs +132 -12
- package/scripts/package-ios.mjs +249 -25
- package/scripts/physical-device-evidence.mjs +644 -0
- package/scripts/production-evidence.mjs +101 -2
- package/scripts/profile-production.mjs +544 -115
- package/scripts/qualify-physical-mobile.mjs +1327 -0
- package/scripts/verify-starter-desktop.mjs +140 -16
- package/scripts/xvfb.sh +68 -0
|
@@ -0,0 +1,1327 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { suppressPlayProtectOnAdbInstalls } from "./device-preflight.mjs";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
REQUIRED_PREREQUISITES,
|
|
12
|
+
assertValidPhysicalDeviceEvidence,
|
|
13
|
+
hashIdentifier,
|
|
14
|
+
rollupPhysicalDeviceEvidence,
|
|
15
|
+
sha256File,
|
|
16
|
+
validatePhysicalDeviceEvidence,
|
|
17
|
+
} from "./physical-device-evidence.mjs";
|
|
18
|
+
|
|
19
|
+
const runtimeRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
20
|
+
const workspaceRoot = resolve(runtimeRoot, "..", "..");
|
|
21
|
+
const defaultScenario = joinPath(workspaceRoot, "examples/native-smoke/playtests/physical-mobile-lifecycle.playtest.json");
|
|
22
|
+
const commitPattern = /^[0-9a-f]{7,64}$/iu;
|
|
23
|
+
const sha256Pattern = /^[0-9a-f]{64}$/u;
|
|
24
|
+
const REQUIRED_PREREQUISITE_REPORT_CONTROLS = {
|
|
25
|
+
prd053: 1,
|
|
26
|
+
prd054: 1,
|
|
27
|
+
prd046: 3,
|
|
28
|
+
prd048: 1,
|
|
29
|
+
};
|
|
30
|
+
const PREREQUISITE_REPORT_KEYS = new Set([
|
|
31
|
+
"schemaVersion",
|
|
32
|
+
"reportType",
|
|
33
|
+
"status",
|
|
34
|
+
"verdict",
|
|
35
|
+
"candidateSha",
|
|
36
|
+
"sourceSha",
|
|
37
|
+
"source",
|
|
38
|
+
"target",
|
|
39
|
+
"platform",
|
|
40
|
+
"device",
|
|
41
|
+
"artifactSha256",
|
|
42
|
+
"artifact",
|
|
43
|
+
"packageVersion",
|
|
44
|
+
"negativeControls",
|
|
45
|
+
"gateEvidence",
|
|
46
|
+
"gateIds",
|
|
47
|
+
"results",
|
|
48
|
+
"observations",
|
|
49
|
+
"consumption",
|
|
50
|
+
]);
|
|
51
|
+
|
|
52
|
+
export class QualificationError extends Error {
|
|
53
|
+
constructor(message, { code = "TN_QUALIFY_BLOCKED", status = "blocked", details = [] } = {}) {
|
|
54
|
+
super(message);
|
|
55
|
+
this.name = "QualificationError";
|
|
56
|
+
this.code = code;
|
|
57
|
+
this.status = status;
|
|
58
|
+
this.details = details;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function joinPath(...parts) {
|
|
63
|
+
return parts.join("/").replaceAll("//", "/");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function usage() {
|
|
67
|
+
return `Usage: pnpm native:qualify:physical [options]
|
|
68
|
+
|
|
69
|
+
Qualifies one supplied production artifact on one named physical device.
|
|
70
|
+
The command never builds or signs an artifact. Raw output must stay under .runtime/prd056/.
|
|
71
|
+
|
|
72
|
+
Required execution options:
|
|
73
|
+
--platform android|ios physical target
|
|
74
|
+
--device ID named physical device identifier
|
|
75
|
+
--android-app PATH production-signed APK (Android)
|
|
76
|
+
--ios-app PATH signed/provisioned .app (iOS)
|
|
77
|
+
--candidate-sha SHA exact source SHA for the candidate
|
|
78
|
+
--out PATH ignored raw output directory
|
|
79
|
+
|
|
80
|
+
Prerequisite options:
|
|
81
|
+
--prerequisite NAME=PATH repeat for prd053, prd054, prd046, and prd048
|
|
82
|
+
--prd053-report PATH shorthand prerequisite report path
|
|
83
|
+
--prd054-report PATH shorthand prerequisite report path
|
|
84
|
+
--prd046-report PATH shorthand prerequisite report path
|
|
85
|
+
--prd048-report PATH shorthand prerequisite report path
|
|
86
|
+
|
|
87
|
+
Evidence and controls:
|
|
88
|
+
--validate-fixture PATH validate one physicalDeviceEvidenceV1 document
|
|
89
|
+
--rollup PATH require passing Android and iOS reports below PATH
|
|
90
|
+
--artifact-provenance PATH supplied artifact provenance sidecar
|
|
91
|
+
--ios-telemetry PATH signed iOS collector report from the app bridge (including processPid)
|
|
92
|
+
--gate-evidence PATH observed-red control evidence for this run
|
|
93
|
+
--duration-ms N declared telemetry duration (default: 30000)
|
|
94
|
+
--cadence-ms N declared telemetry cadence (default: 1000)
|
|
95
|
+
--control NAME run one declared negative control
|
|
96
|
+
--help print this help
|
|
97
|
+
|
|
98
|
+
Exit codes:
|
|
99
|
+
0 validated pass
|
|
100
|
+
1 observed schema or behavioral failure
|
|
101
|
+
2 blocked by missing/invalid external infrastructure or identity
|
|
102
|
+
`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function requireValue(argv, index, flag) {
|
|
106
|
+
const value = argv[index + 1];
|
|
107
|
+
if (value === undefined || (value.startsWith("--") && flag !== "--browser-arg")) {
|
|
108
|
+
throw new QualificationError(`${flag} requires a value.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
109
|
+
}
|
|
110
|
+
return value;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function resolvePath(value, cwd) {
|
|
114
|
+
const base = existsSync(joinPath(cwd, "pnpm-workspace.yaml")) ? cwd : workspaceRoot;
|
|
115
|
+
return resolve(base, value);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function commitSha(value, flag) {
|
|
119
|
+
if (!commitPattern.test(value)) throw new QualificationError(`${flag} must be a git SHA.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function positiveInteger(value, flag) {
|
|
124
|
+
const parsed = Number(value);
|
|
125
|
+
if (!Number.isInteger(parsed) || parsed <= 0) throw new QualificationError(`${flag} must be a positive integer.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
126
|
+
return parsed;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function prerequisiteName(value) {
|
|
130
|
+
const normalized = value.toLowerCase().replaceAll("-", "");
|
|
131
|
+
const found = REQUIRED_PREREQUISITES.find((name) => name.replace("prd", "prd") === normalized || name === normalized || `prd${name.slice(3)}` === normalized);
|
|
132
|
+
if (found === undefined) throw new QualificationError(`Unknown prerequisite '${value}'. Expected prd053, prd054, prd046, or prd048.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
133
|
+
return found;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function parseArgs(argv, cwd = process.cwd()) {
|
|
137
|
+
const options = {
|
|
138
|
+
platform: null,
|
|
139
|
+
device: null,
|
|
140
|
+
app: null,
|
|
141
|
+
candidateSha: null,
|
|
142
|
+
out: resolvePath(".runtime/prd056/run", cwd),
|
|
143
|
+
durationMs: 30_000,
|
|
144
|
+
cadenceMs: 1_000,
|
|
145
|
+
prerequisiteReports: {},
|
|
146
|
+
validateFixture: null,
|
|
147
|
+
rollup: null,
|
|
148
|
+
artifactProvenance: null,
|
|
149
|
+
iosTelemetry: null,
|
|
150
|
+
gateEvidence: null,
|
|
151
|
+
control: null,
|
|
152
|
+
help: false,
|
|
153
|
+
};
|
|
154
|
+
const platformApps = new Map([
|
|
155
|
+
["--android-app", "android"],
|
|
156
|
+
["--ios-app", "ios"],
|
|
157
|
+
]);
|
|
158
|
+
const prerequisiteFlags = new Map([
|
|
159
|
+
["--prd053-report", "prd053"],
|
|
160
|
+
["--prd054-report", "prd054"],
|
|
161
|
+
["--prd046-report", "prd046"],
|
|
162
|
+
["--prd048-report", "prd048"],
|
|
163
|
+
]);
|
|
164
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
165
|
+
const arg = argv[index];
|
|
166
|
+
if (arg === "--help" || arg === "-h") options.help = true;
|
|
167
|
+
else if (arg === "--platform") {
|
|
168
|
+
const value = requireValue(argv, index, arg);
|
|
169
|
+
if (value !== "android" && value !== "ios") throw new QualificationError(`Unknown platform '${value}'.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
170
|
+
options.platform = value;
|
|
171
|
+
index += 1;
|
|
172
|
+
} else if (arg === "--device") {
|
|
173
|
+
options.device = requireValue(argv, index, arg);
|
|
174
|
+
index += 1;
|
|
175
|
+
} else if (arg === "--app" || platformApps.has(arg)) {
|
|
176
|
+
const value = resolvePath(requireValue(argv, index, arg), cwd);
|
|
177
|
+
if (platformApps.has(arg) && options.platform !== null && options.platform !== platformApps.get(arg)) throw new QualificationError(`${arg} does not match --platform ${options.platform}.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
178
|
+
options.app = value;
|
|
179
|
+
index += 1;
|
|
180
|
+
} else if (arg === "--candidate-sha") {
|
|
181
|
+
options.candidateSha = commitSha(requireValue(argv, index, arg), arg);
|
|
182
|
+
index += 1;
|
|
183
|
+
} else if (arg === "--out") {
|
|
184
|
+
options.out = resolvePath(requireValue(argv, index, arg), cwd);
|
|
185
|
+
index += 1;
|
|
186
|
+
} else if (arg === "--duration-ms" || arg === "--duration") {
|
|
187
|
+
options.durationMs = positiveInteger(requireValue(argv, index, arg), arg);
|
|
188
|
+
index += 1;
|
|
189
|
+
} else if (arg === "--cadence-ms") {
|
|
190
|
+
options.cadenceMs = positiveInteger(requireValue(argv, index, arg), arg);
|
|
191
|
+
index += 1;
|
|
192
|
+
} else if (arg === "--prerequisite") {
|
|
193
|
+
const value = requireValue(argv, index, arg);
|
|
194
|
+
const separator = value.indexOf("=");
|
|
195
|
+
if (separator <= 0 || separator === value.length - 1) throw new QualificationError("--prerequisite requires NAME=PATH.", { code: "TN_QUALIFY_ARGUMENT" });
|
|
196
|
+
options.prerequisiteReports[prerequisiteName(value.slice(0, separator))] = resolvePath(value.slice(separator + 1), cwd);
|
|
197
|
+
index += 1;
|
|
198
|
+
} else if (prerequisiteFlags.has(arg)) {
|
|
199
|
+
options.prerequisiteReports[prerequisiteFlags.get(arg)] = resolvePath(requireValue(argv, index, arg), cwd);
|
|
200
|
+
index += 1;
|
|
201
|
+
} else if (arg === "--validate-fixture") {
|
|
202
|
+
options.validateFixture = resolvePath(requireValue(argv, index, arg), cwd);
|
|
203
|
+
index += 1;
|
|
204
|
+
} else if (arg === "--rollup") {
|
|
205
|
+
options.rollup = resolvePath(requireValue(argv, index, arg), cwd);
|
|
206
|
+
index += 1;
|
|
207
|
+
} else if (arg === "--artifact-provenance") {
|
|
208
|
+
options.artifactProvenance = resolvePath(requireValue(argv, index, arg), cwd);
|
|
209
|
+
index += 1;
|
|
210
|
+
} else if (arg === "--ios-telemetry") {
|
|
211
|
+
options.iosTelemetry = resolvePath(requireValue(argv, index, arg), cwd);
|
|
212
|
+
index += 1;
|
|
213
|
+
} else if (arg === "--gate-evidence") {
|
|
214
|
+
options.gateEvidence = resolvePath(requireValue(argv, index, arg), cwd);
|
|
215
|
+
index += 1;
|
|
216
|
+
} else if (arg === "--control") {
|
|
217
|
+
options.control = requireValue(argv, index, arg);
|
|
218
|
+
index += 1;
|
|
219
|
+
} else {
|
|
220
|
+
throw new QualificationError(`Unknown option ${arg}. Run with --help.`, { code: "TN_QUALIFY_ARGUMENT" });
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (options.validateFixture !== null && options.rollup !== null) throw new QualificationError("--validate-fixture and --rollup are mutually exclusive.", { code: "TN_QUALIFY_ARGUMENT" });
|
|
224
|
+
if (options.out.includes(".runtime/prd056/") === false && !options.out.endsWith(".runtime/prd056")) throw new QualificationError("--out must remain under ignored .runtime/prd056/.", { code: "TN_QUALIFY_ARGUMENT" });
|
|
225
|
+
if (options.platform === null && options.app !== null && basename(options.app).endsWith(".apk")) options.platform = "android";
|
|
226
|
+
if (options.platform === null && options.app !== null && basename(options.app).endsWith(".app")) options.platform = "ios";
|
|
227
|
+
return options;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function classifyPhysicalDevice(platform, device) {
|
|
231
|
+
if (device === null || device === undefined || device.length === 0) return { kind: "missing", code: "TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED" };
|
|
232
|
+
if (platform === "android" && (/^emulator-/iu.test(device) || /(?:^|[-_])(?:sim|simulator)(?:$|[-_])/iu.test(device))) return { kind: "emulator", code: "TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED" };
|
|
233
|
+
if (platform === "ios" && /^(?:booted|simulator|simctl)|simulator/iu.test(device)) return { kind: "simulator", code: "TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED" };
|
|
234
|
+
return { kind: "physical-candidate", code: null };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function command(executable, args, { cwd = workspaceRoot, env = process.env, timeout = 30_000 } = {}) {
|
|
238
|
+
const result = spawnSync(executable, args, { cwd, encoding: "utf8", env, timeout, maxBuffer: 16 * 1024 * 1024 });
|
|
239
|
+
return {
|
|
240
|
+
status: result.status === null ? 1 : result.status,
|
|
241
|
+
stdout: result.stdout ?? "",
|
|
242
|
+
stderr: result.stderr ?? "",
|
|
243
|
+
error: result.error,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The Android SDK's own layout, searched after `PATH` fails.
|
|
249
|
+
*
|
|
250
|
+
* An SDK installed by Android Studio puts nothing on `PATH`. Without this, `apksigner` reports as
|
|
251
|
+
* unavailable while sitting in `build-tools/`, and the qualification refuses with
|
|
252
|
+
* `TN_QUALIFY_SIGNING_TOOL_REQUIRED` — a missing-capability error for a tool that is installed.
|
|
253
|
+
*
|
|
254
|
+
* That distinction is the whole point of this file's exit codes: **"blocked, tool unavailable" reads
|
|
255
|
+
* identically whether the tool is absent or merely unfound, and only one of those is a blocker.**
|
|
256
|
+
* `scripts/engine-load-test/run-android.ts` already does this for `adb`, with the same reason.
|
|
257
|
+
*/
|
|
258
|
+
function androidSdkCandidates(name, env) {
|
|
259
|
+
const roots = [env.ANDROID_HOME, env.ANDROID_SDK_ROOT, joinPath(env.HOME ?? "", "Android/Sdk")]
|
|
260
|
+
.filter((root) => typeof root === "string" && root.length > 0 && existsSync(root));
|
|
261
|
+
const candidates = [];
|
|
262
|
+
for (const root of roots) {
|
|
263
|
+
candidates.push(joinPath(root, "platform-tools", name));
|
|
264
|
+
candidates.push(joinPath(root, "tools", "bin", name));
|
|
265
|
+
const buildTools = joinPath(root, "build-tools");
|
|
266
|
+
if (!existsSync(buildTools)) continue;
|
|
267
|
+
// Newest build-tools first. `localeCompare` with `numeric` orders 36.0.0 above 9.0.0, which a
|
|
268
|
+
// plain string sort does not.
|
|
269
|
+
const versions = readdirSync(buildTools).sort((left, right) =>
|
|
270
|
+
right.localeCompare(left, "en", { numeric: true }),
|
|
271
|
+
);
|
|
272
|
+
for (const version of versions) candidates.push(joinPath(buildTools, version, name));
|
|
273
|
+
}
|
|
274
|
+
return candidates;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export function findExecutable(name, env = process.env) {
|
|
278
|
+
const override = env[`THREENATIVE_${name.toUpperCase()}`];
|
|
279
|
+
if (override !== undefined && existsSync(override)) return override;
|
|
280
|
+
const pathValue = env.PATH ?? "";
|
|
281
|
+
for (const directory of pathValue.split(":")) {
|
|
282
|
+
if (directory.length === 0) continue;
|
|
283
|
+
const candidate = joinPath(directory, name);
|
|
284
|
+
if (existsSync(candidate)) return candidate;
|
|
285
|
+
}
|
|
286
|
+
for (const candidate of androidSdkCandidates(name, env))
|
|
287
|
+
if (existsSync(candidate)) return candidate;
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function sourceIdentity(cwd = workspaceRoot) {
|
|
292
|
+
const head = command("git", ["rev-parse", "--verify", "HEAD"], { cwd });
|
|
293
|
+
if (head.status !== 0) throw new QualificationError(`Cannot read candidate HEAD: ${head.stderr || head.stdout || "git failed"}.`, { code: "TN_QUALIFY_SOURCE_BLOCKED" });
|
|
294
|
+
const status = command("git", ["status", "--porcelain"], { cwd });
|
|
295
|
+
const branch = command("git", ["branch", "--show-current"], { cwd });
|
|
296
|
+
const remote = command("git", ["config", "--get", "remote.origin.url"], { cwd });
|
|
297
|
+
const headSha = head.stdout.trim();
|
|
298
|
+
let packageVersion = "unknown";
|
|
299
|
+
try {
|
|
300
|
+
packageVersion = JSON.parse(readFileSync(join(cwd, "packages/runtime-native/package.json"), "utf8")).version;
|
|
301
|
+
} catch {
|
|
302
|
+
// The source identity remains useful when package metadata is unavailable; the artifact
|
|
303
|
+
// provenance check below still has to supply a real package version for a pass report.
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
remote: remote.stdout.trim() || "unknown",
|
|
307
|
+
branch: branch.stdout.trim() || "detached",
|
|
308
|
+
headSha,
|
|
309
|
+
worktree: status.stdout.trim().length === 0 ? "clean" : "dirty",
|
|
310
|
+
packageVersion: typeof packageVersion === "string" && packageVersion.length > 0 ? packageVersion : "unknown",
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function missingPrerequisiteBlockers(options) {
|
|
315
|
+
return REQUIRED_PREREQUISITES.filter((name) => options.prerequisiteReports?.[name] === undefined).map((name) => `${name} prerequisite report is required`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function appFlag(platform) {
|
|
319
|
+
return platform === "android" ? "--android-app" : "--ios-app";
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function isRecord(value) {
|
|
323
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function prerequisiteCandidateSha(report) {
|
|
327
|
+
return report.candidateSha ?? report.sourceSha ?? report.source?.headSha;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function prerequisiteArtifactSha(report) {
|
|
331
|
+
return report.artifactSha256 ?? report.artifact?.sha256;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function normalizePrerequisiteControls(name, value, errors) {
|
|
335
|
+
const controls = value.negativeControls ?? value.gateEvidence;
|
|
336
|
+
if (!Array.isArray(controls) || controls.length === 0) {
|
|
337
|
+
errors.push(`${name}.negativeControls: required negative-control evidence is missing`);
|
|
338
|
+
return [];
|
|
339
|
+
}
|
|
340
|
+
const normalized = [];
|
|
341
|
+
controls.forEach((control, index) => {
|
|
342
|
+
const path = `${name}.negativeControls[${index}]`;
|
|
343
|
+
if (!isRecord(control)) {
|
|
344
|
+
errors.push(`${path}: must be an object`);
|
|
345
|
+
return;
|
|
346
|
+
}
|
|
347
|
+
const allowed = new Set(["id", "gateId", "status", "finalResult", "command", "negativeControlCommand", "observedRed", "redObservation", "exitCode", "reportSha256"]);
|
|
348
|
+
for (const key of Object.keys(control)) if (!allowed.has(key)) errors.push(`${path}.${key}: unknown field`);
|
|
349
|
+
const id = control.id ?? control.gateId;
|
|
350
|
+
const status = control.status ?? control.finalResult;
|
|
351
|
+
const commandText = control.command ?? control.negativeControlCommand;
|
|
352
|
+
const observedRed = control.observedRed ?? control.redObservation;
|
|
353
|
+
if (typeof id !== "string" || id.length === 0) errors.push(`${path}.id: must be a non-empty string`);
|
|
354
|
+
if (status !== "fail" && !(control.finalResult === "pass" && control.exitCode !== 0)) errors.push(`${path}.status: negative control must be observed red`);
|
|
355
|
+
if (typeof commandText !== "string" || commandText.length === 0) errors.push(`${path}.command: must be a non-empty string`);
|
|
356
|
+
if (typeof observedRed !== "string" || observedRed.length === 0) errors.push(`${path}.observedRed: observed red result is required`);
|
|
357
|
+
if (typeof observedRed === "string" && !/red|fail|reject|error/iu.test(observedRed)) errors.push(`${path}.observedRed: must describe the observed red/rejected control`);
|
|
358
|
+
if (!Number.isInteger(control.exitCode) || control.exitCode === 0) errors.push(`${path}.exitCode: negative control must have a nonzero integer exit code`);
|
|
359
|
+
if (control.reportSha256 !== undefined && (typeof control.reportSha256 !== "string" || !sha256Pattern.test(control.reportSha256))) errors.push(`${path}.reportSha256: must be a SHA-256 digest when supplied`);
|
|
360
|
+
normalized.push({
|
|
361
|
+
gateId: id,
|
|
362
|
+
finalResult: "pass",
|
|
363
|
+
negativeControlCommand: commandText,
|
|
364
|
+
redObservation: observedRed,
|
|
365
|
+
exitCode: control.exitCode,
|
|
366
|
+
reportSha256: control.reportSha256,
|
|
367
|
+
});
|
|
368
|
+
});
|
|
369
|
+
const minimum = REQUIRED_PREREQUISITE_REPORT_CONTROLS[name];
|
|
370
|
+
if (normalized.length < minimum) errors.push(`${name}.negativeControls: requires at least ${minimum} observed-red controls`);
|
|
371
|
+
return normalized;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export function validatePrerequisiteReport(name, report, {
|
|
375
|
+
candidateSha,
|
|
376
|
+
platform,
|
|
377
|
+
deviceIdentifierHash,
|
|
378
|
+
artifactSha256,
|
|
379
|
+
} = {}) {
|
|
380
|
+
const errors = [];
|
|
381
|
+
if (!REQUIRED_PREREQUISITES.includes(name)) errors.push(`${name}: unknown prerequisite`);
|
|
382
|
+
if (!isRecord(report)) return { valid: false, errors: [`${name}: report must be an object`] };
|
|
383
|
+
for (const key of Object.keys(report)) if (!PREREQUISITE_REPORT_KEYS.has(key)) errors.push(`${name}.${key}: unknown field`);
|
|
384
|
+
if (report.schemaVersion !== 1) errors.push(`${name}.schemaVersion: must equal 1`);
|
|
385
|
+
if (report.reportType !== name) errors.push(`${name}.reportType: must equal ${name}`);
|
|
386
|
+
if (report.status !== "pass") errors.push(`${name}.status: report must be pass`);
|
|
387
|
+
const candidateValues = [report.candidateSha, report.sourceSha, report.source?.headSha].filter((value) => value !== undefined);
|
|
388
|
+
const reportCandidateSha = prerequisiteCandidateSha(report);
|
|
389
|
+
if (new Set(candidateValues).size > 1) errors.push(`${name}.candidateSha: report contains inconsistent source SHA fields`);
|
|
390
|
+
if (typeof reportCandidateSha !== "string" || !commitPattern.test(reportCandidateSha)) errors.push(`${name}.candidateSha: report must contain a git SHA`);
|
|
391
|
+
else if (candidateSha !== undefined && reportCandidateSha !== candidateSha) errors.push(`${name}.candidateSha: expected ${candidateSha}, got ${reportCandidateSha}`);
|
|
392
|
+
const targetValues = [report.target, report.platform].filter((value) => value !== undefined);
|
|
393
|
+
const reportTarget = report.target ?? report.platform;
|
|
394
|
+
if (targetValues.length === 0 || new Set(targetValues).size > 1 || reportTarget !== platform) errors.push(`${name}.target: expected ${platform}, got ${reportTarget ?? "missing"}`);
|
|
395
|
+
if (!isRecord(report.device)) errors.push(`${name}.device: physical device identity is required`);
|
|
396
|
+
else {
|
|
397
|
+
const deviceKeys = new Set(["kind", "platform", "identifierHash", "idHash", "name", "manufacturer", "model", "osVersion", "osBuild", "cpuAbi", "gpu", "driver"]);
|
|
398
|
+
for (const key of Object.keys(report.device)) if (!deviceKeys.has(key)) errors.push(`${name}.device.${key}: unknown field`);
|
|
399
|
+
if (report.device.kind !== "physical") errors.push(`${name}.device.kind: must be physical`);
|
|
400
|
+
if (report.device.platform !== platform) errors.push(`${name}.device.platform: expected ${platform}`);
|
|
401
|
+
const reportIdentifierHash = report.device.identifierHash ?? report.device.idHash;
|
|
402
|
+
if (typeof reportIdentifierHash !== "string" || !sha256Pattern.test(reportIdentifierHash)) errors.push(`${name}.device.identifierHash: physical device hash is required`);
|
|
403
|
+
else if (deviceIdentifierHash !== undefined && reportIdentifierHash !== deviceIdentifierHash) errors.push(`${name}.device.identifierHash: does not match the supplied device`);
|
|
404
|
+
}
|
|
405
|
+
const artifactValues = [report.artifactSha256, report.artifact?.sha256].filter((value) => value !== undefined);
|
|
406
|
+
const reportArtifactSha = prerequisiteArtifactSha(report);
|
|
407
|
+
if (new Set(artifactValues).size > 1) errors.push(`${name}.artifactSha256: report contains inconsistent artifact SHA fields`);
|
|
408
|
+
if (typeof reportArtifactSha !== "string" || !sha256Pattern.test(reportArtifactSha)) errors.push(`${name}.artifactSha256: artifact SHA-256 is required`);
|
|
409
|
+
else if (artifactSha256 !== undefined && reportArtifactSha !== artifactSha256) errors.push(`${name}.artifactSha256: does not match the supplied artifact`);
|
|
410
|
+
const controls = normalizePrerequisiteControls(name, report, errors);
|
|
411
|
+
return {
|
|
412
|
+
valid: errors.length === 0,
|
|
413
|
+
errors,
|
|
414
|
+
candidateSha: reportCandidateSha,
|
|
415
|
+
artifactSha256: reportArtifactSha,
|
|
416
|
+
controls,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function readPrerequisiteReports(options, { candidateSha, platform, deviceIdentifierHash, artifactSha256 } = {}) {
|
|
421
|
+
const records = {};
|
|
422
|
+
const errors = [];
|
|
423
|
+
for (const name of REQUIRED_PREREQUISITES) {
|
|
424
|
+
const path = options.prerequisiteReports?.[name];
|
|
425
|
+
if (path === undefined) {
|
|
426
|
+
errors.push(`${name} prerequisite report is required`);
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
if (!existsSync(path)) {
|
|
430
|
+
errors.push(`${name} prerequisite report is missing at ${path}`);
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
let report;
|
|
434
|
+
try {
|
|
435
|
+
report = JSON.parse(readFileSync(path, "utf8"));
|
|
436
|
+
} catch (error) {
|
|
437
|
+
errors.push(`${name} prerequisite report is invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
const validation = validatePrerequisiteReport(name, report, { candidateSha, platform, deviceIdentifierHash, artifactSha256 });
|
|
441
|
+
if (!validation.valid) errors.push(...validation.errors);
|
|
442
|
+
records[name] = { path, report, validation, sha256: sha256File(path) };
|
|
443
|
+
}
|
|
444
|
+
return { valid: errors.length === 0, errors, records };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
export function preflight(options, {
|
|
448
|
+
cwd = workspaceRoot,
|
|
449
|
+
source = undefined,
|
|
450
|
+
artifactSha256 = undefined,
|
|
451
|
+
artifactSourceSha = undefined,
|
|
452
|
+
} = {}) {
|
|
453
|
+
const blockers = [];
|
|
454
|
+
const platform = options.platform;
|
|
455
|
+
const identity = classifyPhysicalDevice(platform, options.device);
|
|
456
|
+
if (platform === null) blockers.push("--platform android|ios is required");
|
|
457
|
+
if (identity.kind === "missing") blockers.push(`${platform ?? "physical"} device identifier is required`);
|
|
458
|
+
if (identity.kind === "emulator" || identity.kind === "simulator") blockers.push(`${identity.code}: ${options.device} is not a physical device`);
|
|
459
|
+
if (options.app === null) blockers.push(`${appFlag(platform ?? "android")} signed artifact path is required`);
|
|
460
|
+
if (options.candidateSha === null) blockers.push("--candidate-sha is required");
|
|
461
|
+
blockers.push(...missingPrerequisiteBlockers(options));
|
|
462
|
+
if (!options.out.includes(".runtime/prd056/") && !options.out.endsWith(".runtime/prd056")) blockers.push("raw output must be ignored under .runtime/prd056/");
|
|
463
|
+
if (identity.kind === "emulator" || identity.kind === "simulator") return { status: "blocked", code: identity.code, blockers, source: null };
|
|
464
|
+
if (blockers.length > 0 && options.candidateSha === null) return { status: "blocked", code: "TN_QUALIFY_INPUT_REQUIRED", blockers, source: null };
|
|
465
|
+
const resolvedSource = source ?? sourceIdentity(cwd);
|
|
466
|
+
if (resolvedSource.headSha !== options.candidateSha) blockers.push(`candidate SHA mismatch: requested ${options.candidateSha}, checkout HEAD ${resolvedSource.headSha}`);
|
|
467
|
+
if (resolvedSource.worktree !== "clean") blockers.push("source worktree is dirty; physical evidence requires committed HEAD");
|
|
468
|
+
if (options.app !== null && !existsSync(options.app)) blockers.push(`signed artifact is missing at ${options.app}`);
|
|
469
|
+
if (typeof artifactSha256 !== "string" || !sha256Pattern.test(artifactSha256)) blockers.push("supplied artifact SHA-256 provenance is required");
|
|
470
|
+
if (typeof artifactSourceSha !== "string" || !commitPattern.test(artifactSourceSha)) blockers.push("supplied artifact source SHA provenance is required");
|
|
471
|
+
else if (artifactSourceSha !== options.candidateSha) blockers.push(`artifact source SHA mismatch: expected ${options.candidateSha}, got ${artifactSourceSha}`);
|
|
472
|
+
const prerequisiteResult = readPrerequisiteReports(options, {
|
|
473
|
+
candidateSha: options.candidateSha,
|
|
474
|
+
platform,
|
|
475
|
+
deviceIdentifierHash: options.device === null || options.device === undefined ? undefined : hashIdentifier(options.device),
|
|
476
|
+
artifactSha256,
|
|
477
|
+
});
|
|
478
|
+
blockers.push(...prerequisiteResult.errors);
|
|
479
|
+
return {
|
|
480
|
+
status: blockers.length === 0 ? "pass" : "blocked",
|
|
481
|
+
code: blockers.length === 0 ? "TN_QUALIFY_PREFLIGHT_PASS" : "TN_QUALIFY_PREFLIGHT_BLOCKED",
|
|
482
|
+
blockers,
|
|
483
|
+
source: resolvedSource,
|
|
484
|
+
artifactSha256,
|
|
485
|
+
prerequisites: prerequisiteResult.records,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function resultFor(status, code, fields = {}) {
|
|
490
|
+
return { status, code, ...fields };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function resultFromQualificationError(error) {
|
|
494
|
+
return error instanceof QualificationError
|
|
495
|
+
? resultFor(error.status, error.code, { errors: [error.message, ...error.details] })
|
|
496
|
+
: resultFor("fail", "TN_QUALIFY_UNEXPECTED", { errors: [error instanceof Error ? error.message : String(error)] });
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function lifecycleControl(options) {
|
|
500
|
+
const validation = evaluateLifecycleObservation(options.controlObservation);
|
|
501
|
+
return validation.valid
|
|
502
|
+
? resultFor("pass", "TN_QUALIFY_CONTROL_GREEN", { observation: "lifecycle continuity guard accepted the supplied observation" })
|
|
503
|
+
: resultFor("fail", "TN_QUALIFY_LIFECYCLE_CONTINUITY", { errors: validation.errors });
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function unsignedArtifactControl(options, dependencies) {
|
|
507
|
+
try {
|
|
508
|
+
const artifact = options.platform === "android"
|
|
509
|
+
? verifyAndroidArtifact(options.app, options.candidateSha, { ...dependencies, artifactProvenance: options.artifactProvenance })
|
|
510
|
+
: verifyIosArtifact(options.app, options.candidateSha, { ...dependencies, artifactProvenance: options.artifactProvenance });
|
|
511
|
+
return resultFor("fail", "TN_QUALIFY_CONTROL_NOT_TRIGGERED", { errors: [`unsigned-artifact control accepted supplied artifact ${artifact.artifactSha256}`] });
|
|
512
|
+
} catch (error) {
|
|
513
|
+
return resultFromQualificationError(error);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function missingPrerequisiteControl(options) {
|
|
518
|
+
const result = readPrerequisiteReports(options, {
|
|
519
|
+
candidateSha: options.candidateSha ?? undefined,
|
|
520
|
+
platform: options.platform,
|
|
521
|
+
deviceIdentifierHash: options.device === null || options.device === undefined ? undefined : hashIdentifier(options.device),
|
|
522
|
+
});
|
|
523
|
+
return result.valid
|
|
524
|
+
? resultFor("fail", "TN_QUALIFY_CONTROL_NOT_TRIGGERED", { errors: ["missing-prerequisite control had no missing or malformed prerequisite"] })
|
|
525
|
+
: resultFor("blocked", "TN_QUALIFY_PREREQUISITE_REPORT_MISSING", { blockers: result.errors });
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function writeResult(out, result) {
|
|
529
|
+
mkdirSync(out, { recursive: true });
|
|
530
|
+
writeFileSync(joinPath(out, "qualification-result.json"), `${JSON.stringify(result, null, 2)}\n`);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
export function validateFixture(path) {
|
|
534
|
+
if (!existsSync(path)) return resultFor("blocked", "TN_QUALIFY_FIXTURE_MISSING", { errors: [`fixture is missing: ${path}`] });
|
|
535
|
+
let evidence;
|
|
536
|
+
try {
|
|
537
|
+
evidence = JSON.parse(readFileSync(path, "utf8"));
|
|
538
|
+
} catch (error) {
|
|
539
|
+
return resultFor("fail", "TN_QUALIFY_EVIDENCE_INVALID", { errors: [error instanceof Error ? error.message : String(error)] });
|
|
540
|
+
}
|
|
541
|
+
const validation = validatePhysicalDeviceEvidence(evidence);
|
|
542
|
+
return validation.valid
|
|
543
|
+
? resultFor("pass", "TN_QUALIFY_EVIDENCE_PASS", { report: path })
|
|
544
|
+
: resultFor("fail", "TN_QUALIFY_EVIDENCE_INVALID", { errors: validation.errors, report: path });
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function artifactSha(path) {
|
|
548
|
+
try {
|
|
549
|
+
if (statSync(path).isFile()) return sha256File(path);
|
|
550
|
+
const hash = createHash("sha256");
|
|
551
|
+
const visit = (directory, prefix = "") => {
|
|
552
|
+
for (const entry of readdirSync(directory).sort()) {
|
|
553
|
+
const child = join(directory, entry);
|
|
554
|
+
const childRelative = prefix.length === 0 ? entry : `${prefix}/${entry}`;
|
|
555
|
+
if (statSync(child).isDirectory()) visit(child, childRelative);
|
|
556
|
+
else {
|
|
557
|
+
hash.update(childRelative);
|
|
558
|
+
hash.update("\0");
|
|
559
|
+
hash.update(readFileSync(child));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
visit(path);
|
|
564
|
+
return hash.digest("hex");
|
|
565
|
+
} catch (error) {
|
|
566
|
+
throw new QualificationError(`Cannot hash supplied artifact: ${error instanceof Error ? error.message : String(error)}.`, { code: "TN_QUALIFY_ARTIFACT_BLOCKED" });
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
function artifactProvenanceCandidates(path, explicitPath = null) {
|
|
571
|
+
return [
|
|
572
|
+
explicitPath,
|
|
573
|
+
`${path}.provenance.json`,
|
|
574
|
+
join(dirname(path), "artifact-provenance.json"),
|
|
575
|
+
path.endsWith(".app") ? join(path, "Contents/Resources/threenative-artifact-provenance.json") : null,
|
|
576
|
+
].filter((candidate, index, values) => candidate !== null && values.indexOf(candidate) === index);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function readArtifactProvenanceDocument(path, explicitPath) {
|
|
580
|
+
const provenancePath = artifactProvenanceCandidates(path, explicitPath).find((candidate) => existsSync(candidate));
|
|
581
|
+
if (provenancePath === undefined) throw new QualificationError(`No artifact provenance was supplied for ${path}; provide ${path}.provenance.json or --artifact-provenance.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_REQUIRED" });
|
|
582
|
+
let provenance;
|
|
583
|
+
try {
|
|
584
|
+
provenance = JSON.parse(readFileSync(provenancePath, "utf8"));
|
|
585
|
+
} catch (error) {
|
|
586
|
+
throw new QualificationError(`Artifact provenance is invalid JSON at ${provenancePath}: ${error instanceof Error ? error.message : String(error)}`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
587
|
+
}
|
|
588
|
+
return { provenance, provenancePath };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
export function readArtifactProvenance(path, {
|
|
592
|
+
platform,
|
|
593
|
+
candidateSha,
|
|
594
|
+
artifactSha256,
|
|
595
|
+
explicitPath = null,
|
|
596
|
+
} = {}) {
|
|
597
|
+
const { provenance, provenancePath } = readArtifactProvenanceDocument(path, explicitPath);
|
|
598
|
+
if (!isRecord(provenance)) throw new QualificationError(`Artifact provenance at ${provenancePath} must be an object.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
599
|
+
const allowed = new Set(["schemaVersion", "platform", "sourceSha", "candidateSha", "artifactSha256", "packageVersion", "releaseRun", "signing"]);
|
|
600
|
+
for (const key of Object.keys(provenance)) if (!allowed.has(key)) throw new QualificationError(`Artifact provenance has unknown field ${key}.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
601
|
+
const sourceSha = provenance.sourceSha ?? provenance.candidateSha;
|
|
602
|
+
if (provenance.schemaVersion !== 1 || typeof sourceSha !== "string" || !commitPattern.test(sourceSha)) throw new QualificationError(`Artifact provenance at ${provenancePath} lacks schemaVersion 1 and a source SHA.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
603
|
+
if (provenance.candidateSha !== undefined && provenance.candidateSha !== sourceSha) throw new QualificationError(`Artifact provenance source/candidate SHA mismatch at ${provenancePath}.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
|
|
604
|
+
if (provenance.platform !== platform) throw new QualificationError(`Artifact provenance target mismatch: expected ${platform}, got ${provenance.platform ?? "missing"}.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
605
|
+
if (candidateSha !== undefined && sourceSha !== candidateSha) throw new QualificationError(`Artifact source SHA mismatch: candidate ${candidateSha}, supplied artifact ${sourceSha}.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
|
|
606
|
+
if (provenance.artifactSha256 !== artifactSha256 || typeof artifactSha256 !== "string" || !sha256Pattern.test(provenance.artifactSha256)) throw new QualificationError(`Artifact SHA mismatch: supplied artifact is ${artifactSha256}, provenance records ${provenance.artifactSha256 ?? "missing"}.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
|
|
607
|
+
if (typeof provenance.packageVersion !== "string" || provenance.packageVersion.length === 0) throw new QualificationError("Artifact provenance must include packageVersion.", { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
608
|
+
if (!isRecord(provenance.signing)) throw new QualificationError("Artifact provenance must include signing facts from the supplied artifact.", { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_INVALID" });
|
|
609
|
+
return { ...provenance, sourceSha, provenancePath };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
export function verifyAndroidArtifact(path, candidateSha, options = {}) {
|
|
613
|
+
if (!existsSync(path)) throw new QualificationError(`Android artifact is missing at ${path}.`, { code: "TN_QUALIFY_SIGNING_REQUIRED" });
|
|
614
|
+
const run = options.command ?? command;
|
|
615
|
+
const locate = options.findExecutable ?? findExecutable;
|
|
616
|
+
const signer = locate("apksigner");
|
|
617
|
+
if (signer === null) throw new QualificationError("apksigner is unavailable; production signature cannot be verified before adb install.", { code: "TN_QUALIFY_SIGNING_TOOL_REQUIRED" });
|
|
618
|
+
const verification = run(signer, ["verify", "--print-certs", path]);
|
|
619
|
+
if (verification.status !== 0) throw new QualificationError(`Android signature verification failed: ${verification.stderr || verification.stdout}`, { code: "TN_QUALIFY_ANDROID_SIGNING_INVALID" });
|
|
620
|
+
const certificate = /certificate SHA-256 digest:\s*([0-9a-f:]+)/iu.exec(verification.stdout)?.[1]?.replaceAll(":", "").toLowerCase();
|
|
621
|
+
if (certificate === undefined || certificate.length !== 64) throw new QualificationError("Android signer certificate digest was not reported by apksigner.", { code: "TN_QUALIFY_ANDROID_SIGNING_INVALID" });
|
|
622
|
+
const unzip = locate("unzip");
|
|
623
|
+
if (unzip === null) throw new QualificationError("unzip is unavailable; arm64 library presence cannot be verified.", { code: "TN_QUALIFY_TOOL_REQUIRED" });
|
|
624
|
+
const listing = run(unzip, ["-l", path]);
|
|
625
|
+
if (listing.status !== 0 || !/lib\/arm64-v8a\//u.test(listing.stdout)) throw new QualificationError("Android artifact has no arm64-v8a native library.", { code: "TN_QUALIFY_ANDROID_ARM64_REQUIRED" });
|
|
626
|
+
if (/android:debuggable|debuggable=true/iu.test(verification.stdout)) throw new QualificationError("Android production artifact is debuggable.", { code: "TN_QUALIFY_ANDROID_SIGNING_INVALID" });
|
|
627
|
+
const artifactSha256 = artifactSha(path);
|
|
628
|
+
const provenance = readArtifactProvenance(path, { platform: "android", candidateSha, artifactSha256, explicitPath: options.artifactProvenance ?? null });
|
|
629
|
+
const signing = provenance.signing;
|
|
630
|
+
if (signing.certificateFingerprint !== certificate) throw new QualificationError("Android signer digest does not match the supplied artifact provenance.", { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
|
|
631
|
+
if (signing.debuggable !== false) throw new QualificationError("Android artifact provenance marks the production artifact as debuggable.", { code: "TN_QUALIFY_ANDROID_SIGNING_INVALID" });
|
|
632
|
+
return {
|
|
633
|
+
artifactSha256,
|
|
634
|
+
sourceSha: provenance.sourceSha,
|
|
635
|
+
packageVersion: provenance.packageVersion,
|
|
636
|
+
releaseRun: provenance.releaseRun ?? null,
|
|
637
|
+
certificateFingerprint: certificate,
|
|
638
|
+
signerId: signing.signerId,
|
|
639
|
+
profileFingerprint: null,
|
|
640
|
+
expiresAt: signing.expiresAt,
|
|
641
|
+
applicationId: signing.applicationId,
|
|
642
|
+
debuggable: false,
|
|
643
|
+
provenancePath: provenance.provenancePath,
|
|
644
|
+
verificationCommand: `apksigner verify --print-certs ${path}`,
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function inspectAndroidDevice(adb, serial, options = {}) {
|
|
649
|
+
const run = options.command ?? command;
|
|
650
|
+
const getprop = (name) => {
|
|
651
|
+
const value = run(adb, ["-s", serial, "shell", "getprop", name]);
|
|
652
|
+
if (value.status !== 0) throw new QualificationError(`adb could not read ${name}: ${value.stderr || value.stdout}`, { code: "TN_QUALIFY_ANDROID_DEVICE_BLOCKED" });
|
|
653
|
+
return value.stdout.trim();
|
|
654
|
+
};
|
|
655
|
+
const qemu = getprop("ro.kernel.qemu");
|
|
656
|
+
const hardware = getprop("ro.hardware");
|
|
657
|
+
if (qemu === "1" || /^(goldfish|ranchu)$/iu.test(hardware)) throw new QualificationError(`TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED: ${serial} identifies as an emulator.`, { code: "TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED" });
|
|
658
|
+
const abi = getprop("ro.product.cpu.abi");
|
|
659
|
+
if (!/^(arm64-v8a|aarch64)$/iu.test(abi)) throw new QualificationError(`Android device ABI ${abi} is not arm64.`, { code: "TN_QUALIFY_ANDROID_ARM64_REQUIRED" });
|
|
660
|
+
const gpuInfo = run(adb, ["-s", serial, "shell", "dumpsys", "SurfaceFlinger"]);
|
|
661
|
+
const gpu = gpuInfo.stdout.match(/(?:GLES|Vulkan|GPU)[^\n]*/iu)?.[0]?.trim() ?? "unknown GPU";
|
|
662
|
+
if (/swiftshader|software rasterizer|llvmpipe/iu.test(gpu)) throw new QualificationError(`Android device reports a software GPU: ${gpu}.`, { code: "TN_QUALIFY_NATIVE_GPU_REQUIRED" });
|
|
663
|
+
const size = run(adb, ["-s", serial, "shell", "wm", "size"]);
|
|
664
|
+
const dimensions = /(?:Physical size|Override size):\s*(\d+)x(\d+)/iu.exec(size.stdout);
|
|
665
|
+
if (dimensions === null) throw new QualificationError("Android device did not report a usable physical screen size.", { code: "TN_QUALIFY_ANDROID_DEVICE_BLOCKED" });
|
|
666
|
+
return {
|
|
667
|
+
platform: "android",
|
|
668
|
+
kind: "physical",
|
|
669
|
+
identifierHash: hashIdentifier(serial),
|
|
670
|
+
name: getprop("ro.product.name"),
|
|
671
|
+
manufacturer: getprop("ro.product.manufacturer"),
|
|
672
|
+
model: getprop("ro.product.model"),
|
|
673
|
+
osVersion: getprop("ro.build.version.release"),
|
|
674
|
+
osBuild: getprop("ro.build.id"),
|
|
675
|
+
cpuAbi: abi,
|
|
676
|
+
gpu,
|
|
677
|
+
driver: "Android Vulkan device driver",
|
|
678
|
+
screenModes: [{ width: Number(dimensions[1]), height: Number(dimensions[2]), orientation: Number(dimensions[1]) >= Number(dimensions[2]) ? "landscape" : "portrait" }],
|
|
679
|
+
nativeGpu: true,
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
function installAndroid(adb, serial, app, options = {}) {
|
|
684
|
+
const run = options.command ?? command;
|
|
685
|
+
// The Play Protect verifier dialog is modal and swallows the install, so an unattended
|
|
686
|
+
// lane behind it proves nothing. Suppress before the install, as every install lane must.
|
|
687
|
+
suppressPlayProtectOnAdbInstalls(serial, {
|
|
688
|
+
adb: (args) => String(run(adb, ["-s", serial, ...args], { timeout: 120_000 }).stdout),
|
|
689
|
+
});
|
|
690
|
+
const result = run(adb, ["-s", serial, "install", "--no-streaming", app], { timeout: 120_000 });
|
|
691
|
+
if (result.status !== 0) throw new QualificationError(`adb install failed before lifecycle qualification: ${result.stderr || result.stdout}`, { code: "TN_QUALIFY_ANDROID_INSTALL_BLOCKED" });
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/**
|
|
695
|
+
* The application this qualification drives, and the activity it launches.
|
|
696
|
+
*
|
|
697
|
+
* Both carried the pre-rename Mystral identity when this orchestrator was written. The Android
|
|
698
|
+
* identity was renamed while the orchestrator sat on an unlanded branch, so it would have launched a
|
|
699
|
+
* package that no longer exists and then read `gfxinfo` and `meminfo` for it — collecting empty
|
|
700
|
+
* telemetry from a process that never started. `android/app/build.gradle.kts` and
|
|
701
|
+
* `AndroidManifest.xml` are the source of truth; keep this in step with them.
|
|
702
|
+
*/
|
|
703
|
+
const ANDROID_APPLICATION_ID = "com.threenative.game";
|
|
704
|
+
const ANDROID_LAUNCH_ACTIVITY = `${ANDROID_APPLICATION_ID}/com.threenative.runtime.MystralActivity`;
|
|
705
|
+
|
|
706
|
+
function launchAndroid(adb, serial, options = {}) {
|
|
707
|
+
const run = options.command ?? command;
|
|
708
|
+
const result = run(adb, ["-s", serial, "shell", "am", "start", "-W", "-n", ANDROID_LAUNCH_ACTIVITY], { timeout: 30_000 });
|
|
709
|
+
if (result.status !== 0) throw new QualificationError(`Android launch failed: ${result.stderr || result.stdout}`, { code: "TN_QUALIFY_ANDROID_LAUNCH_FAILED", status: "fail" });
|
|
710
|
+
const pid = run(adb, ["-s", serial, "shell", "pidof", ANDROID_APPLICATION_ID]);
|
|
711
|
+
const value = Number(pid.stdout.trim().split(/\s+/u)[0]);
|
|
712
|
+
if (!Number.isInteger(value) || value <= 0) throw new QualificationError("Android launch did not report a live process id.", { code: "TN_QUALIFY_ANDROID_LAUNCH_FAILED", status: "fail" });
|
|
713
|
+
return value;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function jsonValuesFromOutput(stdout) {
|
|
717
|
+
const values = [];
|
|
718
|
+
for (let start = 0; start < stdout.length; start += 1) {
|
|
719
|
+
if (stdout[start] !== "{" && stdout[start] !== "[") continue;
|
|
720
|
+
let depth = 0;
|
|
721
|
+
let inString = false;
|
|
722
|
+
let escaped = false;
|
|
723
|
+
for (let index = start; index < stdout.length; index += 1) {
|
|
724
|
+
const character = stdout[index];
|
|
725
|
+
if (inString) {
|
|
726
|
+
if (escaped) escaped = false;
|
|
727
|
+
else if (character === "\\") escaped = true;
|
|
728
|
+
else if (character === '"') inString = false;
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
if (character === '"') {
|
|
732
|
+
inString = true;
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (character === "{" || character === "[") depth += 1;
|
|
736
|
+
else if (character === "}") depth -= 1;
|
|
737
|
+
else if (character === "]") depth -= 1;
|
|
738
|
+
if (depth === 0) {
|
|
739
|
+
try {
|
|
740
|
+
values.push(JSON.parse(stdout.slice(start, index + 1)));
|
|
741
|
+
} catch {
|
|
742
|
+
// A diagnostic may contain braces that are not a complete JSON value.
|
|
743
|
+
}
|
|
744
|
+
break;
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
return values;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
export function parsePlaytestReport(stdout) {
|
|
752
|
+
const reports = jsonValuesFromOutput(stdout).filter((value) => isRecord(value) && (value.observations !== undefined || value.assertionResults !== undefined || value.diagnostics !== undefined || (typeof value.pass === "boolean" && value.scenario !== undefined)));
|
|
753
|
+
return reports.at(-1) ?? null;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
function runLifecycleScenario(options, { target, device, adb, app }, dependencies = {}) {
|
|
757
|
+
const cli = joinPath(workspaceRoot, "packages/playtest/dist/runner/cli.js");
|
|
758
|
+
if (!existsSync(cli)) throw new QualificationError("Playtest CLI is missing; run pnpm --filter @threenative/playtest build.", { code: "TN_QUALIFY_TOOL_REQUIRED" });
|
|
759
|
+
const args = [cli, defaultScenario, "--target", target, "--device", device, "--project", joinPath(workspaceRoot, "examples/native-smoke"), "--artifacts", joinPath(options.out, "playtest"), "--timeout", String(Math.max(options.durationMs, 60_000))];
|
|
760
|
+
if (target === "android") args.push("--adb", adb);
|
|
761
|
+
else args.push("--ios-transport", "device", "--app", app);
|
|
762
|
+
const startedAt = new Date((dependencies.now ?? Date.now)()).toISOString();
|
|
763
|
+
const result = (dependencies.command ?? command)(process.execPath, args, { cwd: workspaceRoot, timeout: Math.max(options.durationMs + 30_000, 90_000) });
|
|
764
|
+
const report = parsePlaytestReport(result.stdout);
|
|
765
|
+
if (result.status !== 0 || report?.pass !== true) throw new QualificationError(`Physical lifecycle scenario failed: ${report?.diagnostics?.map((item) => item.message).join("; ") || result.stderr || "assertion failure"}`, { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
|
|
766
|
+
const reportPath = joinPath(options.out, "playtest/report.json");
|
|
767
|
+
mkdirSync(dirname(reportPath), { recursive: true });
|
|
768
|
+
writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
|
|
769
|
+
return {
|
|
770
|
+
report,
|
|
771
|
+
reportPath,
|
|
772
|
+
startedAt,
|
|
773
|
+
completedAt: new Date((dependencies.now ?? Date.now)()).toISOString(),
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
function unavailableCollector(source, unit, error) {
|
|
778
|
+
return { available: false, source, unit, samples: [], error };
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function availableCollector(source, unit, samples) {
|
|
782
|
+
return samples.length === 0
|
|
783
|
+
? unavailableCollector(source, unit, "collector returned no samples")
|
|
784
|
+
: { available: true, source, unit, samples, error: null };
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
export function sampleOffsets(durationMs, cadenceMs) {
|
|
788
|
+
if (!Number.isInteger(durationMs) || durationMs <= 0 || !Number.isInteger(cadenceMs) || cadenceMs <= 0) throw new QualificationError("Telemetry duration and cadence must be positive integers.", { code: "TN_QUALIFY_ARGUMENT" });
|
|
789
|
+
const offsets = [];
|
|
790
|
+
for (let offset = 0; offset < durationMs; offset += cadenceMs) offsets.push(offset);
|
|
791
|
+
offsets.push(durationMs);
|
|
792
|
+
return [...new Set(offsets)];
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function sleepBlocking(durationMs) {
|
|
796
|
+
if (durationMs <= 0) return;
|
|
797
|
+
const atomics = new Int32Array(new SharedArrayBuffer(4));
|
|
798
|
+
Atomics.wait(atomics, 0, 0, durationMs);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
function parseGfxinfoFrameIntervals(stdout) {
|
|
802
|
+
const lines = stdout.split(/\r?\n/u).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
803
|
+
const headerIndex = lines.findIndex((line) => /(?:^|,)IntendedVsync(?:,|$)/u.test(line) && /(?:^|,)FrameCompleted(?:,|$)/u.test(line));
|
|
804
|
+
if (headerIndex < 0) return [];
|
|
805
|
+
const headers = lines[headerIndex].split(",");
|
|
806
|
+
const intendedIndex = headers.indexOf("IntendedVsync");
|
|
807
|
+
const completedIndex = headers.indexOf("FrameCompleted");
|
|
808
|
+
if (intendedIndex < 0 || completedIndex < 0) return [];
|
|
809
|
+
const intervals = [];
|
|
810
|
+
for (const line of lines.slice(headerIndex + 1)) {
|
|
811
|
+
const fields = line.split(",");
|
|
812
|
+
const intended = Number(fields[intendedIndex]);
|
|
813
|
+
const completed = Number(fields[completedIndex]);
|
|
814
|
+
if (Number.isFinite(intended) && Number.isFinite(completed) && completed >= intended) intervals.push((completed - intended) / 1_000_000);
|
|
815
|
+
}
|
|
816
|
+
return intervals.filter((value) => Number.isFinite(value) && value >= 0);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
function collectSampledAndroidValue({
|
|
820
|
+
adb,
|
|
821
|
+
serial,
|
|
822
|
+
durationMs,
|
|
823
|
+
cadenceMs,
|
|
824
|
+
commandRunner,
|
|
825
|
+
now,
|
|
826
|
+
sleep,
|
|
827
|
+
}) {
|
|
828
|
+
const startedMs = now();
|
|
829
|
+
const frameSamples = [];
|
|
830
|
+
const memorySamples = [];
|
|
831
|
+
const thermalSamples = [];
|
|
832
|
+
const batterySamples = [];
|
|
833
|
+
const errors = { frame: [], memory: [], thermal: [], battery: [] };
|
|
834
|
+
for (const offset of sampleOffsets(durationMs, cadenceMs)) {
|
|
835
|
+
const target = startedMs + offset;
|
|
836
|
+
const delay = target - now();
|
|
837
|
+
if (delay > 0) sleep(delay);
|
|
838
|
+
const at = new Date(now()).toISOString();
|
|
839
|
+
const frame = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "gfxinfo", ANDROID_APPLICATION_ID, "framestats"]);
|
|
840
|
+
const frameIntervals = frame.status === 0 ? parseGfxinfoFrameIntervals(frame.stdout) : [];
|
|
841
|
+
if (frameIntervals.length === 0) errors.frame.push(frame.stderr || `no frame intervals at ${at}`);
|
|
842
|
+
else for (const value of frameIntervals) frameSamples.push({ at, value });
|
|
843
|
+
|
|
844
|
+
const memory = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "meminfo", ANDROID_APPLICATION_ID]);
|
|
845
|
+
const memoryKb = /TOTAL\s+(\d+)/iu.exec(memory.stdout)?.[1];
|
|
846
|
+
if (memory.status !== 0 || memoryKb === undefined) errors.memory.push(memory.stderr || `TOTAL row unavailable at ${at}`);
|
|
847
|
+
else memorySamples.push({ at, value: Number(memoryKb) * 1024 });
|
|
848
|
+
|
|
849
|
+
const thermal = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "thermalservice"]);
|
|
850
|
+
const thermalState = /(?:Status|Current thermal status):\s*([^\n]+)/iu.exec(thermal.stdout)?.[1]?.trim();
|
|
851
|
+
if (thermal.status !== 0 || thermalState === undefined) errors.thermal.push(thermal.stderr || `thermal state unavailable at ${at}`);
|
|
852
|
+
else thermalSamples.push({ at, value: thermalState });
|
|
853
|
+
|
|
854
|
+
const battery = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "battery"]);
|
|
855
|
+
const batteryPercent = /level:\s*(\d+)/iu.exec(battery.stdout)?.[1];
|
|
856
|
+
if (battery.status !== 0 || batteryPercent === undefined) errors.battery.push(battery.stderr || `battery level unavailable at ${at}`);
|
|
857
|
+
else batterySamples.push({ at, value: Number(batteryPercent) });
|
|
858
|
+
}
|
|
859
|
+
return {
|
|
860
|
+
frame: errors.frame.length === 0 ? availableCollector(`adb shell dumpsys gfxinfo ${ANDROID_APPLICATION_ID} framestats`, "ms", frameSamples) : unavailableCollector(`adb shell dumpsys gfxinfo ${ANDROID_APPLICATION_ID} framestats`, "ms", errors.frame.join("; ")),
|
|
861
|
+
memory: errors.memory.length === 0 ? availableCollector(`adb shell dumpsys meminfo ${ANDROID_APPLICATION_ID}`, "bytes", memorySamples) : unavailableCollector(`adb shell dumpsys meminfo ${ANDROID_APPLICATION_ID}`, "bytes", errors.memory.join("; ")),
|
|
862
|
+
thermal: errors.thermal.length === 0 ? availableCollector("adb shell dumpsys thermalservice", "state", thermalSamples) : unavailableCollector("adb shell dumpsys thermalservice", "state", errors.thermal.join("; ")),
|
|
863
|
+
battery: errors.battery.length === 0 ? availableCollector("adb shell dumpsys battery", "percent", batterySamples) : unavailableCollector("adb shell dumpsys battery", "percent", errors.battery.join("; ")),
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
export function collectAndroidTelemetry(adb, serial, durationMs, cadenceMs, dependencies = {}) {
|
|
868
|
+
const telemetry = collectSampledAndroidValue({
|
|
869
|
+
adb,
|
|
870
|
+
serial,
|
|
871
|
+
durationMs,
|
|
872
|
+
cadenceMs,
|
|
873
|
+
commandRunner: dependencies.command ?? command,
|
|
874
|
+
now: dependencies.now ?? Date.now,
|
|
875
|
+
sleep: dependencies.sleep ?? sleepBlocking,
|
|
876
|
+
});
|
|
877
|
+
const batteryStart = telemetry.battery.samples.at(0);
|
|
878
|
+
const batteryEnd = telemetry.battery.samples.at(-1);
|
|
879
|
+
if (batteryStart === undefined || batteryEnd === undefined || batteryStart.at === batteryEnd.at) telemetry.battery = unavailableCollector(telemetry.battery.source, telemetry.battery.unit, "battery start/end samples are unavailable");
|
|
880
|
+
return { durationMs, cadenceMs, ...telemetry };
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
export function collectIosTelemetry({ path = null, durationMs, cadenceMs, read = readFileSync } = {}) {
|
|
884
|
+
const unavailable = (name, unit) => unavailableCollector(`signed iOS qualification bridge: ${name}`, unit, "signed-device collector did not provide a report");
|
|
885
|
+
if (path === null || !existsSync(path)) return {
|
|
886
|
+
durationMs,
|
|
887
|
+
cadenceMs,
|
|
888
|
+
frame: unavailable("frame", "ms"),
|
|
889
|
+
memory: unavailable("memory", "bytes"),
|
|
890
|
+
thermal: unavailable("thermal", "state"),
|
|
891
|
+
battery: unavailable("battery", "percent"),
|
|
892
|
+
};
|
|
893
|
+
let value;
|
|
894
|
+
try {
|
|
895
|
+
value = JSON.parse(read(path, "utf8"));
|
|
896
|
+
} catch (error) {
|
|
897
|
+
const reason = `signed iOS collector report is invalid: ${error instanceof Error ? error.message : String(error)}`;
|
|
898
|
+
return { durationMs, cadenceMs, frame: unavailableCollector("signed iOS qualification bridge: frame", "ms", reason), memory: unavailableCollector("signed iOS qualification bridge: memory", "bytes", reason), thermal: unavailableCollector("signed iOS qualification bridge: thermal", "state", reason), battery: unavailableCollector("signed iOS qualification bridge: battery", "percent", reason) };
|
|
899
|
+
}
|
|
900
|
+
const telemetry = value.telemetry ?? value;
|
|
901
|
+
if (!isRecord(telemetry) || telemetry.durationMs !== durationMs || telemetry.cadenceMs !== cadenceMs) {
|
|
902
|
+
const reason = "signed iOS collector duration/cadence does not match the requested sampling window";
|
|
903
|
+
return { durationMs, cadenceMs, frame: unavailableCollector("signed iOS qualification bridge: frame", "ms", reason), memory: unavailableCollector("signed iOS qualification bridge: memory", "bytes", reason), thermal: unavailableCollector("signed iOS qualification bridge: thermal", "state", reason), battery: unavailableCollector("signed iOS qualification bridge: battery", "percent", reason) };
|
|
904
|
+
}
|
|
905
|
+
return telemetry;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function iosProcessPid(telemetry, playtestRun) {
|
|
909
|
+
const observed = telemetry.processPid ?? telemetry.pid ?? playtestRun.report?.pid ?? playtestRun.report?.observations?.resources?.GameState?.after?.pid;
|
|
910
|
+
const pid = Number(observed);
|
|
911
|
+
if (!Number.isInteger(pid) || pid <= 0) throw new QualificationError("Signed iOS collector did not provide the live app process PID.", { code: "TN_QUALIFY_IOS_PROCESS_REQUIRED" });
|
|
912
|
+
return pid;
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function prerequisiteEvidence(preflightResult) {
|
|
916
|
+
return Object.fromEntries(REQUIRED_PREREQUISITES.map((name) => {
|
|
917
|
+
const record = preflightResult.prerequisites[name];
|
|
918
|
+
return [name, {
|
|
919
|
+
status: "pass",
|
|
920
|
+
reportPath: relative(workspaceRoot, record.path).replaceAll("\\", "/"),
|
|
921
|
+
sha256: record.sha256,
|
|
922
|
+
candidateSha: record.validation.candidateSha,
|
|
923
|
+
gateIds: Array.isArray(record.report.gateIds) ? record.report.gateIds : record.validation.controls.map(({ gateId }) => gateId),
|
|
924
|
+
}];
|
|
925
|
+
}));
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function reportConsumption(preflightResult, name, key) {
|
|
929
|
+
const report = preflightResult.prerequisites[name].report;
|
|
930
|
+
const value = report.consumption?.[key] ?? report.results?.[key] ?? report.observations?.[key] ?? (key === "multitouch" && name === "prd053" ? report.results : key === "physics" && name === "prd046" ? report.results : undefined);
|
|
931
|
+
if (!isRecord(value)) throw new QualificationError(`${name} prerequisite report does not contain observed ${key} results.`, { code: "TN_QUALIFY_PREREQUISITE_SCHEMA_INVALID" });
|
|
932
|
+
return value;
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
function productionConsumption(preflightResult, candidateSha) {
|
|
936
|
+
const multitouch = reportConsumption(preflightResult, "prd053", "multitouch");
|
|
937
|
+
const physics = reportConsumption(preflightResult, "prd046", "physics");
|
|
938
|
+
const result = { multitouch: { ...multitouch }, physics: { ...physics } };
|
|
939
|
+
for (const [key, value] of Object.entries(result)) {
|
|
940
|
+
if (value.candidateSha !== candidateSha) throw new QualificationError(`Consumed ${key} prerequisite candidate SHA does not match ${candidateSha}.`, { code: "TN_QUALIFY_PROVENANCE_MISMATCH" });
|
|
941
|
+
if (value.deviceClass !== "physical") throw new QualificationError(`Consumed ${key} prerequisite is not physical-device evidence.`, { code: "TN_QUALIFY_PREREQUISITE_TARGET_INVALID" });
|
|
942
|
+
}
|
|
943
|
+
return result;
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
function countScenarioErrors(playtest) {
|
|
947
|
+
const diagnostics = Array.isArray(playtest.diagnostics) ? playtest.diagnostics : [];
|
|
948
|
+
const runtimeErrors = playtest.observations?.runtimeDiagnostics?.recentRuntimeErrors;
|
|
949
|
+
const errors = [...diagnostics, ...(Array.isArray(runtimeErrors) ? runtimeErrors : [])];
|
|
950
|
+
return errors.filter((item) => item?.severity === "error" || /GPU|WebGPU|validation/iu.test(JSON.stringify(item))).length;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
export function evaluateLifecycleObservation(after, before = undefined) {
|
|
954
|
+
const errors = [];
|
|
955
|
+
if (!isRecord(after)) return { valid: false, errors: ["scenario after observation is missing"] };
|
|
956
|
+
const phases = ["background", "foreground", "supported-rotation", "resume"];
|
|
957
|
+
if (!Array.isArray(after.lifecycleEvents) || after.lifecycleEvents.length !== phases.length) errors.push("scenario lifecycleEvents must contain four observed events");
|
|
958
|
+
else {
|
|
959
|
+
after.lifecycleEvents.forEach((event, index) => {
|
|
960
|
+
if (!isRecord(event) || event.phase !== phases[index]) errors.push(`scenario lifecycleEvents[${index}] is not the expected ${phases[index]} observation`);
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
if (typeof after.sessionNonce !== "string" || after.sessionNonce.length === 0) errors.push("scenario sessionNonce is missing");
|
|
964
|
+
if (before?.sessionNonce !== undefined && before.sessionNonce !== after.sessionNonce) errors.push("scenario sessionNonce changed across lifecycle");
|
|
965
|
+
if (after.stateContinuity !== true) errors.push("scenario stateContinuity is not true");
|
|
966
|
+
if (after.framesPaused !== true) errors.push("scenario did not observe paused frames");
|
|
967
|
+
if (after.framesAdvanced !== true) errors.push("scenario did not observe advanced frames after resume");
|
|
968
|
+
if (after.surfaceValidAfterResume !== true) errors.push("scenario did not observe a valid surface after resume");
|
|
969
|
+
if (after.backgroundGapIntegrated !== false) errors.push("scenario integrated the background wall-clock gap");
|
|
970
|
+
if (!Number.isFinite(after.maxFrameIntervalMs) || after.maxFrameIntervalMs < 0) errors.push("scenario maxFrameIntervalMs is missing or non-finite");
|
|
971
|
+
if (!Number.isFinite(after.physicsStepDelta) || after.physicsStepDelta < 0) errors.push("scenario physicsStepDelta is missing or non-finite");
|
|
972
|
+
return { valid: errors.length === 0, errors };
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function actualArtifactRecord(path, producerCommand, retention = "ignored-raw") {
|
|
976
|
+
if (!existsSync(path) || !statSync(path).isFile()) throw new QualificationError(`Qualification artifact is missing at ${path}.`, { code: "TN_QUALIFY_ARTIFACT_BLOCKED" });
|
|
977
|
+
return {
|
|
978
|
+
path: relative(workspaceRoot, path).replaceAll("\\", "/"),
|
|
979
|
+
sha256: sha256File(path),
|
|
980
|
+
size: statSync(path).size,
|
|
981
|
+
producerCommand,
|
|
982
|
+
retention,
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
export function buildProductionEvidence({
|
|
987
|
+
platform,
|
|
988
|
+
source,
|
|
989
|
+
artifact,
|
|
990
|
+
device,
|
|
991
|
+
signing,
|
|
992
|
+
preflightResult,
|
|
993
|
+
playtestRun,
|
|
994
|
+
telemetry,
|
|
995
|
+
pid,
|
|
996
|
+
processLiveness,
|
|
997
|
+
timestamps,
|
|
998
|
+
artifactPaths,
|
|
999
|
+
gateEvidence,
|
|
1000
|
+
}) {
|
|
1001
|
+
const playtest = playtestRun?.report ?? playtestRun;
|
|
1002
|
+
const after = playtest?.observations?.resources?.GameState?.after;
|
|
1003
|
+
const before = playtest?.observations?.resources?.GameState?.before;
|
|
1004
|
+
const lifecycle = evaluateLifecycleObservation(after, before);
|
|
1005
|
+
if (!lifecycle.valid) throw new QualificationError(lifecycle.errors.join("; "), { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
|
|
1006
|
+
if (!Array.isArray(playtest.assertionResults) || playtest.assertionResults.length === 0) throw new QualificationError("Physical lifecycle scenario produced no assertions.", { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
|
|
1007
|
+
if (!Number.isInteger(after.frames) || after.frames < 300) throw new QualificationError("Physical lifecycle scenario did not observe 300 frames.", { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
|
|
1008
|
+
if (!Number.isInteger(pid) || pid <= 0) throw new QualificationError("Physical lifecycle scenario did not provide the app process id.", { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
|
|
1009
|
+
if (processLiveness !== true) throw new QualificationError("Physical lifecycle scenario did not observe a live app process.", { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
|
|
1010
|
+
if (!isRecord(artifact) || artifact.sourceSha !== source.headSha || artifact.artifactSha256 === undefined) throw new QualificationError("Supplied artifact provenance is absent or does not match source HEAD.", { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
|
|
1011
|
+
if (!isRecord(device) || device.nativeGpu !== true) throw new QualificationError("Physical device observation did not prove a native GPU.", { code: "TN_QUALIFY_NATIVE_GPU_REQUIRED" });
|
|
1012
|
+
if (!isRecord(signing)) throw new QualificationError("Supplied artifact signing observation is missing.", { code: "TN_QUALIFY_SIGNING_REQUIRED" });
|
|
1013
|
+
if (!Array.isArray(artifactPaths) || artifactPaths.length === 0) throw new QualificationError("Qualification artifact observations are missing.", { code: "TN_QUALIFY_ARTIFACT_BLOCKED" });
|
|
1014
|
+
if (!Array.isArray(gateEvidence)) throw new QualificationError("Observed-red gate evidence is missing.", { code: "TN_QUALIFY_GATE_EVIDENCE_REQUIRED" });
|
|
1015
|
+
const { nativeGpu, ...publicDevice } = device;
|
|
1016
|
+
const candidateSha = source.headSha;
|
|
1017
|
+
const evidence = {
|
|
1018
|
+
schemaVersion: 1,
|
|
1019
|
+
identity: {
|
|
1020
|
+
schemaVersion: 1,
|
|
1021
|
+
runId: `prd056-${platform}-${timestamps.startedAt}`,
|
|
1022
|
+
startedAt: timestamps.startedAt,
|
|
1023
|
+
endedAt: timestamps.endedAt,
|
|
1024
|
+
verdict: "pass",
|
|
1025
|
+
blockers: [],
|
|
1026
|
+
evidenceClass: "physical-device",
|
|
1027
|
+
},
|
|
1028
|
+
source: {
|
|
1029
|
+
remote: source.remote,
|
|
1030
|
+
branch: source.branch,
|
|
1031
|
+
headSha: source.headSha,
|
|
1032
|
+
worktree: source.worktree,
|
|
1033
|
+
artifactSourceSha: artifact.sourceSha,
|
|
1034
|
+
packageVersion: artifact.packageVersion,
|
|
1035
|
+
artifactSha256: artifact.artifactSha256,
|
|
1036
|
+
releaseRun: artifact.releaseRun ?? null,
|
|
1037
|
+
publishedPackage: null,
|
|
1038
|
+
promotedConsumer: null,
|
|
1039
|
+
},
|
|
1040
|
+
device: publicDevice,
|
|
1041
|
+
signing: {
|
|
1042
|
+
verificationCommand: signing.verificationCommand,
|
|
1043
|
+
signerId: signing.signerId,
|
|
1044
|
+
certificateFingerprint: signing.certificateFingerprint,
|
|
1045
|
+
profileFingerprint: signing.profileFingerprint ?? null,
|
|
1046
|
+
expiresAt: signing.expiresAt,
|
|
1047
|
+
applicationId: signing.applicationId,
|
|
1048
|
+
debuggable: signing.debuggable,
|
|
1049
|
+
installResult: "installed",
|
|
1050
|
+
},
|
|
1051
|
+
prerequisites: prerequisiteEvidence(preflightResult),
|
|
1052
|
+
execution: {
|
|
1053
|
+
installStartedAt: timestamps.installStartedAt,
|
|
1054
|
+
launchStartedAt: timestamps.launchStartedAt,
|
|
1055
|
+
pid,
|
|
1056
|
+
sessionNonce: after.sessionNonce,
|
|
1057
|
+
readyAt: timestamps.readyAt,
|
|
1058
|
+
firstFrameAt: timestamps.firstFrameAt,
|
|
1059
|
+
frame300At: timestamps.frame300At,
|
|
1060
|
+
frames: after.frames,
|
|
1061
|
+
nonBlankCaptureSha256: artifactPaths.find((item) => item.capture === true)?.sha256 ?? "",
|
|
1062
|
+
gpuErrorCount: countScenarioErrors(playtest),
|
|
1063
|
+
arm64: /^(?:arm64-v8a|arm64|aarch64)$/iu.test(publicDevice.cpuAbi),
|
|
1064
|
+
nativeGpu,
|
|
1065
|
+
processLiveness,
|
|
1066
|
+
assertionCount: playtest.assertionResults.length,
|
|
1067
|
+
},
|
|
1068
|
+
lifecycle: {
|
|
1069
|
+
events: after.lifecycleEvents.map((event) => ({ ...event, pid, sessionNonce: after.sessionNonce })),
|
|
1070
|
+
sameSession: before?.sessionNonce === after.sessionNonce,
|
|
1071
|
+
framesPaused: after.framesPaused,
|
|
1072
|
+
framesAdvanced: after.framesAdvanced,
|
|
1073
|
+
maxFrameIntervalMs: after.maxFrameIntervalMs,
|
|
1074
|
+
surfaceValidAfterResume: after.surfaceValidAfterResume,
|
|
1075
|
+
stateContinuity: after.stateContinuity,
|
|
1076
|
+
physicsStepDelta: after.physicsStepDelta,
|
|
1077
|
+
backgroundGapIntegrated: after.backgroundGapIntegrated,
|
|
1078
|
+
},
|
|
1079
|
+
consumption: productionConsumption(preflightResult, candidateSha),
|
|
1080
|
+
telemetry,
|
|
1081
|
+
artifacts: artifactPaths.map(({ capture: _capture, ...record }) => record),
|
|
1082
|
+
gateEvidence,
|
|
1083
|
+
};
|
|
1084
|
+
assertValidPhysicalDeviceEvidence(evidence, {
|
|
1085
|
+
candidateSha,
|
|
1086
|
+
artifactSha256: artifact.artifactSha256,
|
|
1087
|
+
platform,
|
|
1088
|
+
identifierHash: publicDevice.identifierHash,
|
|
1089
|
+
});
|
|
1090
|
+
return evidence;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function writeArtifactObservation(options, artifact) {
|
|
1094
|
+
const path = joinPath(options.out, "artifact-provenance.json");
|
|
1095
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
1096
|
+
writeFileSync(path, `${JSON.stringify({ schemaVersion: 1, platform: options.platform, sourceSha: artifact.sourceSha, artifactSha256: artifact.artifactSha256, packageVersion: artifact.packageVersion }, null, 2)}\n`);
|
|
1097
|
+
return path;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
function readGateEvidence(path) {
|
|
1101
|
+
if (path === null || !existsSync(path)) return [];
|
|
1102
|
+
let value;
|
|
1103
|
+
try {
|
|
1104
|
+
value = JSON.parse(readFileSync(path, "utf8"));
|
|
1105
|
+
} catch (error) {
|
|
1106
|
+
throw new QualificationError(`Gate evidence is invalid JSON: ${error instanceof Error ? error.message : String(error)}`, { code: "TN_QUALIFY_GATE_EVIDENCE_INVALID" });
|
|
1107
|
+
}
|
|
1108
|
+
const gates = Array.isArray(value) ? value : value?.gates;
|
|
1109
|
+
if (!Array.isArray(gates)) throw new QualificationError("Gate evidence must be an array or an object with a gates array.", { code: "TN_QUALIFY_GATE_EVIDENCE_INVALID" });
|
|
1110
|
+
return gates;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
function telemetryFailure(telemetry) {
|
|
1114
|
+
return ["frame", "memory", "thermal", "battery"]
|
|
1115
|
+
.filter((name) => telemetry[name]?.available !== true)
|
|
1116
|
+
.map((name) => `${name}: ${telemetry[name]?.error ?? "collector unavailable"}`);
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function runAndroidQualification(options, preflightResult, artifact, dependencies = {}) {
|
|
1120
|
+
const locate = dependencies.findExecutable ?? findExecutable;
|
|
1121
|
+
const adb = dependencies.adb ?? locate("adb");
|
|
1122
|
+
if (adb === null) throw new QualificationError("adb is unavailable; physical Android qualification is blocked.", { code: "TN_QUALIFY_TOOL_REQUIRED" });
|
|
1123
|
+
const run = dependencies.command ?? command;
|
|
1124
|
+
const now = dependencies.now ?? Date.now;
|
|
1125
|
+
const device = inspectAndroidDevice(adb, options.device, { command: run });
|
|
1126
|
+
const installStartedAt = new Date(now()).toISOString();
|
|
1127
|
+
installAndroid(adb, options.device, options.app, { command: run });
|
|
1128
|
+
const launchStartedAt = new Date(now()).toISOString();
|
|
1129
|
+
const pid = launchAndroid(adb, options.device, { command: run });
|
|
1130
|
+
const lifecycleRun = runLifecycleScenario(options, { target: "android", device: options.device, adb, app: options.app }, { command: run, now });
|
|
1131
|
+
const telemetry = collectAndroidTelemetry(adb, options.device, options.durationMs, options.cadenceMs, { command: run, now, sleep: dependencies.sleep });
|
|
1132
|
+
const telemetryErrors = telemetryFailure(telemetry);
|
|
1133
|
+
if (telemetryErrors.length > 0) throw new QualificationError(`Android telemetry is incomplete: ${telemetryErrors.join("; ")}`, { code: "TN_QUALIFY_TELEMETRY_INCOMPLETE", details: telemetryErrors });
|
|
1134
|
+
const artifactObservationPath = writeArtifactObservation(options, artifact);
|
|
1135
|
+
const capturePath = joinPath(options.out, "playtest/after.png");
|
|
1136
|
+
const artifactPaths = [
|
|
1137
|
+
{ ...actualArtifactRecord(lifecycleRun.reportPath, "native:qualify:physical playtest"), capture: false },
|
|
1138
|
+
{ ...actualArtifactRecord(artifactObservationPath, "native:qualify:physical artifact provenance"), capture: false },
|
|
1139
|
+
{ ...actualArtifactRecord(capturePath, "native:qualify:physical playtest screenshot"), capture: true },
|
|
1140
|
+
];
|
|
1141
|
+
const endedAt = new Date(now()).toISOString();
|
|
1142
|
+
const evidence = buildProductionEvidence({
|
|
1143
|
+
platform: "android",
|
|
1144
|
+
source: preflightResult.source,
|
|
1145
|
+
artifact,
|
|
1146
|
+
device,
|
|
1147
|
+
signing: { ...artifact, profileFingerprint: null, debuggable: false },
|
|
1148
|
+
preflightResult,
|
|
1149
|
+
playtestRun: lifecycleRun,
|
|
1150
|
+
telemetry,
|
|
1151
|
+
pid,
|
|
1152
|
+
processLiveness: lifecycleRun.report.pass === true,
|
|
1153
|
+
timestamps: { startedAt: installStartedAt, endedAt, installStartedAt, launchStartedAt, readyAt: lifecycleRun.startedAt, firstFrameAt: lifecycleRun.startedAt, frame300At: lifecycleRun.completedAt },
|
|
1154
|
+
artifactPaths,
|
|
1155
|
+
gateEvidence: readGateEvidence(options.gateEvidence),
|
|
1156
|
+
});
|
|
1157
|
+
const reportPath = joinPath(options.out, "physical-device-evidence.json");
|
|
1158
|
+
writeFileSync(reportPath, `${JSON.stringify(evidence, null, 2)}\n`);
|
|
1159
|
+
return resultFor("pass", "TN_QUALIFY_PHYSICAL_PASS", { report: reportPath });
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
function verifyIosArtifact(path, candidateSha, options = {}) {
|
|
1163
|
+
if (!existsSync(path)) throw new QualificationError(`iOS artifact is missing at ${path}.`, { code: "TN_QUALIFY_SIGNING_REQUIRED" });
|
|
1164
|
+
const locate = options.findExecutable ?? findExecutable;
|
|
1165
|
+
const run = options.command ?? command;
|
|
1166
|
+
const codesign = locate("codesign");
|
|
1167
|
+
if (codesign === null) throw new QualificationError("codesign is unavailable; signed iOS qualification is blocked.", { code: "TN_QUALIFY_SIGNING_TOOL_REQUIRED" });
|
|
1168
|
+
const verification = run(codesign, ["--verify", "--strict", "--deep", path]);
|
|
1169
|
+
if (verification.status !== 0) throw new QualificationError(`iOS signing verification failed: ${verification.stderr || verification.stdout}`, { code: "TN_QUALIFY_IOS_SIGNING_INVALID" });
|
|
1170
|
+
const details = run(codesign, ["-dv", "--verbose=4", path]);
|
|
1171
|
+
const team = /TeamIdentifier=([^\n]+)/u.exec(details.stderr || details.stdout)?.[1]?.trim();
|
|
1172
|
+
const identifier = /Identifier=([^\n]+)/u.exec(details.stderr || details.stdout)?.[1]?.trim();
|
|
1173
|
+
if (team === undefined || identifier === undefined) throw new QualificationError("codesign did not report team and application identifiers.", { code: "TN_QUALIFY_IOS_SIGNING_INVALID" });
|
|
1174
|
+
if (/<key>get-task-allow<\/key>\s*<true\s*\/>/u.test(details.stdout || details.stderr)) throw new QualificationError("iOS artifact is development-debuggable (get-task-allow=true).", { code: "TN_QUALIFY_IOS_SIGNING_INVALID" });
|
|
1175
|
+
const artifactSha256 = artifactSha(path);
|
|
1176
|
+
const provenance = readArtifactProvenance(path, { platform: "ios", candidateSha, artifactSha256, explicitPath: options.artifactProvenance ?? null });
|
|
1177
|
+
const signing = provenance.signing;
|
|
1178
|
+
if (signing.signerId !== team || signing.applicationId !== identifier || signing.debuggable !== false) throw new QualificationError("iOS signing facts do not match the supplied artifact provenance.", { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
|
|
1179
|
+
if (signing.profileFingerprint === null || signing.profileFingerprint === undefined) throw new QualificationError("iOS artifact provenance lacks the embedded provisioning-profile fingerprint.", { code: "TN_QUALIFY_IOS_SIGNING_INVALID" });
|
|
1180
|
+
return { ...provenance, artifactSha256, signerId: team, applicationId: identifier, certificateFingerprint: signing.certificateFingerprint, profileFingerprint: signing.profileFingerprint, expiresAt: signing.expiresAt, debuggable: false, verificationCommand: `codesign --verify --strict --deep ${path}` };
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
function inspectIosDevice(device, options = {}) {
|
|
1184
|
+
const locate = options.findExecutable ?? findExecutable;
|
|
1185
|
+
const run = options.command ?? command;
|
|
1186
|
+
const devicectl = locate("devicectl");
|
|
1187
|
+
if (devicectl === null) throw new QualificationError("devicectl is unavailable; physical iOS qualification is blocked.", { code: "TN_QUALIFY_TOOL_REQUIRED" });
|
|
1188
|
+
const details = run(devicectl, ["device", "info", "details", "--device", device]);
|
|
1189
|
+
if (details.status !== 0) throw new QualificationError(`devicectl could not inspect ${device}: ${details.stderr || details.stdout}`, { code: "TN_QUALIFY_IOS_DEVICE_BLOCKED" });
|
|
1190
|
+
if (/simulator/iu.test(details.stdout)) throw new QualificationError(`TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED: ${device} identifies as a simulator.`, { code: "TN_QUALIFY_PHYSICAL_DEVICE_REQUIRED" });
|
|
1191
|
+
if (!/arm64/iu.test(details.stdout)) throw new QualificationError("iOS device details did not prove arm64 execution.", { code: "TN_QUALIFY_IOS_ARM64_REQUIRED" });
|
|
1192
|
+
if (!/Metal/iu.test(details.stdout)) throw new QualificationError("iOS device details did not report a physical Metal adapter.", { code: "TN_QUALIFY_NATIVE_GPU_REQUIRED" });
|
|
1193
|
+
const dimensions = /(?:screen|display)[^\n]*(\d+)\s*[x×]\s*(\d+)/iu.exec(details.stdout);
|
|
1194
|
+
if (dimensions === null) throw new QualificationError("iOS device details did not report a usable screen mode.", { code: "TN_QUALIFY_IOS_DEVICE_BLOCKED" });
|
|
1195
|
+
return {
|
|
1196
|
+
platform: "ios",
|
|
1197
|
+
kind: "physical",
|
|
1198
|
+
identifierHash: hashIdentifier(device),
|
|
1199
|
+
name: /name\s*[:=]\s*([^\n]+)/iu.exec(details.stdout)?.[1]?.trim() ?? "",
|
|
1200
|
+
manufacturer: "Apple",
|
|
1201
|
+
model: /model\s*[:=]\s*([^\n]+)/iu.exec(details.stdout)?.[1]?.trim() ?? "",
|
|
1202
|
+
osVersion: /OS version\s*[:=]\s*([^\n]+)/iu.exec(details.stdout)?.[1]?.trim() ?? "",
|
|
1203
|
+
osBuild: /build version\s*[:=]\s*([^\n]+)/iu.exec(details.stdout)?.[1]?.trim() ?? "",
|
|
1204
|
+
cpuAbi: "arm64",
|
|
1205
|
+
gpu: /(?:Metal[^\n]*|GPU[^\n]*)/iu.exec(details.stdout)?.[0]?.trim() ?? "physical Metal device",
|
|
1206
|
+
driver: "Apple Metal device driver",
|
|
1207
|
+
screenModes: [{ width: Number(dimensions[1]), height: Number(dimensions[2]), orientation: Number(dimensions[1]) >= Number(dimensions[2]) ? "landscape" : "portrait" }],
|
|
1208
|
+
nativeGpu: true,
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
function runIosQualification(options, preflightResult, artifact, dependencies = {}) {
|
|
1213
|
+
const locate = dependencies.findExecutable ?? findExecutable;
|
|
1214
|
+
const run = dependencies.command ?? command;
|
|
1215
|
+
const now = dependencies.now ?? Date.now;
|
|
1216
|
+
const device = inspectIosDevice(options.device, { command: run, findExecutable: locate });
|
|
1217
|
+
const installStartedAt = new Date(now()).toISOString();
|
|
1218
|
+
const lifecycleRun = runLifecycleScenario(options, { target: "ios", device: options.device, app: options.app }, { command: run, now });
|
|
1219
|
+
const collectedTelemetry = collectIosTelemetry({ path: options.iosTelemetry, durationMs: options.durationMs, cadenceMs: options.cadenceMs });
|
|
1220
|
+
const telemetryErrors = telemetryFailure(collectedTelemetry);
|
|
1221
|
+
if (telemetryErrors.length > 0) throw new QualificationError(`iOS signed-device telemetry is incomplete: ${telemetryErrors.join("; ")}`, { code: "TN_QUALIFY_TELEMETRY_INCOMPLETE", details: telemetryErrors });
|
|
1222
|
+
const pid = iosProcessPid(collectedTelemetry, lifecycleRun);
|
|
1223
|
+
const telemetry = { ...collectedTelemetry };
|
|
1224
|
+
delete telemetry.pid;
|
|
1225
|
+
delete telemetry.processPid;
|
|
1226
|
+
const artifactObservationPath = writeArtifactObservation(options, artifact);
|
|
1227
|
+
const capturePath = joinPath(options.out, "playtest/after.png");
|
|
1228
|
+
const artifactPaths = [
|
|
1229
|
+
{ ...actualArtifactRecord(lifecycleRun.reportPath, "native:qualify:physical playtest"), capture: false },
|
|
1230
|
+
{ ...actualArtifactRecord(artifactObservationPath, "native:qualify:physical artifact provenance"), capture: false },
|
|
1231
|
+
{ ...actualArtifactRecord(capturePath, "native:qualify:physical playtest screenshot"), capture: true },
|
|
1232
|
+
];
|
|
1233
|
+
const endedAt = new Date(now()).toISOString();
|
|
1234
|
+
const evidence = buildProductionEvidence({
|
|
1235
|
+
platform: "ios",
|
|
1236
|
+
source: preflightResult.source,
|
|
1237
|
+
artifact,
|
|
1238
|
+
device,
|
|
1239
|
+
signing: artifact,
|
|
1240
|
+
preflightResult,
|
|
1241
|
+
playtestRun: lifecycleRun,
|
|
1242
|
+
telemetry,
|
|
1243
|
+
pid,
|
|
1244
|
+
processLiveness: lifecycleRun.report.pass === true,
|
|
1245
|
+
timestamps: { startedAt: installStartedAt, endedAt, installStartedAt, launchStartedAt: lifecycleRun.startedAt, readyAt: lifecycleRun.startedAt, firstFrameAt: lifecycleRun.startedAt, frame300At: lifecycleRun.completedAt },
|
|
1246
|
+
artifactPaths,
|
|
1247
|
+
gateEvidence: readGateEvidence(options.gateEvidence),
|
|
1248
|
+
});
|
|
1249
|
+
const reportPath = joinPath(options.out, "physical-device-evidence.json");
|
|
1250
|
+
writeFileSync(reportPath, `${JSON.stringify(evidence, null, 2)}\n`);
|
|
1251
|
+
return resultFor("pass", "TN_QUALIFY_PHYSICAL_PASS", { report: reportPath });
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
export function qualifyPhysicalMobile(options, dependencies = {}) {
|
|
1255
|
+
const identity = classifyPhysicalDevice(options.platform, options.device);
|
|
1256
|
+
if (options.control === "reject-nonphysical") {
|
|
1257
|
+
return identity.kind === "physical-candidate"
|
|
1258
|
+
? resultFor("fail", "TN_QUALIFY_CONTROL_NOT_TRIGGERED", { errors: ["reject-nonphysical control accepted a physical-candidate selector"] })
|
|
1259
|
+
: resultFor("blocked", identity.code, { blockers: [`${identity.code}: ${options.device ?? "missing device"}`] });
|
|
1260
|
+
}
|
|
1261
|
+
if (options.control === "break-resume") return lifecycleControl(options);
|
|
1262
|
+
if (options.control === "reject-unsigned") return unsignedArtifactControl(options, dependencies);
|
|
1263
|
+
if (options.control === "missing-prerequisite") return missingPrerequisiteControl(options);
|
|
1264
|
+
if (options.control !== null) return resultFor("fail", "TN_QUALIFY_ARGUMENT", { errors: [`Unknown control ${options.control}.`] });
|
|
1265
|
+
let artifact;
|
|
1266
|
+
try {
|
|
1267
|
+
artifact = options.platform === "android"
|
|
1268
|
+
? verifyAndroidArtifact(options.app, options.candidateSha, { ...dependencies, artifactProvenance: options.artifactProvenance })
|
|
1269
|
+
: verifyIosArtifact(options.app, options.candidateSha, { ...dependencies, artifactProvenance: options.artifactProvenance });
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
return resultFromQualificationError(error);
|
|
1272
|
+
}
|
|
1273
|
+
const preflightResult = preflight(options, {
|
|
1274
|
+
source: dependencies.source,
|
|
1275
|
+
artifactSha256: artifact.artifactSha256,
|
|
1276
|
+
artifactSourceSha: artifact.sourceSha,
|
|
1277
|
+
});
|
|
1278
|
+
if (preflightResult.status !== "pass") return resultFor("blocked", preflightResult.code, { blockers: preflightResult.blockers, source: preflightResult.source });
|
|
1279
|
+
try {
|
|
1280
|
+
return options.platform === "android" ? runAndroidQualification(options, preflightResult, artifact, dependencies) : runIosQualification(options, preflightResult, artifact, dependencies);
|
|
1281
|
+
} catch (error) {
|
|
1282
|
+
return resultFromQualificationError(error);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
export function main(argv = process.argv.slice(2)) {
|
|
1287
|
+
let options;
|
|
1288
|
+
try {
|
|
1289
|
+
options = parseArgs(argv);
|
|
1290
|
+
if (options.help) {
|
|
1291
|
+
process.stdout.write(usage());
|
|
1292
|
+
return 0;
|
|
1293
|
+
}
|
|
1294
|
+
if (options.validateFixture !== null) {
|
|
1295
|
+
const result = validateFixture(options.validateFixture);
|
|
1296
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1297
|
+
return result.status === "pass" ? 0 : result.status === "fail" ? 1 : 2;
|
|
1298
|
+
}
|
|
1299
|
+
if (options.rollup !== null) {
|
|
1300
|
+
if (options.control === "missing-prerequisite") {
|
|
1301
|
+
const result = missingPrerequisiteControl(options);
|
|
1302
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1303
|
+
return result.status === "fail" ? 1 : 2;
|
|
1304
|
+
}
|
|
1305
|
+
if (options.candidateSha === null) {
|
|
1306
|
+
const result = resultFor("blocked", "TN_QUALIFY_INPUT_REQUIRED", { blockers: ["--candidate-sha is required for a physical evidence rollup"] });
|
|
1307
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1308
|
+
return 2;
|
|
1309
|
+
}
|
|
1310
|
+
const result = rollupPhysicalDeviceEvidence(options.rollup, options.candidateSha);
|
|
1311
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1312
|
+
return result.status === "pass" ? 0 : result.status === "fail" ? 1 : 2;
|
|
1313
|
+
}
|
|
1314
|
+
const result = qualifyPhysicalMobile(options);
|
|
1315
|
+
if (result.status === "blocked" || result.status === "fail") writeResult(options.out, result);
|
|
1316
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1317
|
+
return result.status === "pass" ? 0 : result.status === "fail" ? 1 : 2;
|
|
1318
|
+
} catch (error) {
|
|
1319
|
+
const result = error instanceof QualificationError
|
|
1320
|
+
? resultFor(error.status, error.code, { errors: [error.message, ...error.details] })
|
|
1321
|
+
: resultFor("fail", "TN_QUALIFY_UNEXPECTED", { errors: [error instanceof Error ? error.message : String(error)] });
|
|
1322
|
+
process.stderr.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
1323
|
+
return result.status === "fail" ? 1 : 2;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) process.exitCode = main();
|