create-cmp-cli 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +6 -2
  2. package/packages/harness/package.json +38 -0
  3. package/packages/harness/src/approve.mjs +247 -0
  4. package/packages/harness/src/arch-doc.mjs +69 -0
  5. package/packages/harness/src/comment.mjs +76 -0
  6. package/packages/harness/src/lib/a11y.mjs +113 -0
  7. package/packages/harness/src/lib/affected-tests.mjs +147 -0
  8. package/packages/harness/src/lib/approvals.mjs +1403 -0
  9. package/packages/harness/src/lib/arch-doc.mjs +451 -0
  10. package/packages/harness/src/lib/audit-cadence.mjs +290 -0
  11. package/packages/harness/src/lib/comments.mjs +252 -0
  12. package/packages/harness/src/lib/component-stories.mjs +183 -0
  13. package/packages/harness/src/lib/determinism.mjs +179 -0
  14. package/packages/harness/src/lib/device-lease.mjs +249 -0
  15. package/packages/harness/src/lib/evidence-badge.mjs +158 -0
  16. package/packages/harness/src/lib/evidence-level.mjs +117 -0
  17. package/packages/harness/src/lib/feature-brief.mjs +324 -0
  18. package/packages/harness/src/lib/flight-recorder.mjs +332 -0
  19. package/packages/harness/src/lib/harness-lock.mjs +147 -0
  20. package/packages/harness/src/lib/harness-region.mjs +159 -0
  21. package/packages/harness/src/lib/inputs-hash.mjs +194 -0
  22. package/packages/harness/src/lib/reachability.mjs +211 -0
  23. package/packages/harness/src/lib/receipt-validate.mjs +234 -0
  24. package/packages/harness/src/lib/render.mjs +254 -0
  25. package/packages/harness/src/lib/spec-coverage.mjs +131 -0
  26. package/packages/harness/src/lib/step-cache.mjs +221 -0
  27. package/packages/harness/src/lib/token-drift.mjs +94 -0
  28. package/packages/harness/src/lib/tree.mjs +108 -0
  29. package/packages/harness/src/preview-gallery.mjs +122 -0
  30. package/packages/harness/src/receipt-check.mjs +96 -0
  31. package/packages/harness/src/record-audit.mjs +83 -0
  32. package/packages/harness/src/refusal-demo.mjs +498 -0
  33. package/packages/harness/src/retrospective.mjs +51 -0
  34. package/packages/harness/src/scaffold-feature.mjs +723 -0
  35. package/packages/harness/src/setup-hooks.mjs +33 -0
  36. package/packages/harness/src/verify.mjs +1709 -0
  37. package/packages/harness/src/walkthrough.mjs +499 -0
  38. package/packages/harness/src/watch.mjs +622 -0
  39. package/packages/receipts/package.json +36 -0
  40. package/packages/receipts/src/index.mjs +16 -0
  41. package/packages/receipts/src/inputs-hash.mjs +194 -0
  42. package/packages/receipts/src/receipt-validate.mjs +234 -0
  43. package/src/commands/upgrade.mjs +96 -0
  44. package/src/lib/harness-upgrade.mjs +159 -2
  45. package/src/scaffold.mjs +60 -1
  46. package/template/AGENTS.md +5 -0
  47. package/template/CLAUDE.md +30 -0
  48. package/template/gitignore +8 -0
  49. package/template/qa/lib/harness-lock.mjs +147 -0
  50. package/template/qa/lib/harness-region.mjs +159 -0
  51. package/template/qa/lib/inputs-hash.mjs +1 -1
  52. package/template/qa/lib/receipt-validate.mjs +1 -1
  53. package/template/qa/preview-gallery.mjs +17 -2
  54. package/template/qa/verify.mjs +95 -1
@@ -0,0 +1,1709 @@
1
+ #!/usr/bin/env node
2
+ // The verify lane — this project's single verification gate.
3
+ //
4
+ // node qa/verify.mjs [--profile scaffold|local|ci|release] [--fast] [--json]
5
+ //
6
+ // Runs every verification step this project carries, aggregates a typed
7
+ // PASS/FAIL verdict, and writes the evidence receipt to qa/evidence/latest.json.
8
+ // `--fast` is the INNER LOOP: the resolved profile minus the device/release
9
+ // tier, with unchanged pure-Node steps reused from the step cache (CACHED)
10
+ // and unit tests scoped to the working-tree change — its receipt records
11
+ // mode "fast" and can never satisfy the done-gate.
12
+ // The receipt is COMMITTED with your change (see CLAUDE.md — a change is not
13
+ // done without it). Binary artifacts under qa-artifacts/ are never committed;
14
+ // the receipt references them by path + sha256.
15
+ //
16
+ // Verdicts per step: PASS | FAIL | SKIP. The lane verdict is PASS iff no step
17
+ // FAILed. SKIPs are recorded with reasons — green-with-gaps is visible, never
18
+ // silent. Exit code: 0 = PASS, 1 = FAIL.
19
+ //
20
+ // Profiles:
21
+ // scaffold — spec coverage + build + unit tests (what `create-cmp --verify` proves at stamp time)
22
+ // local — everything; device-dependent steps SKIP when no device is attached
23
+ // ci — everything; SKIPs are recorded so the pipeline stays honest
24
+ // release — everything ci proves PLUS the release-APK smoke (releaseSmoke): the
25
+ // ship-time profile, run before cutting a release, never per-change
26
+
27
+ import { execSync, spawnSync } from "node:child_process";
28
+ import { createHash } from "node:crypto";
29
+ import fs from "node:fs";
30
+ import path from "node:path";
31
+ import { fileURLToPath } from "node:url";
32
+
33
+ import { computeInputsHash } from "./lib/inputs-hash.mjs";
34
+ import { compareTokenDrift } from "./lib/token-drift.mjs";
35
+ import { evaluateApprovalsGate } from "./lib/approvals.mjs";
36
+ import { clauseTierCoverage, scanCitations, scanSpecClauses, walkFiles } from "./lib/spec-coverage.mjs";
37
+ import { evaluateComponentStoryParity } from "./lib/component-stories.mjs";
38
+ import { evaluateReachability } from "./lib/reachability.mjs";
39
+ import { evidenceLevel } from "./lib/evidence-level.mjs";
40
+ import { updateReadmeBadge, README_REL_PATH } from "./lib/evidence-badge.mjs";
41
+ import { memoizeStep } from "./lib/step-cache.mjs";
42
+ import { changedWorkingTreePaths, deriveAffectedFilter } from "./lib/affected-tests.mjs";
43
+ import { acquireDeviceLease, releaseDeviceLease, formatHolder } from "./lib/device-lease.mjs";
44
+ import { ARCH_DOC_REL_PATH, SECTION_IDS, regenerateArchDoc } from "./lib/arch-doc.mjs";
45
+ import { DETERMINISM_TIMEZONES, compareOutcomes, parseJUnitOutcomes } from "./lib/determinism.mjs";
46
+ import { evaluateAuditCadence } from "./lib/audit-cadence.mjs";
47
+ import { appendFlightRecord, buildFlightEntry } from "./lib/flight-recorder.mjs";
48
+ import { checkHarnessIntegrity, describeIntegrity, LOCK_PATH } from "./lib/harness-lock.mjs";
49
+
50
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
51
+ const EVIDENCE_DIR = path.join(ROOT, "qa", "evidence");
52
+ const ARTIFACTS_DIR = path.join(ROOT, "qa-artifacts");
53
+
54
+ // ── Argument parsing — strict, and first thing this file does ──────────────
55
+ // An unrecognized flag used to fall through silently and start the full
56
+ // multi-minute lane (`--help` ran the whole lane for ~2 minutes before being
57
+ // killed). Same refusal-over-fabrication stance as qa/approve.mjs, which
58
+ // refuses an unknown artifact by name rather than guessing: an unknown
59
+ // argument here is refused by name, not swallowed into "run everything".
60
+ const USAGE = `node qa/verify.mjs [--profile scaffold|local|ci|release] [--fast] [--json] [--help]
61
+
62
+ The verify lane — this project's single verification gate. Runs every
63
+ verification step this project carries, aggregates a typed PASS/FAIL
64
+ verdict, and writes the evidence receipt to qa/evidence/latest.json (commit
65
+ it with your change — see CLAUDE.md). Exit code: 0 = PASS, 1 = FAIL.
66
+
67
+ Flags:
68
+ --profile <scaffold|local|ci|release>
69
+ which step set to run (default: local)
70
+ --fast INNER LOOP ONLY — run the resolved profile
71
+ minus the device/release tier (releaseBuild,
72
+ tokenDrift, e2eSmoke, androidChecks,
73
+ releaseSmoke), unconditionally, device
74
+ attached or not. Also reuses the pure-Node
75
+ steps' last PASS when their inputs are
76
+ unchanged (verdict CACHED), lets Gradle's
77
+ up-to-date checks stand (no --rerun), and
78
+ scopes unit tests to the working-tree change
79
+ (broad-impact changes run everything). The
80
+ receipt records mode "fast", derives no
81
+ evidence rung, and can NEVER satisfy the
82
+ done-gate — run the full lane once before
83
+ you call it done
84
+ --determinism run the timezone determinism probe: the JVM
85
+ test tier (unit + golden + the other
86
+ desktop suites) executes TWICE, under
87
+ TZ=Etc/GMT+12 (UTC-12) and TZ=Etc/GMT-14
88
+ (UTC+14), and the probe FAILs naming every
89
+ test whose verdict or failure output
90
+ differs — a nondeterminism leak ARCH-13's
91
+ static net missed. Bare (no --profile) it
92
+ runs JUST the probe and writes no receipt;
93
+ with --profile ci (or release) it runs
94
+ inside the lane and lands on the receipt.
95
+ Never combinable with --fast
96
+ --json print the receipt as JSON instead of the
97
+ human-readable step-by-step log
98
+ --help, -h print this usage and exit 0 without
99
+ running anything
100
+
101
+ Profiles:
102
+ scaffold spec coverage + build + unit tests (what \`create-cmp --verify\`
103
+ proves at stamp time)
104
+ local everything; device-dependent steps SKIP when no device is
105
+ attached
106
+ ci everything; SKIPs are recorded so the pipeline stays honest
107
+ release everything ci proves PLUS the release-APK smoke (releaseSmoke) —
108
+ the ship-time profile; run it before cutting a release, never
109
+ per-change
110
+ `;
111
+
112
+ const rawArgs = process.argv.slice(2);
113
+
114
+ if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
115
+ console.log(USAGE);
116
+ process.exit(0);
117
+ }
118
+
119
+ const RECOGNIZED_FLAGS = new Set(["--profile", "--json", "--fast", "--determinism"]);
120
+ for (let i = 0; i < rawArgs.length; i += 1) {
121
+ const arg = rawArgs[i];
122
+ if (arg === "--profile") {
123
+ i += 1; // consume its value (missing/invalid value keeps the existing exit-2 behavior below)
124
+ continue;
125
+ }
126
+ if (RECOGNIZED_FLAGS.has(arg)) continue;
127
+ console.error(`unknown argument "${arg}" — run node qa/verify.mjs --help`);
128
+ process.exit(2);
129
+ }
130
+
131
+ const args = rawArgs;
132
+ const profile = args.includes("--profile") ? args[args.indexOf("--profile") + 1] : "local";
133
+ const asJson = args.includes("--json");
134
+ const fast = args.includes("--fast");
135
+ // --no-journal suppresses the flight-recorder append (qa/watch.mjs passes it).
136
+ // See the append site below for why the inner loop must not write here.
137
+ const noJournal = args.includes("--no-journal");
138
+ const mode = fast ? "fast" : "full";
139
+
140
+ // ── --determinism: the timezone double-run probe (roadmap §10 item 8) ───────
141
+ // Refusals up front, by name (same stance as unknown arguments above):
142
+ // - never with --fast: the probe deliberately runs the JVM test tier twice,
143
+ // and --fast is the inner loop that exists to not pay such costs — the
144
+ // combination is a contradiction, so it is refused rather than silently
145
+ // resolved either way.
146
+ // - only the ci profile (and release, which inherits ci) carries the probe's
147
+ // lane row; asking for it in local/scaffold is refused with the two ways
148
+ // that DO work, instead of silently running a step the requested profile
149
+ // does not own.
150
+ const determinism = args.includes("--determinism");
151
+ const profileExplicit = args.includes("--profile");
152
+ if (determinism && fast) {
153
+ console.error(
154
+ "--determinism cannot be combined with --fast: the probe runs the JVM test tier twice by design, and --fast is the inner loop. Run it alone (node qa/verify.mjs --determinism) or inside a full ci/release lane (--profile ci --determinism).",
155
+ );
156
+ process.exit(2);
157
+ }
158
+ if (determinism && profileExplicit && profile !== "ci" && profile !== "release") {
159
+ console.error(
160
+ `--determinism belongs to the ci profile (release inherits it), not "${profile}" — run --profile ci --determinism, or bare --determinism to run the probe alone.`,
161
+ );
162
+ process.exit(2);
163
+ }
164
+
165
+ const GRADLEW = process.platform === "win32" ? "gradlew.bat" : "./gradlew";
166
+
167
+ // ── `--rerun` is scoped to FULL mode ────────────────────────────────────────
168
+ // `--rerun` exists for evidence integrity (see stepUnitTests's comment): it
169
+ // stops Gradle's build cache replaying a PASS recorded against a different
170
+ // tree into a receipt that claims tests executed. That mechanism belongs to
171
+ // the runs that produce integrity-bearing artifacts — and a --fast run does
172
+ // not: its receipt already declares itself non-evidence (mode "fast", no
173
+ // evidence rung, refused by qa/receipt-check.mjs), so forcing execution there
174
+ // paid an integrity tax to protect an artifact with nothing to protect. Fast
175
+ // mode therefore omits the flag and lets Gradle's up-to-date/cache machinery
176
+ // do its job; full mode keeps it, byte-identical to before.
177
+ const RERUN = fast ? "" : " --rerun";
178
+
179
+ function sh(cmd, opts = {}) {
180
+ const started = Date.now();
181
+ // maxBuffer: first-run Gradle output easily exceeds spawnSync's 1MB default,
182
+ // which would surface as a bogus FAIL (status null / ENOBUFS).
183
+ const res = spawnSync(cmd, { shell: true, cwd: ROOT, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...opts });
184
+ const ok = res.status === 0 && !res.error;
185
+ return { ok, status: res.status, error: res.error?.message, out: `${res.stdout ?? ""}${res.stderr ?? ""}`, durationMs: Date.now() - started };
186
+ }
187
+
188
+ // ── Preview-daemon coexistence ──────────────────────────────────────────────
189
+ // The preview daemon (the eyes) and this lane both spawn Gradle against this
190
+ // project and share composeApp/build/kspCaches, whose KSP incremental storage
191
+ // is single-owner — two concurrent builds throw "Storage for [...] is already
192
+ // registered" and one side dies. Three defenses, all automatic:
193
+ // 1. COORDINATE (this lane -> the daemon): this lane stamps a marker file
194
+ // for its duration; the preview service defers renders while it exists
195
+ // (mtime-bounded, so a crashed lane never wedges the eyes for long).
196
+ // 2. COORDINATE (the daemon -> this lane), the symmetric half: the daemon
197
+ // stamps its OWN marker for the duration of a render's Gradle build;
198
+ // shGradle waits for it to clear (or go stale) before launching this
199
+ // lane's own Gradle command — same mtime-bounded shape, so a crashed
200
+ // daemon never wedges the lane for long either.
201
+ // 3. SELF-HEAL: a Gradle step that still hits the collision clears kspCaches
202
+ // and retries once — the manual recovery that always worked, automated.
203
+ const LANE_MARKER = path.join(ROOT, "composeApp", "build", ".cmp-lane-in-progress");
204
+ const KSP_COLLISION_RE = /Storage for \[[^\]]*\] is already registered/;
205
+
206
+ // Degraded-path activations observed during this run — self-heals and
207
+ // fallbacks that kept the lane moving without failing it. Collected for the
208
+ // flight recorder (qa/lib/flight-recorder.mjs): a degradation that fires
209
+ // once is a shrug, one that fires every run for a month is the tooling
210
+ // quietly rotting under a green lane — and only a journal can tell those
211
+ // two apart.
212
+ const DEGRADED_PATHS = [];
213
+
214
+ // The daemon's half of defense 2 above — pid + ISO timestamp, mirroring
215
+ // LANE_MARKER's own content shape (see where LANE_MARKER is stamped, below).
216
+ const RENDER_MARKER = path.join(ROOT, "composeApp", "build", ".cmp-render-in-progress");
217
+ const RENDER_MARKER_FRESH_MS = 5 * 60 * 1000; // older than this = a crashed daemon's stale marker, ignore it
218
+ const RENDER_WAIT_TIMEOUT_MS = 3 * 60 * 1000; // give up waiting after this long regardless
219
+ const RENDER_WAIT_POLL_MS = 2000;
220
+
221
+ /**
222
+ * Defer this lane's next Gradle command while the preview daemon's render
223
+ * marker is present AND fresh (mtime younger than RENDER_MARKER_FRESH_MS).
224
+ * Polls every RENDER_WAIT_POLL_MS; gives up and proceeds anyway after
225
+ * RENDER_WAIT_TIMEOUT_MS, or the moment the marker disappears or goes stale —
226
+ * whichever comes first. A missing/unreadable marker returns immediately:
227
+ * this is a coexistence courtesy, never a hard dependency on the daemon.
228
+ */
229
+ function waitForRenderMarker() {
230
+ const deadline = Date.now() + RENDER_WAIT_TIMEOUT_MS;
231
+ for (;;) {
232
+ let stat;
233
+ try {
234
+ stat = fs.statSync(RENDER_MARKER);
235
+ } catch {
236
+ return; // no render in flight
237
+ }
238
+ if (Date.now() - stat.mtimeMs >= RENDER_MARKER_FRESH_MS) return; // gone stale
239
+ if (Date.now() >= deadline) return; // waited long enough — proceed regardless
240
+ sh(`sleep ${RENDER_WAIT_POLL_MS / 1000}`);
241
+ }
242
+ }
243
+
244
+ function shGradle(cmd, opts = {}) {
245
+ waitForRenderMarker();
246
+ const first = sh(cmd, opts);
247
+ if (first.ok || !KSP_COLLISION_RE.test(first.out)) return first;
248
+ console.error("· KSP cache collision (concurrent Gradle — the preview daemon?) — clearing kspCaches, retrying once");
249
+ fs.rmSync(path.join(ROOT, "composeApp", "build", "kspCaches"), { recursive: true, force: true });
250
+ const retry = sh(cmd, opts);
251
+ retry.durationMs += first.durationMs;
252
+ retry.selfHealed = "ksp-cache-collision";
253
+ DEGRADED_PATHS.push("ksp-cache-collision: cleared kspCaches and retried the Gradle step");
254
+ return retry;
255
+ }
256
+
257
+ function tryGit(cmd) {
258
+ try {
259
+ return execSync(`git ${cmd}`, { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
260
+ } catch {
261
+ return null;
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Line-oriented git output, WITHOUT [tryGit]'s trim. `git status --porcelain`
267
+ * has significant leading whitespace: an unstaged modification is `" M path"`,
268
+ * so trimming the whole blob eats the first line's leading space — and a fixed
269
+ * `slice(3)` then swallows that path's first character. The receipt would name
270
+ * a file that does not exist. Only trailing newlines are dropped here.
271
+ */
272
+ function tryGitLines(cmd) {
273
+ try {
274
+ const out = execSync(`git ${cmd}`, { cwd: ROOT, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
275
+ return out.replace(/\n+$/, "").split("\n").filter(Boolean);
276
+ } catch {
277
+ return [];
278
+ }
279
+ }
280
+
281
+ // Recursive: desktopTest writes TEST-*.xml flat, but connected (instrumented) results
282
+ // land one directory level down per device (build/outputs/androidTest-results/connected/
283
+ // debug/<device>/TEST-*.xml) — both shapes are summarized by the same walk.
284
+ function junitSummary(dir) {
285
+ if (!fs.existsSync(dir)) return null;
286
+ let tests = 0, failures = 0, errors = 0, skipped = 0;
287
+ const walk = (d) => {
288
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
289
+ const p = path.join(d, entry.name);
290
+ if (entry.isDirectory()) {
291
+ walk(p);
292
+ continue;
293
+ }
294
+ if (!entry.name.startsWith("TEST-") || !entry.name.endsWith(".xml")) continue;
295
+ const xml = fs.readFileSync(p, "utf8");
296
+ const m = xml.match(/<testsuite[^>]*tests="(\d+)"[^>]*skipped="(\d+)"[^>]*failures="(\d+)"[^>]*errors="(\d+)"/);
297
+ if (m) {
298
+ tests += Number(m[1]);
299
+ skipped += Number(m[2]);
300
+ failures += Number(m[3]);
301
+ errors += Number(m[4]);
302
+ }
303
+ }
304
+ };
305
+ walk(dir);
306
+ return { tests, failures, errors, skipped };
307
+ }
308
+
309
+ function deviceAttached() {
310
+ const res = sh("adb devices", { timeout: 10_000 });
311
+ if (!res.ok) return false;
312
+ return res.out.split("\n").slice(1).some((l) => /\tdevice$/.test(l.trim().replace(/\s+/g, "\t")));
313
+ }
314
+
315
+ // ── The machine-global device lease (qa/lib/device-lease.mjs) ───────────────
316
+ // LANE_MARKER above is per-PROJECT; the device is machine-GLOBAL. A scratch app
317
+ // in /tmp and the real app each stamp their own marker and still share the one
318
+ // emulator — nothing stopped two lanes (or a lane and a live console session)
319
+ // driving it at once, which is the observed wedged-adbd / `device offline` /
320
+ // crossed-app-state failure class. Every device-touching step below takes the
321
+ // lease before touching the device.
322
+ //
323
+ // SCOPE DECISION — once per run, not per step: the lease is acquired lazily by
324
+ // the FIRST device step that actually reaches the device and held until the
325
+ // lane exits (released in the same `finally` as LANE_MARKER). A single run must
326
+ // not thrash acquire/release between adjacent device steps, and holding through
327
+ // the desktop steps interleaved among them (a11y sits between tokenDrift and
328
+ // e2eSmoke) costs nothing — nothing else should drive the device mid-lane
329
+ // anyway, which is the whole point.
330
+ //
331
+ // ON CONTENTION THE STEP RETURNS SKIP — NEVER FAIL: nothing is broken; another
332
+ // run legitimately holds the device. This composes with the evidence ladder
333
+ // (qa/lib/evidence-level.mjs): a SKIPped device step simply does not buy its
334
+ // rung, so contention visibly DEGRADES the evidence level (L2 falls back to L1)
335
+ // instead of corrupting the run with a false red — that degradation being
336
+ // honest and visible is exactly why SKIP is the right verdict.
337
+ let laneDeviceLease = null;
338
+
339
+ /** Serials of devices currently in `device` state (same parse as deviceAttached). */
340
+ function attachedDeviceSerials() {
341
+ const res = sh("adb devices", { timeout: 10_000 });
342
+ if (!res.ok) return [];
343
+ return res.out
344
+ .split("\n")
345
+ .slice(1)
346
+ .map((l) => l.trim())
347
+ .filter(Boolean)
348
+ .map((l) => l.split(/\s+/))
349
+ .filter(([, state]) => state === "device")
350
+ .map(([serial]) => serial);
351
+ }
352
+
353
+ /**
354
+ * Acquire (or confirm) the lane's device lease for a device step.
355
+ * Returns null when the lane holds the device; otherwise the SKIP result the
356
+ * step should return verbatim. The serial leased is the one the lane will
357
+ * actually drive: the single attached device, or ANDROID_SERIAL when several
358
+ * are attached (adb/Gradle/Maestro honor the same variable). Ambiguity is
359
+ * SKIPped by name — leasing a guess would protect the wrong device.
360
+ */
361
+ function leaseDeviceForStep(stepName) {
362
+ if (laneDeviceLease) return null; // already held for this run
363
+ const serials = attachedDeviceSerials();
364
+ if (serials.length === 0) return null; // each step's own guard SKIPs "no device" with its precise reason
365
+ let serial = serials[0];
366
+ if (serials.length > 1) {
367
+ const chosen = process.env.ANDROID_SERIAL;
368
+ if (chosen && serials.includes(chosen)) {
369
+ serial = chosen;
370
+ } else {
371
+ return {
372
+ name: stepName,
373
+ verdict: "SKIP",
374
+ reason: `${serials.length} devices attached (${serials.join(", ")}) — the lane cannot tell which one it would drive, so it leases none rather than guessing. Set ANDROID_SERIAL to the device this lane should own, or detach the extras.`,
375
+ durationMs: 0,
376
+ };
377
+ }
378
+ }
379
+ const res = acquireDeviceLease({ serial, holder: `verify lane ${stepName}`, root: ROOT });
380
+ if (!res.ok) {
381
+ return {
382
+ name: stepName,
383
+ verdict: "SKIP",
384
+ reason: `device ${serial} is held by ${formatHolder(res.heldBy)} — device evidence is batched, not concurrent; wait for it or run once when it finishes`,
385
+ durationMs: 0,
386
+ };
387
+ }
388
+ if (res.reclaimed) {
389
+ console.error(`· reclaimed a dead device lease on ${serial} (was ${formatHolder(res.reclaimed)})`);
390
+ }
391
+ laneDeviceLease = res.handle;
392
+ return null;
393
+ }
394
+
395
+ // Settle adb before handing the device to whatever drives it next (Maestro, the
396
+ // instrumented runner). An install task returning 0 means the package manager accepted
397
+ // the APK — NOT that the device is ready to be driven: a reinstall over a running app
398
+ // briefly drops the emulator's adb transport. `adb devices` still says `device`, but a
399
+ // fresh adb client (Maestro's dadb, Gradle's ddmlib) gets `device offline` and dies
400
+ // before the first assertion (observed 4/4 when the live-inspector tier ran earlier in
401
+ // the lane — its port-forward traffic widens the window — and 0/4 when it was skipped).
402
+ // wait-for-device blocks only while the transport is actually down; the kill/start pair
403
+ // ahead of it clears a stale server-side transport entry that survives the device coming
404
+ // back. Neither weakens any assertion — every downstream check still passes on its own
405
+ // merits.
406
+ function settleAdb() {
407
+ sh("adb kill-server");
408
+ sh("adb start-server");
409
+ sh("adb wait-for-device");
410
+ }
411
+
412
+ // ── Steps ──────────────────────────────────────────────────────────────────
413
+ // Each returns { name, verdict, reason?, durationMs, details? }. Failure
414
+ // reasons are worded for an AI collaborator to act on.
415
+
416
+ // Spec ↔ test drift gate — pure Node, no Gradle. The clause/citation scan
417
+ // itself lives in qa/lib/spec-coverage.mjs — the SAME scan feature-brief.mjs
418
+ // derives doneness from, so this gate and the Features view can never disagree
419
+ // about a clause. This step owns only the orphan decision + bookkeeping.
420
+ // The first question any verdict depends on: is the lane that is about to
421
+ // issue it the lane this app was given?
422
+ //
423
+ // Without this the receipt is unfalsifiable in one specific way — edit
424
+ // qa/verify.mjs to force every step PASS and the receipt still validates,
425
+ // because the edited file is simply part of the hashed input surface. Hashing
426
+ // the machine-owned region against qa/harness.lock.json closes that: the lane
427
+ // cannot vouch for itself while modified.
428
+ //
429
+ // DELIBERATELY NOT MEMOIZED. Every other pure-Node step can serve a cached
430
+ // PASS when its inputs are unchanged; a cached PASS on an integrity check is
431
+ // precisely the failure it exists to prevent, and 34 file reads are too cheap
432
+ // to be worth the risk.
433
+ //
434
+ // Three states, three verdicts:
435
+ // intact PASS
436
+ // modified FAIL — named files, with the command that restores them
437
+ // unlocked SKIP — an app stamped before locks existed. Nothing is known to
438
+ // be wrong, but nothing is proven either; recording the gap keeps
439
+ // the pipeline honest instead of quietly passing.
440
+ function stepHarnessIntegrity() {
441
+ const started = Date.now();
442
+ const r = checkHarnessIntegrity(ROOT);
443
+ const base = { name: "harnessIntegrity", durationMs: Date.now() - started, harness: r };
444
+
445
+ if (r.status === "intact") {
446
+ return { ...base, verdict: "PASS", note: describeIntegrity(r) };
447
+ }
448
+ if (r.status === "unlocked") {
449
+ return {
450
+ ...base,
451
+ verdict: "SKIP",
452
+ reason: `no ${LOCK_PATH} — this app was stamped before harness locks existed. ` +
453
+ "`npx create-cmp-cli upgrade --harness` records one.",
454
+ };
455
+ }
456
+
457
+ const named = [
458
+ ...r.modified.map((f) => `modified ${f}`),
459
+ ...r.missing.map((f) => `missing ${f}`),
460
+ ...r.extra.map((f) => `unrecorded ${f}`),
461
+ ];
462
+ return {
463
+ ...base,
464
+ verdict: "FAIL",
465
+ reason:
466
+ `the verify lane has been modified since it was installed — ${describeIntegrity(r)}. ` +
467
+ "Lane code is machine-owned: it is byte-identical in every create-cmp app and carries " +
468
+ "no app content, so a local edit is either an accident, a half-applied upgrade, or an " +
469
+ "attempt to make this receipt say something the lane would not. Restore it with " +
470
+ "`npx create-cmp-cli upgrade --harness`, which also reports any genuine local patch " +
471
+ "instead of discarding it.",
472
+ files: named,
473
+ };
474
+ }
475
+
476
+ function stepSpecCoverage() {
477
+ const started = Date.now();
478
+ const specsDir = path.join(ROOT, "specs");
479
+ if (!fs.existsSync(specsDir)) {
480
+ return { name: "specCoverage", verdict: "SKIP", reason: "no specs/ directory in this project", durationMs: Date.now() - started };
481
+ }
482
+
483
+ const clauses = scanSpecClauses(ROOT);
484
+ const tags = scanCitations(ROOT);
485
+ const searchDirs = [path.join(ROOT, "composeApp/src"), path.join(ROOT, "qa/e2e")];
486
+ const files = searchDirs.flatMap((d) => walkFiles(d, [".kt", ".kts", ".yaml", ".yml"]));
487
+
488
+ const citedIds = new Set(tags.map((t) => t.id));
489
+ const orphanClauses = [...clauses.entries()].filter(([, c]) => !c.withdrawn).filter(([id]) => !citedIds.has(id));
490
+ const orphanTags = tags.filter((t) => !clauses.has(t.id) || clauses.get(t.id).withdrawn);
491
+
492
+ if (orphanClauses.length === 0 && orphanTags.length === 0) {
493
+ // Tier visibility, not a gate (industry rule: instrument before you police). A clause
494
+ // cited only from desktop-tier tests can still hide a platform-behavior bug — both
495
+ // production apps shipped alarm/notification defects behind clauses that were
496
+ // "covered" by JVM tests androidMain never ran under. The line names them; the
497
+ // instrumented seam (androidChecks) is where such clauses earn a citation.
498
+ const tiers = clauseTierCoverage(clauses, tags);
499
+ return {
500
+ name: "specCoverage",
501
+ verdict: "PASS",
502
+ durationMs: Date.now() - started,
503
+ details: {
504
+ clauses: [...clauses.values()].filter((c) => !c.withdrawn).length,
505
+ withdrawn: [...clauses.values()].filter((c) => c.withdrawn).length,
506
+ tags: tags.length,
507
+ files: files.length,
508
+ tierNote: tiers.summaryLine,
509
+ },
510
+ };
511
+ }
512
+
513
+ const lines = ["Spec coverage broken — the spec and the tests have drifted apart:"];
514
+ for (const [id, c] of orphanClauses) {
515
+ lines.push(` [${id}] ${c.file} — no durable test cites this clause. Write the test (tag it '// SPEC: ${id}') or withdraw the clause (strike it through).`);
516
+ }
517
+ for (const t of orphanTags) {
518
+ const known = clauses.get(t.id);
519
+ if (known?.withdrawn) {
520
+ lines.push(` // SPEC: ${t.id} at ${t.file}:${t.line} — the test verifies withdrawn behavior (clause ${t.id} in ${known.file} is struck through). Remove the test or un-withdraw the clause.`);
521
+ } else {
522
+ lines.push(` // SPEC: ${t.id} at ${t.file}:${t.line} — no such clause in specs/. Add the clause (AI proposes, human confirms) or fix the id.`);
523
+ }
524
+ }
525
+
526
+ return {
527
+ name: "specCoverage",
528
+ verdict: "FAIL",
529
+ reason: lines.join("\n"),
530
+ durationMs: Date.now() - started,
531
+ details: {
532
+ clauses: [...clauses.values()].filter((c) => !c.withdrawn).length,
533
+ withdrawn: [...clauses.values()].filter((c) => c.withdrawn).length,
534
+ tags: tags.length,
535
+ files: files.length,
536
+ },
537
+ };
538
+ }
539
+
540
+ // Human-approval gate (VERIFICATION-LAYER-DESIGN.md §2) — pure Node, no Gradle,
541
+ // same grouping as specCoverage. The decision itself lives in
542
+ // qa/lib/approvals.mjs (evaluateApprovalsGate); this step only adds the
543
+ // name/duration bookkeeping every step in this file carries.
544
+ function stepApprovals() {
545
+ const started = Date.now();
546
+ const { verdict, reason, statuses } = evaluateApprovalsGate(ROOT);
547
+ return {
548
+ name: "approvals",
549
+ verdict,
550
+ reason,
551
+ durationMs: Date.now() - started,
552
+ details: { artifacts: statuses.map((s) => ({ id: s.id, status: s.status, hash: s.hash })) },
553
+ };
554
+ }
555
+
556
+ // There is deliberately NO feature-doneness step here (CHANGE-FLOW-DESIGN.md
557
+ // §7): a feature's doneness is DERIVED from gates this lane already runs —
558
+ // specCoverage fails an uncited clause, the test steps fail a broken promise,
559
+ // and the receipt's inputs.hash attests the tree. A second mechanism would be
560
+ // a second truth.
561
+
562
+ // Component ↔ story parity gate (STUDIO-REDESIGN.md §3.3) — pure Node, no
563
+ // Gradle, same grouping as specCoverage/approvals. The decision itself lives
564
+ // in qa/lib/component-stories.mjs (evaluateComponentStoryParity); this step
565
+ // only adds the name/duration bookkeeping every step in this file carries.
566
+ function stepComponentStories() {
567
+ const started = Date.now();
568
+ const { verdict, reason, details } = evaluateComponentStoryParity(ROOT);
569
+ return { name: "componentStories", verdict, reason, durationMs: Date.now() - started, details };
570
+ }
571
+
572
+ // Navigation-reachability gate (task FI-7, docs/AUTONOMY-GAPS.md §3) — pure
573
+ // Node, no Gradle, same grouping as specCoverage/approvals/componentStories.
574
+ // The decision itself lives in qa/lib/reachability.mjs (evaluateReachability);
575
+ // this step only adds the name/duration bookkeeping every step in this file
576
+ // carries. Closes the exact hole a real feature slipped through: every other
577
+ // gate PASSed while its screen was wired into nothing.
578
+ function stepReachability() {
579
+ const started = Date.now();
580
+ const { verdict, reason, details } = evaluateReachability(ROOT);
581
+ return { name: "reachability", verdict, reason, durationMs: Date.now() - started, details };
582
+ }
583
+
584
+ // Architecture-doc freshness gate (Wave B, docs/proposals/architecture-document-
585
+ // standard.md §6) — pure Node, no Gradle, same grouping as specCoverage/
586
+ // approvals. The decision itself lives in qa/lib/arch-doc.mjs
587
+ // (regenerateArchDoc); this step only adds the name/duration bookkeeping every
588
+ // step in this file carries, plus wording the FAIL reason for an AI
589
+ // collaborator (name the stale/missing section, name the fix command).
590
+ function stepArchDoc() {
591
+ const started = Date.now();
592
+ const elapsed = () => Date.now() - started;
593
+
594
+ const result = regenerateArchDoc(ROOT);
595
+ if (!result.ok) {
596
+ return { name: "archDoc", verdict: "SKIP", reason: `${result.reason} — nothing to check`, durationMs: elapsed() };
597
+ }
598
+ if (result.unknownSections.length > 0) {
599
+ return {
600
+ name: "archDoc",
601
+ verdict: "FAIL",
602
+ reason: `${ARCH_DOC_REL_PATH} has cmp:generated marker(s) with no registered generator: ${result.unknownSections.join(", ")} — add a generator in qa/lib/arch-doc.mjs or remove the marker.`,
603
+ durationMs: elapsed(),
604
+ };
605
+ }
606
+
607
+ const stale = result.changed || result.missingSections.length > 0;
608
+ if (!stale) {
609
+ return { name: "archDoc", verdict: "PASS", durationMs: elapsed(), details: { sectionsChecked: SECTION_IDS.length } };
610
+ }
611
+
612
+ const lines = [`${ARCH_DOC_REL_PATH} is stale — a generated section no longer matches the tree:`];
613
+ for (const id of result.changedSections) {
614
+ lines.push(` [${id}] regenerating would change this section.`);
615
+ }
616
+ for (const id of result.missingSections) {
617
+ lines.push(` [${id}] marker missing from the doc entirely — never generated.`);
618
+ }
619
+ lines.push("Run: node qa/arch-doc.mjs");
620
+ return {
621
+ name: "archDoc",
622
+ verdict: "FAIL",
623
+ reason: lines.join("\n"),
624
+ durationMs: elapsed(),
625
+ details: { changedSections: result.changedSections, missingSections: result.missingSections },
626
+ };
627
+ }
628
+
629
+ // Schema-history gate — pure Node + git, no Gradle, same grouping as the other
630
+ // evidence checks. Room's exportSchema writes one <version>.json per database per
631
+ // target under composeApp/schemas/. Every version EXCEPT the current highest is a
632
+ // frozen historical record of a database that shipped: migrations are written and
633
+ // validated against those exact bytes, so a regeneration that rewrites them
634
+ // silently corrupts the baseline every future migration is proven against. Only
635
+ // the highest version is the live, in-progress schema — free to change or appear
636
+ // (that IS the current change). This gate exists because schema regeneration
637
+ // looks like harmless build output right up until a shipped user's upgrade fails.
638
+ function stepSchemaHistory() {
639
+ const started = Date.now();
640
+ const elapsed = () => Date.now() - started;
641
+ const schemasRel = path.join("composeApp", "schemas");
642
+ const schemasRoot = path.join(ROOT, schemasRel);
643
+
644
+ if (!fs.existsSync(schemasRoot)) {
645
+ return { name: "schemaHistory", verdict: "SKIP", reason: "no exported Room schemas (composeApp/schemas/ absent) — nothing frozen to guard", durationMs: elapsed() };
646
+ }
647
+ const gitTop = tryGit("rev-parse --show-toplevel");
648
+ if (!gitTop || !tryGit("rev-parse HEAD")) {
649
+ return { name: "schemaHistory", verdict: "SKIP", reason: "no git history yet — schema versions have no committed baseline to be frozen against", durationMs: elapsed() };
650
+ }
651
+
652
+ // Every directory holding versioned schema JSONs, with its highest version on disk.
653
+ const versionFile = /^(\d+)\.json$/;
654
+ const maxVersionByDir = new Map(); // absolute dir path -> highest N among its N.json files
655
+ const walkSchemas = (dir) => {
656
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
657
+ const p = path.join(dir, entry.name);
658
+ if (entry.isDirectory()) walkSchemas(p);
659
+ else {
660
+ const m = entry.name.match(versionFile);
661
+ if (m) maxVersionByDir.set(dir, Math.max(maxVersionByDir.get(dir) ?? 0, Number(m[1])));
662
+ }
663
+ }
664
+ };
665
+ walkSchemas(schemasRoot);
666
+
667
+ // Tracked schema files whose committed bytes no longer match the tree (staged or
668
+ // unstaged; deletions included). Paths come back relative to the git toplevel.
669
+ // Untracked files never appear here — a brand-new version file is by definition
670
+ // not yet frozen history.
671
+ const dirtyFiles = tryGitLines(`diff --name-only HEAD -- "${schemasRel.replace(/\\/g, "/")}"`);
672
+
673
+ const violations = [];
674
+ for (const rel of dirtyFiles) {
675
+ const abs = path.resolve(gitTop, rel);
676
+ const m = path.basename(abs).match(versionFile);
677
+ if (!m) continue; // not a versioned schema JSON
678
+ const version = Number(m[1]);
679
+ const dirMax = maxVersionByDir.get(path.dirname(abs));
680
+ // The highest version currently on disk is the live schema — dirty is fine.
681
+ // Anything else (a lower version, or a file whose whole directory is gone)
682
+ // is rewritten/deleted history.
683
+ if (dirMax !== undefined && version === dirMax) continue;
684
+ violations.push(rel);
685
+ }
686
+
687
+ if (violations.length === 0) {
688
+ return { name: "schemaHistory", verdict: "PASS", durationMs: elapsed(), details: { schemaDirs: maxVersionByDir.size } };
689
+ }
690
+
691
+ const lines = [
692
+ "Historical Room schema files were modified or deleted — these are frozen records of shipped databases, and regeneration must never rewrite them (migrations are validated against these exact bytes). Only the current highest version may change. Restore each file:",
693
+ ];
694
+ for (const rel of violations) lines.push(` git checkout -- ${rel}`);
695
+ lines.push("If you intended a schema change, bump the database version so a NEW <version>.json is exported instead of overwriting history.");
696
+ return {
697
+ name: "schemaHistory",
698
+ verdict: "FAIL",
699
+ reason: lines.join("\n"),
700
+ durationMs: elapsed(),
701
+ details: { schemaDirs: maxVersionByDir.size, violations },
702
+ };
703
+ }
704
+
705
+ function stepBuild() {
706
+ const res = shGradle(`${GRADLEW} :composeApp:assembleDebug --console=plain`);
707
+ return {
708
+ name: "build",
709
+ verdict: res.ok ? "PASS" : "FAIL",
710
+ reason: res.ok ? undefined : `assembleDebug failed — fix the build before anything else:\n${res.out.split("\n").filter((l) => /error|FAILURE/i.test(l)).slice(0, 12).join("\n")}`,
711
+ durationMs: res.durationMs,
712
+ };
713
+ }
714
+
715
+ // The build nobody runs until the day they need it.
716
+ //
717
+ // assembleDebug passing says nothing about assembleRelease: R8 and `lintVital` only run on
718
+ // the release variant, and BuildConfig is generated PER BUILD TYPE, so a constant declared
719
+ // in one and not the other is a compile error that only release ever sees. All three of
720
+ // those bit this template at once, and none of them were visible from a green debug lane —
721
+ // the first release build ever attempted (2026-07-29) failed three times over.
722
+ //
723
+ // So release is proven at the checkpoint, not discovered at launch. Unsigned: signing needs
724
+ // a keystore, which belongs to whoever ships the app, and this step is about the shrinker
725
+ // and the build graph rather than the signature.
726
+ function stepReleaseBuild() {
727
+ const res = shGradle(`${GRADLEW} :composeApp:assembleRelease --console=plain`);
728
+ return {
729
+ name: "releaseBuild",
730
+ verdict: res.ok ? "PASS" : "FAIL",
731
+ reason: res.ok
732
+ ? undefined
733
+ : `assembleRelease failed — the shippable build is broken even though the debug one is fine:\n${res.out
734
+ .split("\n")
735
+ .filter((l) => /error|FAILURE|Missing class|Unresolved/i.test(l))
736
+ .slice(0, 12)
737
+ .join("\n")}`,
738
+ durationMs: res.durationMs,
739
+ };
740
+ }
741
+
742
+ // Runs a filtered slice of the JVM test tier and names the verdict after the gate it proves.
743
+ // The full suite already ran in unitTests; the filtered slices stay cheap (compilation is
744
+ // cached) while `--rerun` forces the tests themselves to EXECUTE — see stepUnitTests.
745
+ // In fast mode the flag is omitted (RERUN, defined with the mode flags above): the
746
+ // integrity mechanism belongs to the runs that produce integrity-bearing artifacts, and a
747
+ // fast receipt has already declared itself non-evidence.
748
+ function gradleTestStep(name, testsFilter, failHint) {
749
+ return () => {
750
+ const res = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN} --tests "${testsFilter}" --console=plain`);
751
+ return {
752
+ name,
753
+ verdict: res.ok ? "PASS" : "FAIL",
754
+ reason: res.ok
755
+ ? undefined
756
+ : `${failHint}\n${res.out.split("\n").filter((l) => /FAILED|\[(ARCH|SHELL|HOME)-\d+\]|error:/i.test(l)).slice(0, 15).join("\n")}`,
757
+ durationMs: res.durationMs,
758
+ };
759
+ };
760
+ }
761
+
762
+ function stepUnitTests() {
763
+ // `--rerun` is EVIDENCE INTEGRITY, not pedantry: without it, Gradle's build cache can
764
+ // restore a PASS recorded against a *different* tree state (deterministic re-scaffolds
765
+ // produce byte-identical sources, and golden baselines aren't compile inputs), so the
766
+ // receipt would attest tests that never executed. Compilation stays cached — only the
767
+ // test execution is forced. Scoped to FULL mode (see RERUN above): the integrity
768
+ // mechanism belongs to the runs that produce integrity-bearing artifacts, and a fast
769
+ // receipt is already declared non-evidence.
770
+ //
771
+ // Fast mode additionally scopes the suite to tests plausibly affected by the
772
+ // working-tree change (qa/lib/affected-tests.mjs): changed .kt files map to
773
+ // `--tests "*<segment>*"` patterns, with a mandatory blast-radius escape hatch (build
774
+ // files, DI, theme, shared components, qa/, anything outside composeApp/src → full
775
+ // suite) and fail-open on every uncertain case (no git, unmappable change). FALSE
776
+ // NEGATIVES ARE ACCEPTABLE HERE AND ONLY HERE: the full, unfiltered suite runs at the
777
+ // checkpoint (the full lane), where done is actually decided. The filter that ran is
778
+ // reported in the step's note and recorded in the (fast-only) receipt, so a filtered
779
+ // run can never be mistaken for the full suite.
780
+ let note;
781
+ let testsArgs = "";
782
+ let affected = null;
783
+ if (fast) {
784
+ const changed = changedWorkingTreePaths(ROOT);
785
+ if (changed === null) {
786
+ note = "full suite — git unavailable, cannot derive the change (fail open)";
787
+ } else {
788
+ const filter = deriveAffectedFilter(changed);
789
+ if (filter.mode === "filtered") {
790
+ testsArgs = filter.patterns.map((p) => ` --tests "${p}"`).join("");
791
+ note = `affected: ${filter.patterns.join(", ")} — ${filter.sourcePaths.length} changed source file(s)`;
792
+ affected = { patterns: filter.patterns, changedFiles: filter.sourcePaths.length };
793
+ } else {
794
+ note = `full suite — ${filter.reason}`;
795
+ }
796
+ }
797
+ }
798
+ let res = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN}${testsArgs} --console=plain`);
799
+ if (fast && testsArgs && !res.ok && /No tests found for given includes/.test(res.out)) {
800
+ // The heuristic filter matched no test class at all (e.g. a feature with no tests
801
+ // yet). That is the harness's guess being wrong, not the app — fall back to the
802
+ // full suite in-lane rather than false-redding on our own filter. (RERUN is empty
803
+ // here by construction — this branch only exists in fast mode.)
804
+ const retry = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN} --console=plain`);
805
+ retry.durationMs += res.durationMs;
806
+ res = retry;
807
+ note = "full suite — the affected-test filter matched no tests (fell back)";
808
+ affected = null;
809
+ DEGRADED_PATHS.push("affected-test filter matched no tests — fell back to the full desktopTest suite");
810
+ }
811
+ const summary = junitSummary(path.join(ROOT, "composeApp/build/test-results/desktopTest"));
812
+ let details = summary ?? undefined;
813
+ if (affected) details = { ...(summary ?? {}), affected };
814
+ return {
815
+ name: "unitTests",
816
+ verdict: res.ok ? "PASS" : "FAIL",
817
+ reason: res.ok
818
+ ? undefined
819
+ : `desktopTest failed (${summary ? `${summary.failures + summary.errors} of ${summary.tests} tests` : "see output"}). Fix the failing behavior — do not delete or weaken tests to pass:\n${res.out.split("\n").filter((l) => /FAILED|error:/i.test(l)).slice(0, 12).join("\n")}`,
820
+ note,
821
+ durationMs: res.durationMs,
822
+ details,
823
+ };
824
+ }
825
+
826
+ const stepConformance = gradleTestStep(
827
+ "conformance",
828
+ "*ArchitectureConformanceTest",
829
+ "Architecture conformance violated (specs/app-base.spec.md ARCH clauses). The failing rule names the clause, files, and fix:",
830
+ );
831
+ const stepGoldenTrees = gradleTestStep(
832
+ "goldenTrees",
833
+ "*GoldenTreeTest",
834
+ "Golden-tree drift: a screen's rendered STRUCTURE no longer matches qa/golden/. Unintended → fix your change; intended → regenerate with UPDATE_GOLDEN=1 and declare it:",
835
+ );
836
+ const stepA11y = gradleTestStep(
837
+ "a11y",
838
+ "*A11yConformanceTest",
839
+ "A11y gate failed (SHELL-04): interactive nodes must expose a testTag, text, or contentDescription:",
840
+ );
841
+
842
+ // ── Determinism probe (roadmap §10 item 8) — opt-in, ci-profile ────────────
843
+ // ARCH-13 statically bans ambient time reads — in APP code. A library the
844
+ // app calls can still read the wall clock, and a golden can still depend on
845
+ // the machine's timezone through a seam the static net cannot see (a
846
+ // ViewModel constructed without its injected clock already caused one
847
+ // overnight golden-tree drift). This probe closes that gap DYNAMICALLY: it
848
+ // runs the JVM test tier twice, under two timezones whose local calendar
849
+ // dates never agree — the offsets are 26 hours apart, so any date-derived
850
+ // value differs between the legs at every instant (see DETERMINISM_TIMEZONES
851
+ // in qa/lib/determinism.mjs for why UTC-12/UTC+14 and not UTC/UTC+14) — and
852
+ // FAILs naming every test whose outcome differs between the legs.
853
+ //
854
+ // Mechanics that carry the honesty:
855
+ // - TZ reaches the test JVM through the environment: Gradle forwards the
856
+ // client's environment to the daemon on every build, and test workers
857
+ // fork from the daemon — so the child env below is inherited all the way
858
+ // down to the JVM whose default timezone the tests see.
859
+ // - BOTH legs force --rerun. Without it Gradle would mark the second leg
860
+ // up-to-date (TZ is not a declared build input) and replay the first
861
+ // leg's results — the probe would then compare a run against its own
862
+ // echo and certify a determinism it never tested (the build-cache-replay
863
+ // lesson, again). The legs use the mode-scoped RERUN like every other
864
+ // desktopTest invocation — and because --determinism is refused alongside
865
+ // --fast up front, RERUN is always " --rerun" by the time a leg runs.
866
+ // - Only verdicts and failure output are compared; durations are never even
867
+ // parsed (qa/lib/determinism.mjs), so a timing wobble is structurally
868
+ // unable to trip the probe.
869
+ function stepDeterminism() {
870
+ const started = Date.now();
871
+ const elapsed = () => Date.now() - started;
872
+ if (!determinism) {
873
+ return {
874
+ name: "determinism",
875
+ verdict: "SKIP",
876
+ reason: "determinism probe is opt-in (it runs the JVM test tier twice) — add --determinism to this lane, or run the probe alone: node qa/verify.mjs --determinism",
877
+ durationMs: elapsed(),
878
+ };
879
+ }
880
+
881
+ const resultsDir = path.join(ROOT, "composeApp/build/test-results/desktopTest");
882
+ const legs = [];
883
+ for (const { tz, label } of DETERMINISM_TIMEZONES) {
884
+ const res = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN} --console=plain`, { env: { ...process.env, TZ: tz } });
885
+ // Parsed NOW, before the next leg overwrites the same results directory.
886
+ const outcomes = parseJUnitOutcomes(resultsDir);
887
+ legs.push({ tz, label, ok: res.ok, outcomes, tail: res.out.split("\n").slice(-8).join("\n") });
888
+ }
889
+ const [a, b] = legs;
890
+ const labelA = `TZ=${a.tz} (${a.label})`;
891
+ const labelB = `TZ=${b.tz} (${b.label})`;
892
+ const countA = Object.keys(a.outcomes).length;
893
+ const countB = Object.keys(b.outcomes).length;
894
+
895
+ if (countA === 0 && countB === 0) {
896
+ // Neither leg produced a single test result: the suite failed before
897
+ // running anything (build error). The probe measured nothing — that is
898
+ // a FAIL that says so, never a PASS by absence of differences.
899
+ return {
900
+ name: "determinism",
901
+ verdict: "FAIL",
902
+ reason: `determinism probe could not execute: desktopTest produced no test results under either timezone — the suite fails before running (fix the build first; this is not a timezone difference):\n${a.tail}`,
903
+ durationMs: elapsed(),
904
+ };
905
+ }
906
+ if (countA === 0 || countB === 0) {
907
+ const ran = countA > 0 ? { label: labelA, n: countA } : { label: labelB, n: countB };
908
+ const empty = countA > 0 ? b : a;
909
+ return {
910
+ name: "determinism",
911
+ verdict: "FAIL",
912
+ reason: `Nondeterminism under timezone shift: desktopTest ran ${ran.n} test(s) under ${ran.label} but produced no results at all under TZ=${empty.tz} (${empty.label}) — the suite itself dies under that zone:\n${empty.tail}`,
913
+ durationMs: elapsed(),
914
+ details: { timezones: DETERMINISM_TIMEZONES.map((t) => t.tz) },
915
+ };
916
+ }
917
+
918
+ const diffs = compareOutcomes(a.outcomes, b.outcomes, labelA, labelB);
919
+ if (diffs.length > 0) {
920
+ const lines = [
921
+ `Nondeterminism under timezone shift — the same tree produced different outcomes under ${labelA} vs ${labelB}. Something reads ambient time or zone past the ARCH-13 net (a library default, an uninjected clock, a golden that captures "today"):`,
922
+ ];
923
+ for (const d of diffs.slice(0, 20)) lines.push(` [${d.step}] ${d.test} — ${d.detail}`);
924
+ if (diffs.length > 20) lines.push(` … and ${diffs.length - 20} more differing test(s)`);
925
+ return {
926
+ name: "determinism",
927
+ verdict: "FAIL",
928
+ reason: lines.join("\n"),
929
+ durationMs: elapsed(),
930
+ details: { timezones: DETERMINISM_TIMEZONES.map((t) => t.tz), diffs: diffs.slice(0, 50) },
931
+ };
932
+ }
933
+
934
+ const failedIdentically = Object.values(a.outcomes).filter((o) => o.status !== "pass" && o.status !== "skip").length;
935
+ return {
936
+ name: "determinism",
937
+ verdict: "PASS",
938
+ // Identical red is DETERMINISTIC red: the probe's claim ("no timezone
939
+ // dependence") holds, and the failing tests already belong to
940
+ // unitTests/goldenTrees, which fail the lane on their own merits — a
941
+ // second FAIL here would report the same defect twice under a wrong name.
942
+ note:
943
+ failedIdentically > 0
944
+ ? `${failedIdentically} test(s) failed identically under both timezones — deterministic, but red (the owning test steps report it)`
945
+ : undefined,
946
+ durationMs: elapsed(),
947
+ details: { timezones: DETERMINISM_TIMEZONES.map((t) => t.tz), testsCompared: countA },
948
+ };
949
+ }
950
+
951
+ // Live tokenDrift tier (harness M4-D): when a debug app + device are available,
952
+ // fetches the declared catalog and the live semantics tree off the debug-only
953
+ // inspector server (127.0.0.1:9500, see composeApp/src/androidDebug/.../
954
+ // InspectorHttpServer.kt) and runs compareTokenDrift() over them — real runtime
955
+ // drift detection, embedded in the evidence receipt.
956
+ //
957
+ // Infrastructure absence (no device, app not running) is NEVER a FAIL — only
958
+ // actual drift is. curl (via the existing synchronous sh() helper) stands in for
959
+ // an HTTP client here because every step in this lane runs synchronously; a
960
+ // couple of short retries cover the debug app's cold start.
961
+ const INSPECTOR_PORT = 9500;
962
+
963
+ function curlJson(url, timeoutSec = 5) {
964
+ const res = sh(`curl -s -m ${timeoutSec} -w "\\n%{http_code}" "${url}"`);
965
+ if (!res.ok) return { ok: false };
966
+ const out = res.out;
967
+ const idx = out.lastIndexOf("\n");
968
+ const code = (idx >= 0 ? out.slice(idx + 1) : "").trim();
969
+ const bodyText = idx >= 0 ? out.slice(0, idx) : "";
970
+ if (code !== "200") return { ok: false };
971
+ try {
972
+ return { ok: true, body: JSON.parse(bodyText) };
973
+ } catch {
974
+ return { ok: false };
975
+ }
976
+ }
977
+
978
+ function pollHealth(port, attempts, delaySec) {
979
+ let health = curlJson(`http://127.0.0.1:${port}/inspect/health`);
980
+ for (let tries = 1; !health.ok && tries < attempts; tries += 1) {
981
+ sh(`sleep ${delaySec}`);
982
+ health = curlJson(`http://127.0.0.1:${port}/inspect/health`);
983
+ }
984
+ return health;
985
+ }
986
+
987
+ function stepTokenDrift() {
988
+ const started = Date.now();
989
+ const elapsed = () => Date.now() - started;
990
+
991
+ if (!deviceAttached()) {
992
+ return {
993
+ name: "tokenDrift",
994
+ verdict: "SKIP",
995
+ reason: "no Android device/emulator attached (adb) — runtime token drift needs the live inspector tier",
996
+ durationMs: elapsed(),
997
+ };
998
+ }
999
+
1000
+ const unreachable = () => ({
1001
+ name: "tokenDrift",
1002
+ verdict: "SKIP",
1003
+ reason: "inspector endpoint not reachable on :9500 (debug app not running?) — launch the debug build to enable the live tier",
1004
+ durationMs: elapsed(),
1005
+ });
1006
+
1007
+ // Machine-global lease before the first device touch (contention = SKIP).
1008
+ const leaseSkip = leaseDeviceForStep("tokenDrift");
1009
+ if (leaseSkip) return { ...leaseSkip, durationMs: elapsed() };
1010
+
1011
+ sh(`adb forward tcp:${INSPECTOR_PORT} tcp:${INSPECTOR_PORT}`);
1012
+ try {
1013
+ let health = curlJson(`http://127.0.0.1:${INSPECTOR_PORT}/inspect/health`);
1014
+ if (!health.ok) {
1015
+ // Debug app may not be running — try to launch it (best-effort: parse the
1016
+ // applicationId out of the Android build config), then give it a moment
1017
+ // to cold-start before giving up.
1018
+ let applicationId = null;
1019
+ try {
1020
+ const gradle = fs.readFileSync(path.join(ROOT, "composeApp/build.gradle.kts"), "utf8");
1021
+ applicationId = gradle.match(/applicationId\s*=\s*"([^"]+)"/)?.[1] ?? null;
1022
+ } catch {
1023
+ applicationId = null;
1024
+ }
1025
+ if (applicationId) {
1026
+ sh(`adb shell am start -n ${applicationId}/.MainActivity`);
1027
+ }
1028
+ health = pollHealth(INSPECTOR_PORT, 5, 2);
1029
+ }
1030
+ if (!health.ok) return unreachable();
1031
+
1032
+ const designSystem = curlJson(`http://127.0.0.1:${INSPECTOR_PORT}/inspect/design-system`);
1033
+ const tree = curlJson(`http://127.0.0.1:${INSPECTOR_PORT}/inspect/tree`);
1034
+ if (!designSystem.ok || !tree.ok) return unreachable();
1035
+
1036
+ const { checked, drifted } = compareTokenDrift(designSystem.body, tree.body);
1037
+
1038
+ if (drifted.length === 0) {
1039
+ return {
1040
+ name: "tokenDrift",
1041
+ verdict: "PASS",
1042
+ durationMs: elapsed(),
1043
+ details: { checked, drifted: 0 },
1044
+ };
1045
+ }
1046
+
1047
+ const lines = ["Runtime token drift — a component's resolved value contradicts the declared design-system catalog:"];
1048
+ for (const d of drifted) {
1049
+ lines.push(
1050
+ ` [${d.node}] token '${d.token}' (${d.facet}) — expected ${d.expected}, resolved ${d.actual}. Update the component to use the token, or update the catalog if the token itself changed.`,
1051
+ );
1052
+ }
1053
+ return {
1054
+ name: "tokenDrift",
1055
+ verdict: "FAIL",
1056
+ reason: lines.join("\n"),
1057
+ durationMs: elapsed(),
1058
+ details: { checked, drifted },
1059
+ };
1060
+ } finally {
1061
+ sh(`adb forward --remove tcp:${INSPECTOR_PORT}`);
1062
+ }
1063
+ }
1064
+
1065
+ function maestroAvailable() {
1066
+ return sh("maestro --version", { timeout: 15_000 }).ok;
1067
+ }
1068
+
1069
+ // The e2e guard trio, shared by every step that drives the smoke flow on a device.
1070
+ // Returns null when the harness is fully available, else the SKIP result for [name].
1071
+ function maestroGuards(name) {
1072
+ if (!fs.existsSync(path.join(ROOT, "qa/e2e"))) {
1073
+ return { name, verdict: "SKIP", reason: "e2e harness not included in this project (--no-e2e)", durationMs: 0 };
1074
+ }
1075
+ if (!deviceAttached()) {
1076
+ return { name, verdict: "SKIP", reason: "no Android device/emulator attached (adb)", durationMs: 0 };
1077
+ }
1078
+ if (!maestroAvailable()) {
1079
+ return { name, verdict: "SKIP", reason: "maestro CLI not installed — curl -fsSL https://get.maestro.mobile.dev | bash", durationMs: 0 };
1080
+ }
1081
+ return null;
1082
+ }
1083
+
1084
+ // Drives qa/e2e/smoke.yaml against whatever build is installed, with the device hardened
1085
+ // for headless/CI automation. Shared by e2eSmoke (debug APK) and releaseSmoke (release
1086
+ // APK) so the hardening and the honesty sweep can never drift apart between variants.
1087
+ // Without the hardening, a slow or loaded emulator produces false reds that have nothing
1088
+ // to do with the app:
1089
+ // - hide_error_dialogs=1 stops Android popping ANR/crash dialogs (e.g. SystemUI under load)
1090
+ // that steal focus over the app — a Maestro assert would then see only the dialog;
1091
+ // - MAESTRO_DRIVER_STARTUP_TIMEOUT gives the UiAutomator2 driver a generous budget to come
1092
+ // up on a slow emulator (the built-in default gives up too early under load).
1093
+ // Both are benign, reversible, and only touch the device while the lane is driving it —
1094
+ // hide_error_dialogs is restored to its pre-run value (or deleted, returning the device
1095
+ // to its default) in the finally below, on every exit path.
1096
+ // hide_error_dialogs suppresses the OS dialog, NEVER the underlying event — so after the
1097
+ // run we grep the device log for ANR/crash lines the dialog would have shown, and FAIL on
1098
+ // them. The eyes must report what automation stability had to hide.
1099
+ function runMaestroSmoke(name, priorDurationMs) {
1100
+ const prevHideErrorDialogs = sh("adb shell settings get global hide_error_dialogs").out.trim();
1101
+ sh("adb shell settings put global hide_error_dialogs 1");
1102
+ sh("adb logcat -c"); // clear so the post-run dump only reflects this run
1103
+ try {
1104
+ const res = sh("maestro test qa/e2e/smoke.yaml", { env: { ...process.env, MAESTRO_DRIVER_STARTUP_TIMEOUT: "120000" } });
1105
+ if (!res.ok) {
1106
+ return {
1107
+ name,
1108
+ verdict: "FAIL",
1109
+ reason: `Maestro smoke failed (flow cites the SHELL spec clauses it proves):\n${res.out.split("\n").slice(-15).join("\n")}`,
1110
+ durationMs: priorDurationMs + res.durationMs,
1111
+ };
1112
+ }
1113
+ const anrDump = sh("adb logcat -d -b system,crash,main");
1114
+ const anrRe = /ANR in |FATAL EXCEPTION/i;
1115
+ if (anrDump.ok && anrRe.test(anrDump.out)) {
1116
+ const anrLines = anrDump.out.split("\n").filter((l) => anrRe.test(l)).slice(0, 10).join("\n");
1117
+ return {
1118
+ name,
1119
+ verdict: "FAIL",
1120
+ reason: `Maestro smoke passed, but the device log shows an ANR/crash during the run (hide_error_dialogs only suppresses the OS dialog, never the underlying event):\n${anrLines}`,
1121
+ durationMs: priorDurationMs + res.durationMs,
1122
+ };
1123
+ }
1124
+ return { name, verdict: "PASS", durationMs: priorDurationMs + res.durationMs };
1125
+ } finally {
1126
+ if (prevHideErrorDialogs && prevHideErrorDialogs !== "null") {
1127
+ sh(`adb shell settings put global hide_error_dialogs ${prevHideErrorDialogs}`);
1128
+ } else {
1129
+ sh("adb shell settings delete global hide_error_dialogs");
1130
+ }
1131
+ }
1132
+ }
1133
+
1134
+ function stepE2eSmoke() {
1135
+ const guard = maestroGuards("e2eSmoke");
1136
+ if (guard) return guard;
1137
+ // Machine-global lease before the first device touch (contention = SKIP).
1138
+ const leaseSkip = leaseDeviceForStep("e2eSmoke");
1139
+ if (leaseSkip) return leaseSkip;
1140
+ const install = shGradle(`${GRADLEW} :composeApp:installDebug --console=plain`);
1141
+ if (!install.ok) {
1142
+ return { name: "e2eSmoke", verdict: "FAIL", reason: "installDebug failed — the APK could not be installed on the attached device", durationMs: install.durationMs };
1143
+ }
1144
+ settleAdb();
1145
+ return runMaestroSmoke("e2eSmoke", install.durationMs);
1146
+ }
1147
+
1148
+ // Instrumented behavior tier (composeApp/src/androidInstrumentedTest) — the one step
1149
+ // whose evidence crosses the process boundary. Alarms, notification channels,
1150
+ // full-screen intents, PendingIntent identity, and audio routing are OS facts:
1151
+ // desktopTest is a JVM, golden trees are structure, the conformance suite is static,
1152
+ // and the Maestro smoke taps UI without asserting anything about the shade or the
1153
+ // alarm table. Nine escaped platform-semantics defects across two real apps trace to
1154
+ // exactly this blind spot; the hand-built precursor of this step caught two bugs the
1155
+ // week it landed. `connectedDebugAndroidTest` builds, installs, and runs the
1156
+ // instrumented suite in the app's real process on the attached device.
1157
+ //
1158
+ // SKIP (never FAIL) on missing infrastructure — no device, or no instrumented sources
1159
+ // yet — mirroring e2eSmoke's stance: absence of the tier is recorded honestly, only
1160
+ // broken behavior fails.
1161
+ function stepAndroidChecks() {
1162
+ const started = Date.now();
1163
+ const instrumentedDir = path.join(ROOT, "composeApp/src/androidInstrumentedTest");
1164
+ const hasSources = fs.existsSync(instrumentedDir) &&
1165
+ walkFiles(instrumentedDir, [".kt"]).length > 0;
1166
+ if (!hasSources) {
1167
+ return {
1168
+ name: "androidChecks",
1169
+ verdict: "SKIP",
1170
+ reason: "no instrumented tests (composeApp/src/androidInstrumentedTest has no Kotlin sources)",
1171
+ durationMs: Date.now() - started,
1172
+ };
1173
+ }
1174
+ if (!deviceAttached()) {
1175
+ return {
1176
+ name: "androidChecks",
1177
+ verdict: "SKIP",
1178
+ reason: "no Android device/emulator attached (adb) — instrumented behavior needs the real process boundary",
1179
+ durationMs: Date.now() - started,
1180
+ };
1181
+ }
1182
+ // Machine-global lease before the first device touch (contention = SKIP).
1183
+ const leaseSkip = leaseDeviceForStep("androidChecks");
1184
+ if (leaseSkip) return { ...leaseSkip, durationMs: Date.now() - started };
1185
+ // Settle before Gradle's own install+drive: earlier lane steps (tokenDrift's
1186
+ // port-forwards, e2eSmoke's reinstall) can leave the transport stale — see settleAdb.
1187
+ settleAdb();
1188
+ // `--rerun` for the same evidence-integrity reason as stepUnitTests: the receipt must
1189
+ // attest tests that EXECUTED on this tree, never a replayed up-to-date verdict.
1190
+ const res = shGradle(`${GRADLEW} :composeApp:connectedDebugAndroidTest --rerun --console=plain`);
1191
+ const summary = junitSummary(path.join(ROOT, "composeApp/build/outputs/androidTest-results/connected"));
1192
+ return {
1193
+ name: "androidChecks",
1194
+ verdict: res.ok ? "PASS" : "FAIL",
1195
+ reason: res.ok
1196
+ ? undefined
1197
+ : `connectedDebugAndroidTest failed (${summary ? `${summary.failures + summary.errors} of ${summary.tests} tests` : "see output"}) — an on-device behavior claim is broken. Fix the behavior, not the test:\n${res.out.split("\n").filter((l) => /FAILED|error:|failed/i.test(l)).slice(0, 12).join("\n")}`,
1198
+ durationMs: Date.now() - started,
1199
+ details: summary ?? undefined,
1200
+ };
1201
+ }
1202
+
1203
+ // Release-APK smoke — the behavior half of stepReleaseBuild. assembleRelease proves R8
1204
+ // and the build graph COMPILE; two real bugs were only findable by *running* the release
1205
+ // variant (R8 behavior differs from debug). Installs the release APK and drives the same
1206
+ // Maestro smoke flow against it. Ship-time cost by design: this step exists only in the
1207
+ // `release` profile, never per-change.
1208
+ //
1209
+ // Honesty notes, both deliberate:
1210
+ // - A template-fresh app has NO release signingConfig (the keystore belongs to whoever
1211
+ // ships), and an unsigned APK cannot be installed. That is a SKIP naming what to
1212
+ // configure, never a FAIL — a fresh scaffold must not red-bar on a keystore it was
1213
+ // never given.
1214
+ // - This step reinstalls NOTHING afterwards: the release build stays on the device,
1215
+ // which is the honest state ("what is installed is what was last proven"). The next
1216
+ // debug install over it will hit INSTALL_FAILED_UPDATE_INCOMPATIBLE (release and debug
1217
+ // signatures differ) — run `adb uninstall <applicationId>` first; the same applies in
1218
+ // reverse here, so that raw Gradle error is translated into the actionable message.
1219
+ function stepReleaseSmoke() {
1220
+ const guard = maestroGuards("releaseSmoke");
1221
+ if (guard) return guard;
1222
+
1223
+ let gradleText = "";
1224
+ try {
1225
+ gradleText = fs.readFileSync(path.join(ROOT, "composeApp/build.gradle.kts"), "utf8");
1226
+ } catch {
1227
+ gradleText = "";
1228
+ }
1229
+ const applicationId = gradleText.match(/applicationId\s*=\s*"([^"]+)"/)?.[1] ?? "<applicationId>";
1230
+ if (!/signingConfig/.test(gradleText)) {
1231
+ return {
1232
+ name: "releaseSmoke",
1233
+ verdict: "SKIP",
1234
+ reason:
1235
+ "release APK is unsigned — no signingConfig in composeApp/build.gradle.kts. To enable the release smoke: create a keystore (keytool -genkeypair), declare android.signingConfigs { create(\"release\") { … } } from a gitignored keystore.properties, and set buildTypes.release.signingConfig. The keystore is yours to keep out of the repo.",
1236
+ durationMs: 0,
1237
+ };
1238
+ }
1239
+
1240
+ // Machine-global lease before the first device touch (contention = SKIP).
1241
+ // After the signing check on purpose: an unsigned template SKIPs on the
1242
+ // keystore without ever needing the device.
1243
+ const leaseSkip = leaseDeviceForStep("releaseSmoke");
1244
+ if (leaseSkip) return leaseSkip;
1245
+
1246
+ const install = shGradle(`${GRADLEW} :composeApp:installRelease --console=plain`);
1247
+ if (!install.ok) {
1248
+ if (/INSTALL_FAILED_UPDATE_INCOMPATIBLE/.test(install.out)) {
1249
+ return {
1250
+ name: "releaseSmoke",
1251
+ verdict: "FAIL",
1252
+ reason: `installRelease refused: the device holds a build with a different signature (usually the debug build from an earlier lane step). Android never installs across signatures — run \`adb uninstall ${applicationId}\` and re-run the release profile. This is a device-state conflict, not a build defect.`,
1253
+ durationMs: install.durationMs,
1254
+ };
1255
+ }
1256
+ if (/SigningConfig|not signed|INSTALL_PARSE_FAILED_NO_CERTIFICATES/i.test(install.out)) {
1257
+ return {
1258
+ name: "releaseSmoke",
1259
+ verdict: "SKIP",
1260
+ reason: "release APK is not installable — signing is not fully configured (see composeApp/build.gradle.kts signingConfigs). Configure a release keystore to enable the release smoke.",
1261
+ durationMs: install.durationMs,
1262
+ };
1263
+ }
1264
+ return {
1265
+ name: "releaseSmoke",
1266
+ verdict: "FAIL",
1267
+ reason: `installRelease failed — the shippable APK could not be installed:\n${install.out.split("\n").filter((l) => /error|FAILURE|INSTALL_/i.test(l)).slice(0, 12).join("\n")}`,
1268
+ durationMs: install.durationMs,
1269
+ };
1270
+ }
1271
+ settleAdb();
1272
+ return runMaestroSmoke("releaseSmoke", install.durationMs);
1273
+ }
1274
+
1275
+ // ── Audit cadence (roadmap §10 item 9) — a REPORT, never a gate ────────────
1276
+ // cmp-audit (the adversarial platform-semantics audit) found six latent
1277
+ // defects the first time a human happened to ask for it — which is exactly
1278
+ // why it must not depend on someone remembering to ask. This step is the
1279
+ // cheapest honest replacement for that memory: at ship time (release
1280
+ // profile) the receipt lists which androidMain subsystems changed since
1281
+ // their last RECORDED audit (qa/audits.jsonl, appended by
1282
+ // node qa/record-audit.mjs). The derivation lives in
1283
+ // qa/lib/audit-cadence.mjs; this step adds only the bookkeeping every step
1284
+ // carries — and by construction it maps every outcome to PASS or SKIP,
1285
+ // never FAIL: audit debt is a judgment call (a rename is not six latent
1286
+ // defects), and a gate here would teach people to game the ledger, which
1287
+ // would destroy the only value it has.
1288
+ function stepAuditCadence() {
1289
+ const started = Date.now();
1290
+ const report = evaluateAuditCadence(ROOT);
1291
+ if (!report.ok) {
1292
+ return { name: "auditCadence", verdict: "SKIP", reason: report.reason, durationMs: Date.now() - started };
1293
+ }
1294
+ return {
1295
+ name: "auditCadence",
1296
+ verdict: "PASS",
1297
+ note: report.summary,
1298
+ durationMs: Date.now() - started,
1299
+ details: {
1300
+ packageRoot: report.packageRoot,
1301
+ subsystems: report.subsystems.map((s) => ({
1302
+ name: s.name,
1303
+ status: s.status,
1304
+ changedFiles: s.changedFiles,
1305
+ lastAudit: s.audit ? { sha: s.audit.sha, at: s.audit.at, by: s.audit.by } : null,
1306
+ })),
1307
+ lines: report.lines,
1308
+ },
1309
+ };
1310
+ }
1311
+
1312
+ // ── Lane ───────────────────────────────────────────────────────────────────
1313
+
1314
+ // Device-dependent steps, in lane order. Used twice: receipt STRENGTH (which
1315
+ // on-device steps actually PASSed — see below, where the receipt is built) and
1316
+ // the --fast exclusion (with releaseBuild added), so the "device/slow tier"
1317
+ // can never mean two different lists.
1318
+ const DEVICE_STEPS = ["e2eSmoke", "tokenDrift", "androidChecks", "releaseSmoke"];
1319
+
1320
+ // ── Fast-mode memoization of the pure-Node steps (qa/lib/step-cache.mjs) ────
1321
+ // These five steps run no Gradle, shell out to nothing, and are pure functions
1322
+ // of files on disk — so in FAST mode an unchanged input set reuses the last
1323
+ // PASS as verdict "CACHED" (rendered distinctly; only a PASS is ever reused,
1324
+ // a cached FAIL/SKIP always re-runs). THE FULL LANE NEVER CONSULTS THE CACHE —
1325
+ // deliberately: it keeps the integrity property absolute rather than "absolute
1326
+ // unless a cache says otherwise". A full run still WRITES entries so the next
1327
+ // fast run benefits. schemaHistory is NOT here even though it runs no Gradle:
1328
+ // it shells out to git and its verdict depends on HEAD state, not only file
1329
+ // bytes — memoizing it on a content hash could go silently stale.
1330
+ //
1331
+ // Each input set is the step's ACTUAL read surface, over-declared where cheap
1332
+ // (a too-broad set only costs cache misses; a too-narrow one is a
1333
+ // silently-stale gate — the worst possible bug here):
1334
+ // specCoverage reads specs/*.spec.md + citations under composeApp/src
1335
+ // and qa/e2e (qa/lib/spec-coverage.mjs)
1336
+ // approvals reads qa/approvals.json + every governed artifact file:
1337
+ // specs/, docs/features/, docs/ARCHITECTURE.md, and the
1338
+ // exemplar/theme/components Kotlin under composeApp/src
1339
+ // (qa/lib/approvals.mjs listGovernedArtifacts)
1340
+ // componentStories reads commonMain presentation/components and desktopMain
1341
+ // inspector sources — both under composeApp/src
1342
+ // reachability reads commonMain Kotlin (composeApp/src) + the unrouted
1343
+ // declarations in docs/features/
1344
+ // archDoc reads docs/ARCHITECTURE.md, docs/adr/, specs/intent.md
1345
+ // (over-declared to all of specs/), and every source-set's
1346
+ // Kotlin under composeApp/src (qa/lib/arch-doc.mjs)
1347
+ const MEMOIZED_STEP_INPUTS = {
1348
+ specCoverage: ["specs", "composeApp/src", "qa/e2e"],
1349
+ approvals: ["qa/approvals.json", "specs", "docs/features", "docs/ARCHITECTURE.md", "composeApp/src"],
1350
+ componentStories: ["composeApp/src"],
1351
+ reachability: ["composeApp/src", "docs/features"],
1352
+ archDoc: ["docs/ARCHITECTURE.md", "docs/adr", "specs", "composeApp/src"],
1353
+ };
1354
+
1355
+ const memoized = (stepName, stepFn) => () =>
1356
+ memoizeStep({ fast, root: ROOT, stepName, inputs: MEMOIZED_STEP_INPUTS[stepName], run: stepFn });
1357
+
1358
+ const stepSpecCoverageMemo = memoized("specCoverage", stepSpecCoverage);
1359
+ const stepApprovalsMemo = memoized("approvals", stepApprovals);
1360
+ const stepComponentStoriesMemo = memoized("componentStories", stepComponentStories);
1361
+ const stepReachabilityMemo = memoized("reachability", stepReachability);
1362
+ const stepArchDocMemo = memoized("archDoc", stepArchDoc);
1363
+
1364
+ const stepsForProfile = {
1365
+ // scaffold: what `create-cmp --verify` proves at stamp time — specCoverage,
1366
+ // the full JVM tier (unit + conformance + golden + UI tests) plus the Android build.
1367
+ scaffold: [stepHarnessIntegrity, stepSpecCoverageMemo, stepApprovalsMemo, stepComponentStoriesMemo, stepReachabilityMemo, stepArchDocMemo, stepSchemaHistory, stepBuild, stepUnitTests],
1368
+ local: [
1369
+ // First, always: every verdict below is only worth what the lane issuing
1370
+ // it is worth.
1371
+ stepHarnessIntegrity,
1372
+ stepSpecCoverageMemo,
1373
+ stepApprovalsMemo,
1374
+ stepComponentStoriesMemo,
1375
+ stepReachabilityMemo,
1376
+ stepArchDocMemo,
1377
+ stepSchemaHistory,
1378
+ stepBuild,
1379
+ // Release stays OUT of `scaffold`: stamp-time --verify promises a green first build, and
1380
+ // an R8 pass would add minutes to every scaffold to re-prove what this step proves here.
1381
+ // local + ci is where release rot gets caught before it reaches anyone.
1382
+ stepReleaseBuild,
1383
+ stepUnitTests,
1384
+ stepConformance,
1385
+ stepGoldenTrees,
1386
+ stepTokenDrift,
1387
+ stepA11y,
1388
+ stepE2eSmoke,
1389
+ // androidChecks joins local BY the file's own convention, not despite it: local's
1390
+ // contract (see USAGE) is "everything; device-dependent steps SKIP when no device is
1391
+ // attached" — device presence is the opt-in, exactly as e2eSmoke and tokenDrift
1392
+ // already work. A developer with no device attached pays nothing here; one who
1393
+ // attached an emulator has already opted into the device tier's cost. Hiding this
1394
+ // step in ci-only would make local's documented contract a lie and re-open the gap
1395
+ // this tier closes (androidMain test-invisible in the profile people actually run).
1396
+ // Last on purpose: the cheap desktop verdicts and the smoke land first.
1397
+ stepAndroidChecks,
1398
+ ],
1399
+ };
1400
+ // ci = local + the determinism probe's row — the first place ci diverges
1401
+ // from local. The probe is OPT-IN (the step SKIPs unless --determinism was
1402
+ // passed: it doubles the JVM test tier's cost), but its row lives in the ci
1403
+ // profile so a ci receipt always records whether the probe ran — an honest,
1404
+ // visible gap beats an invisible one ("SKIPs are recorded so the pipeline
1405
+ // stays honest", per the profile's own contract). local deliberately does
1406
+ // NOT carry the row: the per-change developer profile is not where a
1407
+ // deliberate double-run belongs.
1408
+ stepsForProfile.ci = [...stepsForProfile.local, stepDeterminism];
1409
+ // release = everything ci proves PLUS the audit-cadence report and the
1410
+ // release-APK behavior smoke. The expensive proofs are profile-tiered by
1411
+ // decision: per-change stays fast (local/ci pay for the release COMPILE via
1412
+ // releaseBuild, already in the set), and the release-variant *behavior* cost
1413
+ // lands once, at ship time. auditCadence (a report, never a gate) also
1414
+ // belongs to ship time — "what moved in androidMain since its last
1415
+ // adversarial audit?" is the question asked before shipping, not per edit.
1416
+ // releaseSmoke runs last so the device ends the run holding the exact build
1417
+ // that was proven.
1418
+ stepsForProfile.release = [...stepsForProfile.ci, stepAuditCadence, stepReleaseSmoke];
1419
+
1420
+ if (!stepsForProfile[profile]) {
1421
+ console.error(`Unknown profile "${profile}" — use scaffold | local | ci | release.`);
1422
+ process.exit(2);
1423
+ }
1424
+
1425
+ // ── Bare --determinism: the probe, nothing else, and NO receipt ─────────────
1426
+ // "Run it alone" means alone: no other steps, and deliberately no
1427
+ // qa/evidence/latest.json. The done-gate (qa/receipt-check.mjs) validates a
1428
+ // receipt by verdict + content hash — a receipt whose steps are one probe
1429
+ // would satisfy it while attesting almost nothing, so a probe-only run must
1430
+ // never mint one. The lane marker IS still stamped: the probe runs Gradle
1431
+ // and owes the preview daemon the same coexistence courtesy as the lane.
1432
+ if (determinism && !profileExplicit) {
1433
+ fs.mkdirSync(path.dirname(LANE_MARKER), { recursive: true });
1434
+ fs.writeFileSync(LANE_MARKER, `${process.pid} ${new Date().toISOString()}\n`);
1435
+ let probe;
1436
+ try {
1437
+ probe = stepDeterminism();
1438
+ } finally {
1439
+ fs.rmSync(LANE_MARKER, { force: true });
1440
+ }
1441
+ if (asJson) {
1442
+ console.log(JSON.stringify(probe, null, 2));
1443
+ } else {
1444
+ const mark = probe.verdict === "PASS" ? "✓" : "✗";
1445
+ console.log(`${mark} determinism: ${probe.verdict}${probe.note ? ` (${probe.note})` : ""}${probe.reason ? ` — ${probe.reason}` : ""}`);
1446
+ console.log("\n(probe-only run — no receipt written; the full lane is where evidence is earned)");
1447
+ }
1448
+ process.exit(probe.verdict === "FAIL" ? 1 : 0);
1449
+ }
1450
+
1451
+ // ── --fast: the inner loop, mechanically unable to claim done ───────────────
1452
+ // The genuinely slow tier is device/release work — every DEVICE_STEPS entry
1453
+ // (Gradle install + emulator + Maestro + instrumented runner) plus
1454
+ // releaseBuild (R8 + lintVital, the slow release COMPILE). --fast filters
1455
+ // that tier out of whatever profile resolved, UNCONDITIONALLY — device
1456
+ // attached or not — so a small change gets its did-I-break-anything-obvious
1457
+ // signal in JVM time. The rest of the profile still runs — but cheaply: the
1458
+ // pure-Node steps reuse an unchanged PASS from the step cache (CACHED — see
1459
+ // the memoization block above), the Gradle test steps drop --rerun (see
1460
+ // RERUN above), and unitTests scopes itself to the working-tree change
1461
+ // (see stepUnitTests). The loophole is closed at the receipt, not by
1462
+ // convention: mode "fast" is
1463
+ // recorded, no evidence rung is derived (qa/lib/evidence-level.mjs), and
1464
+ // qa/receipt-check.mjs refuses a fast receipt as done evidence.
1465
+ const FAST_EXCLUDED_NAMES = [...DEVICE_STEPS, "releaseBuild"];
1466
+ const STEP_FN_BY_NAME = {
1467
+ e2eSmoke: stepE2eSmoke,
1468
+ tokenDrift: stepTokenDrift,
1469
+ androidChecks: stepAndroidChecks,
1470
+ releaseSmoke: stepReleaseSmoke,
1471
+ releaseBuild: stepReleaseBuild,
1472
+ };
1473
+ for (const name of FAST_EXCLUDED_NAMES) {
1474
+ if (!STEP_FN_BY_NAME[name]) {
1475
+ // Drift guard: a new device-tier step must be mapped here or --fast would silently run it.
1476
+ console.error(`internal: fast-excluded step "${name}" has no entry in STEP_FN_BY_NAME — fix qa/verify.mjs`);
1477
+ process.exit(2);
1478
+ }
1479
+ }
1480
+ const FAST_EXCLUDED_FNS = new Set(FAST_EXCLUDED_NAMES.map((name) => STEP_FN_BY_NAME[name]));
1481
+ const laneSteps = fast
1482
+ ? stepsForProfile[profile].filter((fn) => !FAST_EXCLUDED_FNS.has(fn))
1483
+ : stepsForProfile[profile];
1484
+ const fastExcluded = fast
1485
+ ? FAST_EXCLUDED_NAMES.filter((name) => stepsForProfile[profile].includes(STEP_FN_BY_NAME[name]))
1486
+ : [];
1487
+
1488
+ if (fast) {
1489
+ console.error(
1490
+ [
1491
+ "⚡⚡ FAST MODE — INNER LOOP ONLY, NOT THE DONE-GATE ⚡⚡",
1492
+ ` skipping the device/release tier: ${fastExcluded.join(", ") || "(none in this profile)"}`,
1493
+ ' this run\'s receipt records mode "fast", earns no evidence rung, and can NEVER satisfy "done"',
1494
+ " run the full lane once (node qa/verify.mjs) before you finish",
1495
+ ].join("\n"),
1496
+ );
1497
+ }
1498
+
1499
+ // Stamp the lane marker for the run's duration (coexistence defense 1 above);
1500
+ // always removed, even on a failing step, so the eyes only ever defer briefly.
1501
+ fs.mkdirSync(path.dirname(LANE_MARKER), { recursive: true });
1502
+ fs.writeFileSync(LANE_MARKER, `${process.pid} ${new Date().toISOString()}\n`);
1503
+ const laneStartedAt = Date.now(); // for the flight-recorder entry's durationMs
1504
+ const steps = [];
1505
+ try {
1506
+ for (const step of laneSteps) {
1507
+ const result = step();
1508
+ steps.push(result);
1509
+ if (!asJson) {
1510
+ // CACHED (fast mode only — see the memoization block above) renders with
1511
+ // its own mark and "unchanged since" note so a reused verdict is never
1512
+ // mistakable for a fresh execution.
1513
+ const mark = result.verdict === "PASS" ? "✓" : result.verdict === "CACHED" ? "⚡" : result.verdict === "SKIP" ? "→" : "✗";
1514
+ console.log(`${mark} ${result.name}: ${result.verdict}${result.note ? ` (${result.note})` : ""}${result.reason ? ` — ${result.reason.split("\n")[0]}` : ""}`);
1515
+ }
1516
+ if (result.name === "build" && result.verdict === "FAIL") break; // nothing downstream is meaningful
1517
+ }
1518
+ } finally {
1519
+ fs.rmSync(LANE_MARKER, { force: true });
1520
+ // The device lease (if a device step took it) is held to the very end of the
1521
+ // run — see the scope decision at leaseDeviceForStep. Release is idempotent
1522
+ // and never deletes a foreign holder's lease.
1523
+ if (laneDeviceLease) releaseDeviceLease(laneDeviceLease);
1524
+ }
1525
+
1526
+ // CACHED counts as PASS for the lane verdict (it IS a prior PASS, reused only
1527
+ // in fast mode on an unchanged input set) — but it stays CACHED on the
1528
+ // receipt, visibly distinct, so a fast receipt can never be read as if every
1529
+ // step freshly executed.
1530
+ const verdict = steps.some((s) => s.verdict === "FAIL") ? "FAIL" : "PASS";
1531
+
1532
+ // Receipt STRENGTH — a desktop-only green and an on-device green are different
1533
+ // claims, and the difference should never live only in the SKIP lines. Device-
1534
+ // dependent steps that actually RAN (PASSed) are named on the receipt and in the
1535
+ // verdict line: "PASS (on-device: e2eSmoke)" vs "PASS (desktop-only)".
1536
+ // (DEVICE_STEPS itself is defined above the lane — it also drives --fast.)
1537
+ const onDeviceSteps = steps.filter((s) => DEVICE_STEPS.includes(s.name) && s.verdict === "PASS").map((s) => s.name);
1538
+ const strengthLabel = onDeviceSteps.length ? `on-device: ${onDeviceSteps.join("+")}` : "desktop-only";
1539
+
1540
+ // Receipt RUNG — the evidence ladder (qa/lib/evidence-level.mjs): the coarse,
1541
+ // named grade (L0 scaffold / L1 desktop / L2 device / L3 release) DERIVED from
1542
+ // which steps actually ran and PASSed. The strength string above stays as the
1543
+ // fine print; the rung is added alongside, never in place of it. null on FAIL —
1544
+ // a failed lane has no rung. null on a --fast run too: the inner loop is a
1545
+ // signal, never evidence, so a fast receipt derives NO rung at all.
1546
+ const level = evidenceLevel(steps, profile, { mode });
1547
+
1548
+ // Artifacts: hash whatever the run left under qa-artifacts/ (never committed).
1549
+ const artifacts = [];
1550
+ if (fs.existsSync(ARTIFACTS_DIR)) {
1551
+ const walk = (dir) => {
1552
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1553
+ const p = path.join(dir, entry.name);
1554
+ if (entry.isDirectory()) walk(p);
1555
+ else artifacts.push({ path: path.relative(ROOT, p), sha256: createHash("sha256").update(fs.readFileSync(p)).digest("hex") });
1556
+ }
1557
+ };
1558
+ walk(ARTIFACTS_DIR);
1559
+ artifacts.sort((a, b) => a.path.localeCompare(b.path));
1560
+ }
1561
+
1562
+ // Bind the receipt to the content of the verified surface (ADR-0005), NOT the
1563
+ // parent SHA (rebase/merge-fragile). Must be computed before latest.json is
1564
+ // written — the receipt is an output and must never hash itself.
1565
+ /**
1566
+ * The receipt's harness summary — compact by design. The per-file detail lives
1567
+ * on the harnessIntegrity step; this is the part a receipt-holder needs to
1568
+ * identify the lane, plus the names of any modified files (an auditor told
1569
+ * "not intact" and not told which files has been given a rumour, not a fact).
1570
+ */
1571
+ function harnessForReceipt() {
1572
+ const row = steps.find((st) => st.name === "harnessIntegrity");
1573
+ const r = row?.harness ?? checkHarnessIntegrity(ROOT);
1574
+ const summary = {
1575
+ name: r.name,
1576
+ version: r.version,
1577
+ sha256: r.sha256,
1578
+ status: r.status,
1579
+ intact: r.status === "intact",
1580
+ };
1581
+ if (r.status === "modified") {
1582
+ summary.modified = r.modified;
1583
+ summary.missing = r.missing;
1584
+ summary.extra = r.extra;
1585
+ }
1586
+ return summary;
1587
+ }
1588
+
1589
+ const inputs = computeInputsHash(ROOT);
1590
+
1591
+ // The receipt. Deterministic key order; ONE volatile timestamp field.
1592
+ // commit.sha is the parent HEAD at run time (you cannot know the sha of the
1593
+ // commit the receipt will be part of); commit.dirty lists what was uncommitted.
1594
+ const receipt = {
1595
+ schema: "cmp-evidence/1",
1596
+ profile,
1597
+ // "full" is the done-gate; "fast" (--fast) excluded the device/release tier
1598
+ // and is REFUSED by qa/receipt-check.mjs — a fast run can never end a session
1599
+ // as "done". Receipts predating this field are treated as full.
1600
+ mode,
1601
+ verdict,
1602
+ commit: {
1603
+ sha: tryGit("rev-parse HEAD"),
1604
+ dirty: tryGitLines("status --porcelain").map((l) => l.slice(3)).sort(),
1605
+ },
1606
+ inputs: {
1607
+ hash: inputs.hash,
1608
+ fileCount: inputs.fileCount,
1609
+ },
1610
+ steps,
1611
+ // WHICH LANE issued this verdict. A receipt that cannot name its own harness
1612
+ // can only be checked against the tree it came from; naming the version and
1613
+ // the region digest lets a third party who holds the receipt ask the harder
1614
+ // question — was this the real published lane? — without the tree at all.
1615
+ //
1616
+ // `intact` is the LOCAL claim only: unmodified since installed. It is a
1617
+ // checksum, not a signature, and someone who edits the lane can edit this
1618
+ // too. What they cannot edit is what the registry published under that
1619
+ // version, which is why `version` + `sha256` travel together.
1620
+ harness: harnessForReceipt(),
1621
+ strength: { onDeviceSteps },
1622
+ evidenceLevel: level,
1623
+ artifacts,
1624
+ toolVersions: {
1625
+ node: process.version,
1626
+ platform: `${process.platform}-${process.arch}`,
1627
+ },
1628
+ generatedAt: new Date().toISOString(),
1629
+ };
1630
+
1631
+ fs.mkdirSync(EVIDENCE_DIR, { recursive: true });
1632
+ fs.writeFileSync(path.join(EVIDENCE_DIR, "latest.json"), `${JSON.stringify(receipt, null, 2)}\n`);
1633
+ // latest.json is the single receipt-of-record. Commit it with your change: the
1634
+ // studio console's Evidence audit trail reconstructs the full history from the
1635
+ // git log of this file — every commit is one verified, attributed state.
1636
+
1637
+ // The README's evidence badge is DERIVED from the receipt just written — an
1638
+ // output, never a gate, so it runs after the verdict and cannot change it. It
1639
+ // renders the rung together with the commit it was attested against, so the
1640
+ // sentence stays true as the tree moves on (qa/lib/evidence-badge.mjs).
1641
+ const badge = updateReadmeBadge(ROOT);
1642
+
1643
+ // ── Flight recorder (roadmap §10 item 5) — the lane journals its own run ────
1644
+ // One JSON line per run into qa/flight-recorder.jsonl (committed, and
1645
+ // excluded from the receipt's hashed surface — qa/lib/flight-recorder.mjs
1646
+ // carries the whole rationale). Appended AFTER the receipt so the entry
1647
+ // records the final verdict and rung. A failed append must never fail the
1648
+ // lane — a recorder that breaks the thing it observes is worse than no
1649
+ // recorder — so the failure degrades to a note in the lane's own output,
1650
+ // which is itself the honest record of the degradation.
1651
+ //
1652
+ // --no-journal is the ONE exemption, and qa/watch.mjs passes it on every
1653
+ // save-triggered run. Same rule the README badge obeys, for the same reason:
1654
+ // THE INNER LOOP DOES NOT WRITE TO COMMITTED FILES. A watcher journaling every
1655
+ // save would add hundreds of lines a day to a committed file — turning the
1656
+ // app's history into keystroke noise and leaving a permanently-dirty tree in
1657
+ // the loop the recorder exists to observe. What survives is every full lane
1658
+ // and every DELIBERATE fast run, which is what the retrospective's questions
1659
+ // actually rest on (SKIP reasons, degraded paths, the longest stretch with no
1660
+ // full lane). qa/retrospective.mjs discloses the exemption in its own output
1661
+ // so the fast-vs-full ratio is never read as a complete census.
1662
+ const flight = noJournal
1663
+ ? { ok: true, skipped: true }
1664
+ : appendFlightRecord(
1665
+ ROOT,
1666
+ buildFlightEntry({
1667
+ profile,
1668
+ mode,
1669
+ verdict,
1670
+ evidenceLevel: level,
1671
+ steps,
1672
+ sha: receipt.commit.sha,
1673
+ durationMs: Date.now() - laneStartedAt,
1674
+ onDeviceSteps,
1675
+ degraded: DEGRADED_PATHS,
1676
+ }),
1677
+ );
1678
+ if (!flight.ok) {
1679
+ console.error(`· flight recorder: journal append failed (${flight.reason}) — the lane verdict is unaffected, but this run is missing from qa/flight-recorder.jsonl`);
1680
+ }
1681
+
1682
+ if (asJson) {
1683
+ console.log(JSON.stringify(receipt, null, 2));
1684
+ if (fast) {
1685
+ console.error(`⚡⚡ FAST MODE verdict: ${verdict} — INNER LOOP ONLY, not done. Skipped: ${fastExcluded.join(", ") || "(none)"}. Run the full lane (node qa/verify.mjs) before you finish.`);
1686
+ }
1687
+ } else if (fast) {
1688
+ // Deliberately NOT the full lane's verdict-line shape: fast-green must never
1689
+ // be mistakable for done-green.
1690
+ console.log(
1691
+ `\n${verdict === "PASS" ? "⚡⚡" : "❌"} verify lane [FAST — INNER LOOP ONLY, NOT DONE]: ${verdict} (skipped device/release tier: ${fastExcluded.join(", ") || "none"}) — this fast receipt satisfies no done-gate; run the full lane (node qa/verify.mjs) once before you finish`,
1692
+ );
1693
+ } else {
1694
+ console.log(`\n${verdict === "PASS" ? "✅" : "❌"} verify lane: ${verdict}${level ? ` · ${level.rung} ${level.name}` : ""} (${strengthLabel}) — receipt written to qa/evidence/latest.json${badge.changed ? ` and ${README_REL_PATH}'s evidence badge refreshed` : ""} (commit ${badge.changed ? "them" : "it"} with your change)`);
1695
+ }
1696
+
1697
+ // The audit-cadence nudges print in the human path, not only inside the
1698
+ // receipt JSON — a ship-time report that lives only in a JSON field is a
1699
+ // report nobody reads at ship time. Nudges only; a gate this is not.
1700
+ if (!asJson) {
1701
+ const auditStep = steps.find((s) => s.name === "auditCadence");
1702
+ const auditLines = auditStep?.details?.lines ?? [];
1703
+ if (auditLines.length > 0) {
1704
+ console.log("\naudit cadence (report, never a gate):");
1705
+ for (const l of auditLines) console.log(` ${l}`);
1706
+ }
1707
+ }
1708
+
1709
+ process.exit(verdict === "PASS" ? 0 : 1);