@threenative/runtime-native 0.3.3 → 0.3.4

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.
@@ -18,7 +18,8 @@ import {
18
18
 
19
19
  const runtimeRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
20
20
  const workspaceRoot = resolve(runtimeRoot, "..", "..");
21
- const defaultScenario = joinPath(workspaceRoot, "examples/native-smoke/playtests/physical-mobile-lifecycle.playtest.json");
21
+ const defaultProject = joinPath(workspaceRoot, "examples/native-smoke");
22
+ const defaultScenario = joinPath(defaultProject, "playtests/physical-mobile-lifecycle.playtest.json");
22
23
  const commitPattern = /^[0-9a-f]{7,64}$/iu;
23
24
  const sha256Pattern = /^[0-9a-f]{64}$/u;
24
25
  const REQUIRED_PREREQUISITE_REPORT_CONTROLS = {
@@ -77,6 +78,12 @@ Required execution options:
77
78
  --candidate-sha SHA exact source SHA for the candidate
78
79
  --out PATH ignored raw output directory
79
80
 
81
+ Declared consumer subject (defaults to examples/native-smoke):
82
+ --project PATH game project root; its app.id is the identity qualified
83
+ --scenario PATH playtest scenario inside that project
84
+ --application-id ID override the project's app.id
85
+ --activity CLASS Android launch activity (default: com.threenative.runtime.MystralActivity)
86
+
80
87
  Prerequisite options:
81
88
  --prerequisite NAME=PATH repeat for prd053, prd054, prd046, and prd048
82
89
  --prd053-report PATH shorthand prerequisite report path
@@ -85,7 +92,7 @@ Prerequisite options:
85
92
  --prd048-report PATH shorthand prerequisite report path
86
93
 
87
94
  Evidence and controls:
88
- --validate-fixture PATH validate one physicalDeviceEvidenceV1 document
95
+ --validate-fixture PATH validate one physicalDeviceEvidenceV1 or V2 document
89
96
  --rollup PATH require passing Android and iOS reports below PATH
90
97
  --artifact-provenance PATH supplied artifact provenance sidecar
91
98
  --ios-telemetry PATH signed iOS collector report from the app bridge (including processPid)
@@ -140,6 +147,10 @@ export function parseArgs(argv, cwd = process.cwd()) {
140
147
  app: null,
141
148
  candidateSha: null,
142
149
  out: resolvePath(".runtime/prd056/run", cwd),
150
+ project: defaultProject,
151
+ scenario: defaultScenario,
152
+ applicationId: null,
153
+ activity: null,
143
154
  durationMs: 30_000,
144
155
  cadenceMs: 1_000,
145
156
  prerequisiteReports: {},
@@ -183,6 +194,18 @@ export function parseArgs(argv, cwd = process.cwd()) {
183
194
  } else if (arg === "--out") {
184
195
  options.out = resolvePath(requireValue(argv, index, arg), cwd);
185
196
  index += 1;
197
+ } else if (arg === "--project") {
198
+ options.project = resolvePath(requireValue(argv, index, arg), cwd);
199
+ index += 1;
200
+ } else if (arg === "--scenario") {
201
+ options.scenario = resolvePath(requireValue(argv, index, arg), cwd);
202
+ index += 1;
203
+ } else if (arg === "--application-id") {
204
+ options.applicationId = requireValue(argv, index, arg);
205
+ index += 1;
206
+ } else if (arg === "--activity") {
207
+ options.activity = requireValue(argv, index, arg);
208
+ index += 1;
186
209
  } else if (arg === "--duration-ms" || arg === "--duration") {
187
210
  options.durationMs = positiveInteger(requireValue(argv, index, arg), arg);
188
211
  index += 1;
@@ -444,24 +467,95 @@ function readPrerequisiteReports(options, { candidateSha, platform, deviceIdenti
444
467
  return { valid: errors.length === 0, errors, records };
445
468
  }
446
469
 
470
+ /**
471
+ * The application this qualification drives, and the activity it launches.
472
+ *
473
+ * A consumer's `app.id` in `threenative.config.ts` is what `package-android.mjs` writes into the
474
+ * gradle template, so the runtime's own `applicationId` only survives in a project that declares
475
+ * none. Both this orchestrator and the playtest CLI it invokes used to name a package instead of
476
+ * reading one — a package the consumer never installed, which renders a plausible scene at a
477
+ * plausible frame rate and answers a question nobody asked. Resolve the identity once, from the
478
+ * declared project, and use it for the launch, the telemetry, the runner and the device readback.
479
+ */
480
+ const DEFAULT_ANDROID_APPLICATION_ID = "com.threenative.game";
481
+ const ANDROID_LAUNCH_ACTIVITY_CLASS = "com.threenative.runtime.MystralActivity";
482
+
483
+ export function declaredApplicationId(project) {
484
+ const config = joinPath(project, "threenative.config.ts");
485
+ if (!existsSync(config)) return null;
486
+ const match = /id\s*:\s*["'`]([^"'`]+)["'`]/u.exec(readFileSync(config, "utf8"));
487
+ return match === null || match[1].includes("__") ? null : match[1];
488
+ }
489
+
490
+ function readScenarioName(scenario) {
491
+ if (!existsSync(scenario)) return null;
492
+ try {
493
+ const name = JSON.parse(readFileSync(scenario, "utf8")).name;
494
+ return typeof name === "string" && name.length > 0 ? name : null;
495
+ } catch {
496
+ return null;
497
+ }
498
+ }
499
+
500
+ export function subjectIdentity(options) {
501
+ const project = options.project ?? defaultProject;
502
+ const scenario = options.scenario ?? defaultScenario;
503
+ const configuredApplicationId = declaredApplicationId(project);
504
+ return {
505
+ project,
506
+ scenario,
507
+ configuredApplicationId,
508
+ scenarioName: readScenarioName(scenario),
509
+ applicationId: options.applicationId ?? configuredApplicationId ?? DEFAULT_ANDROID_APPLICATION_ID,
510
+ activity: options.activity ?? ANDROID_LAUNCH_ACTIVITY_CLASS,
511
+ };
512
+ }
513
+
514
+ /**
515
+ * What the declared subject must satisfy before a device is touched.
516
+ *
517
+ * The project and scenario checks are common: either platform drives a scenario out of the project
518
+ * it was handed, and a run that drove some other one answered a question nobody asked.
519
+ *
520
+ * The package-id checks are Android's, and only Android's. This orchestrator resolves an Android
521
+ * `applicationId` because that is what it launches, `pidof`s and reads `gfxinfo`/`meminfo` for. An
522
+ * iOS artifact carries a *bundle* identifier read from `codesign`, and the iOS lane launches through
523
+ * `--app` and never names a package at all, so holding a bundle id to an Android package rule would
524
+ * block a run on a field it does not read. iOS identity stays where it was: the signed artifact's own.
525
+ */
526
+ function subjectBlockers(options, subject, artifact) {
527
+ const blockers = [];
528
+ if (!existsSync(subject.project)) blockers.push(`declared project is missing at ${subject.project}`);
529
+ if (subject.scenarioName === null) blockers.push(`declared scenario is missing or names no scenario at ${subject.scenario}`);
530
+ else if (relative(subject.project, subject.scenario).startsWith("..")) blockers.push(`declared scenario ${subject.scenario} is outside the declared project ${subject.project}`);
531
+ if (options.platform !== "android") return blockers;
532
+ if (!/^[A-Za-z0-9_.-]+$/u.test(subject.applicationId)) blockers.push(`declared application id '${subject.applicationId}' is not a safe package name`);
533
+ if (options.applicationId !== null && options.applicationId !== undefined && subject.configuredApplicationId !== null && options.applicationId !== subject.configuredApplicationId) blockers.push(`--application-id ${options.applicationId} does not match the declared project's app.id ${subject.configuredApplicationId}`);
534
+ if (artifact !== undefined && artifact !== null && artifact.applicationId !== undefined && artifact.applicationId !== subject.applicationId) blockers.push(`supplied artifact applicationId ${artifact.applicationId} does not match the declared project ${subject.applicationId}`);
535
+ return blockers;
536
+ }
537
+
447
538
  export function preflight(options, {
448
539
  cwd = workspaceRoot,
449
540
  source = undefined,
450
541
  artifactSha256 = undefined,
451
542
  artifactSourceSha = undefined,
543
+ artifact = undefined,
452
544
  } = {}) {
453
545
  const blockers = [];
454
546
  const platform = options.platform;
455
547
  const identity = classifyPhysicalDevice(platform, options.device);
548
+ const subject = subjectIdentity(options);
456
549
  if (platform === null) blockers.push("--platform android|ios is required");
457
550
  if (identity.kind === "missing") blockers.push(`${platform ?? "physical"} device identifier is required`);
458
551
  if (identity.kind === "emulator" || identity.kind === "simulator") blockers.push(`${identity.code}: ${options.device} is not a physical device`);
459
552
  if (options.app === null) blockers.push(`${appFlag(platform ?? "android")} signed artifact path is required`);
460
553
  if (options.candidateSha === null) blockers.push("--candidate-sha is required");
461
554
  blockers.push(...missingPrerequisiteBlockers(options));
555
+ blockers.push(...subjectBlockers(options, subject, artifact));
462
556
  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 };
557
+ if (identity.kind === "emulator" || identity.kind === "simulator") return { status: "blocked", code: identity.code, blockers, source: null, subject };
558
+ if (blockers.length > 0 && options.candidateSha === null) return { status: "blocked", code: "TN_QUALIFY_INPUT_REQUIRED", blockers, source: null, subject };
465
559
  const resolvedSource = source ?? sourceIdentity(cwd);
466
560
  if (resolvedSource.headSha !== options.candidateSha) blockers.push(`candidate SHA mismatch: requested ${options.candidateSha}, checkout HEAD ${resolvedSource.headSha}`);
467
561
  if (resolvedSource.worktree !== "clean") blockers.push("source worktree is dirty; physical evidence requires committed HEAD");
@@ -481,6 +575,7 @@ export function preflight(options, {
481
575
  code: blockers.length === 0 ? "TN_QUALIFY_PREFLIGHT_PASS" : "TN_QUALIFY_PREFLIGHT_BLOCKED",
482
576
  blockers,
483
577
  source: resolvedSource,
578
+ subject,
484
579
  artifactSha256,
485
580
  prerequisites: prerequisiteResult.records,
486
581
  };
@@ -692,22 +787,26 @@ function installAndroid(adb, serial, app, options = {}) {
692
787
  }
693
788
 
694
789
  /**
695
- * The application this qualification drives, and the activity it launches.
790
+ * The APK that is on the device, not the one handed to `adb install`.
696
791
  *
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.
792
+ * A phone that has been used for this work carries several ThreeNative installs, and a stale
793
+ * install of the same id is worse: it launches, renders and reports telemetry without ever being
794
+ * the artifact whose signature and provenance were just verified.
702
795
  */
703
- const ANDROID_APPLICATION_ID = "com.threenative.game";
704
- const ANDROID_LAUNCH_ACTIVITY = `${ANDROID_APPLICATION_ID}/com.threenative.runtime.MystralActivity`;
796
+ function assertInstalledAndroidArtifact(adb, serial, applicationId, artifactSha256, run) {
797
+ const located = run(adb, ["-s", serial, "shell", "pm", "path", applicationId]);
798
+ const installed = located.status === 0 ? /^package:(\/\S+\.apk)$/u.exec(located.stdout.trim()) : null;
799
+ if (installed === null) throw new QualificationError(`No installed APK for '${applicationId}' on ${serial}.`, { code: "TN_QUALIFY_ANDROID_INSTALL_BLOCKED" });
800
+ const digest = run(adb, ["-s", serial, "shell", "sha256sum", installed[1]]).stdout.trim().split(/\s+/u)[0];
801
+ if (digest !== artifactSha256) throw new QualificationError(`Installed '${applicationId}' is ${digest}, not the supplied artifact ${artifactSha256}.`, { code: "TN_QUALIFY_ARTIFACT_PROVENANCE_MISMATCH" });
802
+ return installed[1];
803
+ }
705
804
 
706
- function launchAndroid(adb, serial, options = {}) {
805
+ function launchAndroid(adb, serial, subject, options = {}) {
707
806
  const run = options.command ?? command;
708
- const result = run(adb, ["-s", serial, "shell", "am", "start", "-W", "-n", ANDROID_LAUNCH_ACTIVITY], { timeout: 30_000 });
807
+ const result = run(adb, ["-s", serial, "shell", "am", "start", "-W", "-n", `${subject.applicationId}/${subject.activity}`], { timeout: 30_000 });
709
808
  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]);
809
+ const pid = run(adb, ["-s", serial, "shell", "pidof", subject.applicationId]);
711
810
  const value = Number(pid.stdout.trim().split(/\s+/u)[0]);
712
811
  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
812
  return value;
@@ -753,16 +852,17 @@ export function parsePlaytestReport(stdout) {
753
852
  return reports.at(-1) ?? null;
754
853
  }
755
854
 
756
- function runLifecycleScenario(options, { target, device, adb, app }, dependencies = {}) {
855
+ function runLifecycleScenario(options, { target, device, adb, app, subject }, dependencies = {}) {
757
856
  const cli = joinPath(workspaceRoot, "packages/playtest/dist/runner/cli.js");
758
857
  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);
858
+ const args = [cli, subject.scenario, "--target", target, "--device", device, "--project", subject.project, "--artifacts", joinPath(options.out, "playtest"), "--timeout", String(Math.max(options.durationMs, 60_000))];
859
+ if (target === "android") args.push("--adb", adb, "--package", subject.applicationId, "--activity", subject.activity);
761
860
  else args.push("--ios-transport", "device", "--app", app);
762
861
  const startedAt = new Date((dependencies.now ?? Date.now)()).toISOString();
763
862
  const result = (dependencies.command ?? command)(process.execPath, args, { cwd: workspaceRoot, timeout: Math.max(options.durationMs + 30_000, 90_000) });
764
863
  const report = parsePlaytestReport(result.stdout);
765
864
  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" });
865
+ if (report.scenario !== subject.scenarioName) throw new QualificationError(`The device ran scenario '${report.scenario}', not the declared '${subject.scenarioName}' from ${subject.scenario}.`, { code: "TN_QUALIFY_SCENARIO_MISMATCH", status: "fail" });
766
866
  const reportPath = joinPath(options.out, "playtest/report.json");
767
867
  mkdirSync(dirname(reportPath), { recursive: true });
768
868
  writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
@@ -819,6 +919,7 @@ function parseGfxinfoFrameIntervals(stdout) {
819
919
  function collectSampledAndroidValue({
820
920
  adb,
821
921
  serial,
922
+ applicationId,
822
923
  durationMs,
823
924
  cadenceMs,
824
925
  commandRunner,
@@ -836,12 +937,12 @@ function collectSampledAndroidValue({
836
937
  const delay = target - now();
837
938
  if (delay > 0) sleep(delay);
838
939
  const at = new Date(now()).toISOString();
839
- const frame = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "gfxinfo", ANDROID_APPLICATION_ID, "framestats"]);
940
+ const frame = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "gfxinfo", applicationId, "framestats"]);
840
941
  const frameIntervals = frame.status === 0 ? parseGfxinfoFrameIntervals(frame.stdout) : [];
841
942
  if (frameIntervals.length === 0) errors.frame.push(frame.stderr || `no frame intervals at ${at}`);
842
943
  else for (const value of frameIntervals) frameSamples.push({ at, value });
843
944
 
844
- const memory = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "meminfo", ANDROID_APPLICATION_ID]);
945
+ const memory = commandRunner(adb, ["-s", serial, "shell", "dumpsys", "meminfo", applicationId]);
845
946
  const memoryKb = /TOTAL\s+(\d+)/iu.exec(memory.stdout)?.[1];
846
947
  if (memory.status !== 0 || memoryKb === undefined) errors.memory.push(memory.stderr || `TOTAL row unavailable at ${at}`);
847
948
  else memorySamples.push({ at, value: Number(memoryKb) * 1024 });
@@ -857,17 +958,18 @@ function collectSampledAndroidValue({
857
958
  else batterySamples.push({ at, value: Number(batteryPercent) });
858
959
  }
859
960
  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("; ")),
961
+ frame: errors.frame.length === 0 ? availableCollector(`adb shell dumpsys gfxinfo ${applicationId} framestats`, "ms", frameSamples) : unavailableCollector(`adb shell dumpsys gfxinfo ${applicationId} framestats`, "ms", errors.frame.join("; ")),
962
+ memory: errors.memory.length === 0 ? availableCollector(`adb shell dumpsys meminfo ${applicationId}`, "bytes", memorySamples) : unavailableCollector(`adb shell dumpsys meminfo ${applicationId}`, "bytes", errors.memory.join("; ")),
862
963
  thermal: errors.thermal.length === 0 ? availableCollector("adb shell dumpsys thermalservice", "state", thermalSamples) : unavailableCollector("adb shell dumpsys thermalservice", "state", errors.thermal.join("; ")),
863
964
  battery: errors.battery.length === 0 ? availableCollector("adb shell dumpsys battery", "percent", batterySamples) : unavailableCollector("adb shell dumpsys battery", "percent", errors.battery.join("; ")),
864
965
  };
865
966
  }
866
967
 
867
- export function collectAndroidTelemetry(adb, serial, durationMs, cadenceMs, dependencies = {}) {
968
+ export function collectAndroidTelemetry(adb, serial, durationMs, cadenceMs, dependencies = {}, applicationId = DEFAULT_ANDROID_APPLICATION_ID) {
868
969
  const telemetry = collectSampledAndroidValue({
869
970
  adb,
870
971
  serial,
972
+ applicationId,
871
973
  durationMs,
872
974
  cadenceMs,
873
975
  commandRunner: dependencies.command ?? command,
@@ -950,25 +1052,108 @@ function countScenarioErrors(playtest) {
950
1052
  return errors.filter((item) => item?.severity === "error" || /GPU|WebGPU|validation/iu.test(JSON.stringify(item))).length;
951
1053
  }
952
1054
 
953
- export function evaluateLifecycleObservation(after, before = undefined) {
1055
+ /**
1056
+ * The operations this claim rests on, in the order it reads them: the app went away, came back,
1057
+ * and turned. Any phase after the rotation is a resume, so the report may carry more of them.
1058
+ */
1059
+ const LIFECYCLE_OPERATIONS = ["background", "foreground", "rotate"];
1060
+
1061
+ /** The device has to have turned, not merely been asked to. */
1062
+ function rotationErrors(phase, previous, label) {
1063
+ if (phase.windowRotation !== phase.requestedRotation) return [`${label}.windowRotation is ${String(phase.windowRotation)}, not the requested rotation ${String(phase.requestedRotation)}`];
1064
+ if (phase.windowRotation === previous?.windowRotation) return [`${label}.windowRotation is still ${String(phase.windowRotation)}, so the device never turned`];
1065
+ return [];
1066
+ }
1067
+
1068
+ /** What one phase's own reading has to carry: a time, a frame count, the session, and its focus. */
1069
+ function phaseReadingErrors(phase, previous, pid, label) {
1070
+ const errors = [];
1071
+ if (!Number.isFinite(phase.at) || phase.at < 0) errors.push(`${label}.at is missing or non-finite`);
1072
+ if (!Number.isInteger(phase.frames) || phase.frames < 0) errors.push(`${label}.frames is not a whole device frame count`);
1073
+ if (phase.pid !== pid) errors.push(`${label}.pid is ${String(phase.pid)}, not the session process ${String(pid)}`);
1074
+ if (phase.focused !== (phase.phase !== "background")) errors.push(`${label}.focused is ${String(phase.focused)}; the device should report ${String(phase.phase !== "background")} here`);
1075
+ if (Number.isFinite(phase.at) && Number.isFinite(previous?.at) && phase.at <= previous.at) errors.push(`${label}.at is ${String(phase.at)}, not after the previous phase's ${String(previous.at)}`);
1076
+ if (Number.isInteger(phase.frames) && Number.isInteger(previous?.frames) && phase.frames < previous.frames) errors.push(`${label}.frames is ${String(phase.frames)}, below the previous phase's ${String(previous.frames)}; a device frame count does not run backwards`);
1077
+ return errors;
1078
+ }
1079
+
1080
+ /** The phases themselves: one process throughout, unfocused only while away, and a real turn. */
1081
+ function lifecyclePhaseErrors(phases, pid) {
954
1082
  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");
1083
+ phases.forEach((phase, index) => {
1084
+ const operation = LIFECYCLE_OPERATIONS[index] ?? "foreground";
1085
+ const label = `observations.deviceLifecycle.phases[${index}]`;
1086
+ if (!isRecord(phase) || phase.phase !== operation) {
1087
+ errors.push(`${label} is not the ${operation} operation this claim needs`);
1088
+ return;
1089
+ }
1090
+ errors.push(...phaseReadingErrors(phase, phases[index - 1], pid, label));
1091
+ if (operation === "rotate") errors.push(...rotationErrors(phase, phases[index - 1], label));
1092
+ });
1093
+ return errors;
1094
+ }
1095
+
1096
+ /** What the phases' own counts show: nothing drawn while away, and movement again after the return. */
1097
+ function renderClaimsFromPhases(phases) {
1098
+ const [background, resumed] = [phases[0], phases.at(-1)];
1099
+ if (![background, resumed].every((phase) => isRecord(phase) && Number.isInteger(phase.frames))) return {};
1100
+ const advanced = resumed.frames > background.frames;
1101
+ return {
1102
+ advanced,
1103
+ errors: [
1104
+ ...(background.framesPaused === true ? [] : [`observations.deviceLifecycle.phases[0].framesPaused is ${String(background.framesPaused)}; the backgrounded reading itself has to show the frame counter stopping`]),
1105
+ ...(advanced ? [] : [`observations.deviceLifecycle.phases: the resumed frame count ${String(resumed.frames)} did not advance past the backgrounded ${String(background.frames)}`]),
1106
+ ],
1107
+ paused: background.framesPaused,
1108
+ };
1109
+ }
1110
+
1111
+ /** The summary the phases must agree with: the surface stopped while away, and both counters moved after. */
1112
+ function lifecycleContinuityErrors(observation, phases) {
1113
+ const { errors: renderErrors, paused, advanced } = renderClaimsFromPhases(phases);
1114
+ const errors = [...renderErrors];
1115
+ const render = isRecord(observation.render) ? observation.render : undefined;
1116
+ if (render === undefined) errors.push("observations.deviceLifecycle.render is missing");
958
1117
  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
- });
1118
+ if (render.framesPaused !== true) errors.push("observations.deviceLifecycle.render.framesPaused is not true; the device's frame counter did not stop while the app was unfocused");
1119
+ if (render.framesAdvanced !== true) errors.push("observations.deviceLifecycle.render.framesAdvanced is not true");
1120
+ if (paused !== undefined && render.framesPaused !== paused) errors.push(`observations.deviceLifecycle.render.framesPaused is ${String(render.framesPaused)}, but phases[0].framesPaused is ${String(paused)}`);
1121
+ if (advanced !== undefined && render.framesAdvanced !== advanced) errors.push(`observations.deviceLifecycle.render.framesAdvanced is ${String(render.framesAdvanced)}, but the phases' own counts ${advanced ? "advance" : "do not advance"} past the backgrounded frame count`);
1122
+ }
1123
+ const physics = observation.physics;
1124
+ const label = "observations.deviceLifecycle.physics";
1125
+ if (!isRecord(physics)) return [...errors, `${label} is missing`];
1126
+ if (physics.available !== true) return [...errors, `${label} is unavailable: ${String(physics.reason ?? "it reported no reason")}`];
1127
+ const steps = isRecord(physics.steps) ? physics.steps : {};
1128
+ const [before, back, afterAdvance] = [steps.beforeBackground, steps.afterForeground, steps.afterAdvance];
1129
+ if (![before, back, afterAdvance].every((value) => Number.isInteger(value) && value >= 0)) errors.push(`${label}.steps must carry three whole counts (beforeBackground, afterForeground, afterAdvance)`);
1130
+ else {
1131
+ if (back !== before) errors.push(`${label}: the simulation stepped from ${String(before)} to ${String(back)} while the app was away`);
1132
+ if (afterAdvance <= back) errors.push(`${label}: the simulation did not advance after the resume (${String(back)} to ${String(afterAdvance)})`);
1133
+ if (physics.stepsPaused !== (back === before)) errors.push(`${label}.stepsPaused is ${String(physics.stepsPaused)}, but the step counts around the away period are ${String(before)} and ${String(back)}`);
1134
+ if (physics.stepsAdvanced !== (afterAdvance > back)) errors.push(`${label}.stepsAdvanced is ${String(physics.stepsAdvanced)}, but the step counts after the return are ${String(back)} and ${String(afterAdvance)}`);
962
1135
  }
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");
1136
+ if (physics.stepsPaused !== true) errors.push(`${label}.stepsPaused is not true`);
1137
+ if (physics.stepsAdvanced !== true) errors.push(`${label}.stepsAdvanced is not true`);
1138
+ return errors;
1139
+ }
1140
+
1141
+ /**
1142
+ * Certify the lifecycle from the runner's own device observation, never from the game's.
1143
+ *
1144
+ * Every value here was read off the phone, so a `GameState` resource — the game's own account of
1145
+ * whether it went away and came back — certifies nothing and is not read. The summary booleans the
1146
+ * producer reported are re-derived from the phases' own counts, and may not contradict them.
1147
+ */
1148
+ export function evaluateLifecycleObservation(observation) {
1149
+ if (!isRecord(observation)) return { valid: false, errors: ["observations.deviceLifecycle is missing; the run reported no device-observed lifecycle"] };
1150
+ const errors = [];
1151
+ const phases = Array.isArray(observation.phases) ? observation.phases : [];
1152
+ if (!Array.isArray(observation.phases)) errors.push("observations.deviceLifecycle.phases is missing");
1153
+ const pid = isRecord(observation.session) ? observation.session.pid : undefined;
1154
+ if (!Number.isInteger(pid) || pid <= 0) errors.push("observations.deviceLifecycle.session.pid is missing or is not a live process id");
1155
+ if (phases.length < LIFECYCLE_OPERATIONS.length) errors.push(`observations.deviceLifecycle.phases reported ${phases.length} operations; this claim needs at least ${LIFECYCLE_OPERATIONS.join(", then ")}`);
1156
+ errors.push(...lifecyclePhaseErrors(phases, pid), ...lifecycleContinuityErrors(observation, phases));
972
1157
  return { valid: errors.length === 0, errors };
973
1158
  }
974
1159
 
@@ -983,6 +1168,41 @@ function actualArtifactRecord(path, producerCommand, retention = "ignored-raw")
983
1168
  };
984
1169
  }
985
1170
 
1171
+ /**
1172
+ * The v2 evidence document's lifecycle block: exactly what the device reported, in the order it
1173
+ * read it.
1174
+ *
1175
+ * Each row is one operation the phone observed, timed as an offset from the run's own clock, and
1176
+ * carries that reading's own frame count, focus, pid and — on the rotation — the window state the
1177
+ * turn produced. The three step counts bracket the away period rather than being attributed to a
1178
+ * phase, because none of them was read during one. So the v1 booleans (`sameSession`,
1179
+ * `surfaceValidAfterResume`, `stateContinuity`, `backgroundGapIntegrated`, and `physicsStepDelta`,
1180
+ * which is a count, not a delta) have no measured field behind them and are not restated: the v2
1181
+ * validator re-derives each claim from these numbers and refuses a document that denies them.
1182
+ */
1183
+ function observedLifecycle(observation) {
1184
+ return {
1185
+ clock: "run-relative-ms",
1186
+ operations: observation.phases.map((phase) => ({
1187
+ operation: phase.phase,
1188
+ offsetMs: phase.at,
1189
+ frames: phase.frames,
1190
+ focused: phase.focused,
1191
+ pid: phase.pid,
1192
+ ...(phase.framesPaused === undefined ? {} : { framesPaused: phase.framesPaused }),
1193
+ ...(phase.windowRotation === undefined ? {} : { windowRotation: phase.windowRotation }),
1194
+ ...(phase.requestedRotation === undefined ? {} : { requestedRotation: phase.requestedRotation }),
1195
+ })),
1196
+ framesPaused: observation.render.framesPaused,
1197
+ framesAdvanced: observation.render.framesAdvanced,
1198
+ physics: {
1199
+ steps: { ...observation.physics.steps },
1200
+ stepsPaused: observation.physics.stepsPaused,
1201
+ stepsAdvanced: observation.physics.stepsAdvanced,
1202
+ },
1203
+ };
1204
+ }
1205
+
986
1206
  export function buildProductionEvidence({
987
1207
  platform,
988
1208
  source,
@@ -999,13 +1219,16 @@ export function buildProductionEvidence({
999
1219
  gateEvidence,
1000
1220
  }) {
1001
1221
  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);
1222
+ // A game-authored `observations.resources.GameState` restates the scenario's own account of
1223
+ // itself, so it is not read: phases, focus, rotation and frames all came off the device.
1224
+ const observation = playtest?.observations?.deviceLifecycle;
1225
+ const lifecycle = evaluateLifecycleObservation(observation);
1005
1226
  if (!lifecycle.valid) throw new QualificationError(lifecycle.errors.join("; "), { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
1227
+ const frames = observation.phases.at(-1).frames;
1006
1228
  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" });
1229
+ if (frames < 300) throw new QualificationError(`Physical lifecycle scenario did not observe 300 frames; the device counted ${frames}.`, { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
1008
1230
  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" });
1231
+ if (observation.session.pid !== pid) throw new QualificationError(`The device reported process ${observation.session.pid} across the lifecycle, not the launched process ${pid}.`, { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
1009
1232
  if (processLiveness !== true) throw new QualificationError("Physical lifecycle scenario did not observe a live app process.", { code: "TN_QUALIFY_LIFECYCLE_CONTINUITY", status: "fail" });
1010
1233
  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
1234
  if (!isRecord(device) || device.nativeGpu !== true) throw new QualificationError("Physical device observation did not prove a native GPU.", { code: "TN_QUALIFY_NATIVE_GPU_REQUIRED" });
@@ -1015,7 +1238,7 @@ export function buildProductionEvidence({
1015
1238
  const { nativeGpu, ...publicDevice } = device;
1016
1239
  const candidateSha = source.headSha;
1017
1240
  const evidence = {
1018
- schemaVersion: 1,
1241
+ schemaVersion: 2,
1019
1242
  identity: {
1020
1243
  schemaVersion: 1,
1021
1244
  runId: `prd056-${platform}-${timestamps.startedAt}`,
@@ -1052,12 +1275,13 @@ export function buildProductionEvidence({
1052
1275
  execution: {
1053
1276
  installStartedAt: timestamps.installStartedAt,
1054
1277
  launchStartedAt: timestamps.launchStartedAt,
1278
+ // The scenario's own start and end are not a ready time, a first frame or a 300th frame, so
1279
+ // the run reports them as unmeasured rather than copying its own clock into all three.
1280
+ readyAt: null,
1281
+ firstFrameAt: null,
1282
+ frame300At: null,
1055
1283
  pid,
1056
- sessionNonce: after.sessionNonce,
1057
- readyAt: timestamps.readyAt,
1058
- firstFrameAt: timestamps.firstFrameAt,
1059
- frame300At: timestamps.frame300At,
1060
- frames: after.frames,
1284
+ frames,
1061
1285
  nonBlankCaptureSha256: artifactPaths.find((item) => item.capture === true)?.sha256 ?? "",
1062
1286
  gpuErrorCount: countScenarioErrors(playtest),
1063
1287
  arm64: /^(?:arm64-v8a|arm64|aarch64)$/iu.test(publicDevice.cpuAbi),
@@ -1065,17 +1289,7 @@ export function buildProductionEvidence({
1065
1289
  processLiveness,
1066
1290
  assertionCount: playtest.assertionResults.length,
1067
1291
  },
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
- },
1292
+ lifecycle: observedLifecycle(observation),
1079
1293
  consumption: productionConsumption(preflightResult, candidateSha),
1080
1294
  telemetry,
1081
1295
  artifacts: artifactPaths.map(({ capture: _capture, ...record }) => record),
@@ -1122,13 +1336,15 @@ function runAndroidQualification(options, preflightResult, artifact, dependencie
1122
1336
  if (adb === null) throw new QualificationError("adb is unavailable; physical Android qualification is blocked.", { code: "TN_QUALIFY_TOOL_REQUIRED" });
1123
1337
  const run = dependencies.command ?? command;
1124
1338
  const now = dependencies.now ?? Date.now;
1339
+ const subject = preflightResult.subject;
1125
1340
  const device = inspectAndroidDevice(adb, options.device, { command: run });
1126
1341
  const installStartedAt = new Date(now()).toISOString();
1127
1342
  installAndroid(adb, options.device, options.app, { command: run });
1343
+ assertInstalledAndroidArtifact(adb, options.device, subject.applicationId, artifact.artifactSha256, run);
1128
1344
  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 });
1345
+ const pid = launchAndroid(adb, options.device, subject, { command: run });
1346
+ const lifecycleRun = runLifecycleScenario(options, { target: "android", device: options.device, adb, app: options.app, subject }, { command: run, now });
1347
+ const telemetry = collectAndroidTelemetry(adb, options.device, options.durationMs, options.cadenceMs, { command: run, now, sleep: dependencies.sleep }, subject.applicationId);
1132
1348
  const telemetryErrors = telemetryFailure(telemetry);
1133
1349
  if (telemetryErrors.length > 0) throw new QualificationError(`Android telemetry is incomplete: ${telemetryErrors.join("; ")}`, { code: "TN_QUALIFY_TELEMETRY_INCOMPLETE", details: telemetryErrors });
1134
1350
  const artifactObservationPath = writeArtifactObservation(options, artifact);
@@ -1150,13 +1366,13 @@ function runAndroidQualification(options, preflightResult, artifact, dependencie
1150
1366
  telemetry,
1151
1367
  pid,
1152
1368
  processLiveness: lifecycleRun.report.pass === true,
1153
- timestamps: { startedAt: installStartedAt, endedAt, installStartedAt, launchStartedAt, readyAt: lifecycleRun.startedAt, firstFrameAt: lifecycleRun.startedAt, frame300At: lifecycleRun.completedAt },
1369
+ timestamps: { startedAt: installStartedAt, endedAt, installStartedAt, launchStartedAt },
1154
1370
  artifactPaths,
1155
1371
  gateEvidence: readGateEvidence(options.gateEvidence),
1156
1372
  });
1157
1373
  const reportPath = joinPath(options.out, "physical-device-evidence.json");
1158
1374
  writeFileSync(reportPath, `${JSON.stringify(evidence, null, 2)}\n`);
1159
- return resultFor("pass", "TN_QUALIFY_PHYSICAL_PASS", { report: reportPath });
1375
+ return resultFor("pass", "TN_QUALIFY_PHYSICAL_PASS", { report: reportPath, subject });
1160
1376
  }
1161
1377
 
1162
1378
  function verifyIosArtifact(path, candidateSha, options = {}) {
@@ -1215,7 +1431,7 @@ function runIosQualification(options, preflightResult, artifact, dependencies =
1215
1431
  const now = dependencies.now ?? Date.now;
1216
1432
  const device = inspectIosDevice(options.device, { command: run, findExecutable: locate });
1217
1433
  const installStartedAt = new Date(now()).toISOString();
1218
- const lifecycleRun = runLifecycleScenario(options, { target: "ios", device: options.device, app: options.app }, { command: run, now });
1434
+ const lifecycleRun = runLifecycleScenario(options, { target: "ios", device: options.device, app: options.app, subject: preflightResult.subject }, { command: run, now });
1219
1435
  const collectedTelemetry = collectIosTelemetry({ path: options.iosTelemetry, durationMs: options.durationMs, cadenceMs: options.cadenceMs });
1220
1436
  const telemetryErrors = telemetryFailure(collectedTelemetry);
1221
1437
  if (telemetryErrors.length > 0) throw new QualificationError(`iOS signed-device telemetry is incomplete: ${telemetryErrors.join("; ")}`, { code: "TN_QUALIFY_TELEMETRY_INCOMPLETE", details: telemetryErrors });
@@ -1242,13 +1458,13 @@ function runIosQualification(options, preflightResult, artifact, dependencies =
1242
1458
  telemetry,
1243
1459
  pid,
1244
1460
  processLiveness: lifecycleRun.report.pass === true,
1245
- timestamps: { startedAt: installStartedAt, endedAt, installStartedAt, launchStartedAt: lifecycleRun.startedAt, readyAt: lifecycleRun.startedAt, firstFrameAt: lifecycleRun.startedAt, frame300At: lifecycleRun.completedAt },
1461
+ timestamps: { startedAt: installStartedAt, endedAt, installStartedAt, launchStartedAt: lifecycleRun.startedAt },
1246
1462
  artifactPaths,
1247
1463
  gateEvidence: readGateEvidence(options.gateEvidence),
1248
1464
  });
1249
1465
  const reportPath = joinPath(options.out, "physical-device-evidence.json");
1250
1466
  writeFileSync(reportPath, `${JSON.stringify(evidence, null, 2)}\n`);
1251
- return resultFor("pass", "TN_QUALIFY_PHYSICAL_PASS", { report: reportPath });
1467
+ return resultFor("pass", "TN_QUALIFY_PHYSICAL_PASS", { report: reportPath, subject: preflightResult.subject });
1252
1468
  }
1253
1469
 
1254
1470
  export function qualifyPhysicalMobile(options, dependencies = {}) {
@@ -1274,6 +1490,7 @@ export function qualifyPhysicalMobile(options, dependencies = {}) {
1274
1490
  source: dependencies.source,
1275
1491
  artifactSha256: artifact.artifactSha256,
1276
1492
  artifactSourceSha: artifact.sourceSha,
1493
+ artifact,
1277
1494
  });
1278
1495
  if (preflightResult.status !== "pass") return resultFor("blocked", preflightResult.code, { blockers: preflightResult.blockers, source: preflightResult.source });
1279
1496
  try {
@@ -1312,7 +1529,7 @@ export function main(argv = process.argv.slice(2)) {
1312
1529
  return result.status === "pass" ? 0 : result.status === "fail" ? 1 : 2;
1313
1530
  }
1314
1531
  const result = qualifyPhysicalMobile(options);
1315
- if (result.status === "blocked" || result.status === "fail") writeResult(options.out, result);
1532
+ writeResult(options.out, result);
1316
1533
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
1317
1534
  return result.status === "pass" ? 0 : result.status === "fail" ? 1 : 2;
1318
1535
  } catch (error) {