create-cmp-cli 0.18.0 → 0.20.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 (42) hide show
  1. package/README.md +3 -3
  2. package/llms.txt +1 -1
  3. package/package.json +1 -1
  4. package/packages/harness/src/approve.mjs +30 -2
  5. package/packages/harness/src/lib/approvals.mjs +74 -10
  6. package/packages/harness/src/lib/evidence-level.mjs +3 -1
  7. package/packages/harness/src/lib/flight-recorder.mjs +47 -2
  8. package/packages/harness/src/lib/inputs-hash.mjs +71 -3
  9. package/packages/harness/src/lib/lane-narrator.mjs +97 -0
  10. package/packages/harness/src/lib/lane-runner.mjs +173 -0
  11. package/packages/harness/src/lib/plan.mjs +286 -20
  12. package/packages/harness/src/lib/receipt-validate.mjs +56 -1
  13. package/packages/harness/src/lib/spec-coverage.mjs +111 -3
  14. package/packages/harness/src/lib/step-cache.mjs +1 -1
  15. package/packages/harness/src/lib/step-outcomes.mjs +123 -0
  16. package/packages/harness/src/lib/steps-cmp.mjs +1284 -0
  17. package/packages/harness/src/lib/walk.mjs +67 -17
  18. package/packages/harness/src/receipt-check.mjs +80 -4
  19. package/packages/harness/src/verify.mjs +119 -1197
  20. package/packages/receipts/src/index.mjs +1 -0
  21. package/packages/receipts/src/inputs-hash.mjs +71 -3
  22. package/packages/receipts/src/receipt-validate.mjs +56 -1
  23. package/template/CLAUDE.md +52 -6
  24. package/template/composeApp/src/desktopTest/kotlin/com/example/app/conformance/ArchitectureConformanceTest.kt +1 -1
  25. package/template/gitignore +3 -0
  26. package/template/qa/approve.mjs +30 -2
  27. package/template/qa/lib/approvals.mjs +74 -10
  28. package/template/qa/lib/evidence-level.mjs +3 -1
  29. package/template/qa/lib/flight-recorder.mjs +47 -2
  30. package/template/qa/lib/inputs-hash.mjs +71 -3
  31. package/template/qa/lib/lane-narrator.mjs +97 -0
  32. package/template/qa/lib/lane-runner.mjs +173 -0
  33. package/template/qa/lib/plan.mjs +286 -20
  34. package/template/qa/lib/receipt-validate.mjs +56 -1
  35. package/template/qa/lib/spec-coverage.mjs +111 -3
  36. package/template/qa/lib/step-cache.mjs +1 -1
  37. package/template/qa/lib/step-outcomes.mjs +123 -0
  38. package/template/qa/lib/steps-cmp.mjs +1284 -0
  39. package/template/qa/lib/walk.mjs +67 -17
  40. package/template/qa/receipt-check.mjs +80 -4
  41. package/template/qa/verify.mjs +119 -1197
  42. package/template/specs/README.md +26 -0
@@ -0,0 +1,1284 @@
1
+ // steps-cmp.mjs — the Compose Multiplatform STEP PACK (evidence-economics S8b).
2
+ //
3
+ // Every step the lane runs against a create-cmp app, behind one factory. The
4
+ // SPINE — argument parsing, the subprocess helper with its deadline, the
5
+ // markers, the runner (qa/lib/lane-runner.mjs), the receipt, the journal —
6
+ // lives in qa/verify.mjs and knows nothing about Gradle, adb, Maestro or
7
+ // composeApp/. THIS file knows nothing about receipts or argv. A Kotlin
8
+ // backend supplies a different pack to the same spine; that is the split
9
+ // payment-blueprint had to re-implement by hand (2,769 lines) because the two
10
+ // were one file.
11
+ //
12
+ // `ctx` is everything the steps borrow from the spine, passed explicitly so
13
+ // the borrowing is visible: the project root, the Gradle wrapper, the
14
+ // `--rerun` suffix, the run's mode flags, the subprocess helpers (sh reads the
15
+ // running step's deadline; shGradle adds the KSP self-heal), git helpers, and
16
+ // the DEGRADED_PATHS list the receipt reports.
17
+ //
18
+ // The bodies below are the lane's own steps, moved verbatim from verify.mjs.
19
+
20
+ import fs from "node:fs";
21
+ import path from "node:path";
22
+ import { compareTokenDrift } from "./token-drift.mjs";
23
+ import { evaluateApprovalsGate } from "./approvals.mjs";
24
+ import { TIERS_SATISFYING, clauseTierCoverage, scanCitations, scanSpecClauses, walkFiles } from "./spec-coverage.mjs";
25
+ import { evaluateComponentStoryParity } from "./component-stories.mjs";
26
+ import { evaluateReachability } from "./reachability.mjs";
27
+ import { memoizeStep } from "./step-cache.mjs";
28
+ import { changedWorkingTreePaths, deriveAffectedFilter } from "./affected-tests.mjs";
29
+ import { acquireDeviceLease, releaseDeviceLease, formatHolder } from "./device-lease.mjs";
30
+ import { ARCH_DOC_REL_PATH, SECTION_IDS, regenerateArchDoc } from "./arch-doc.mjs";
31
+ import { DETERMINISM_TIMEZONES, compareOutcomes, parseJUnitOutcomes } from "./determinism.mjs";
32
+ import { evaluateAuditCadence } from "./audit-cadence.mjs";
33
+ import { androidChecksOutcome } from "./step-outcomes.mjs";
34
+ import { checkHarnessIntegrity, describeIntegrity, LOCK_PATH } from "./harness-lock.mjs";
35
+
36
+ /**
37
+ * @param {object} ctx
38
+ * @param {string} ctx.ROOT project root
39
+ * @param {string} ctx.HERE the qa/ directory
40
+ * @param {string} ctx.GRADLEW the wrapper invocation
41
+ * @param {string} ctx.RERUN " --rerun" in full mode, "" in fast
42
+ * @param {boolean} ctx.fast
43
+ * @param {boolean} ctx.determinism
44
+ * @param {string} ctx.profile
45
+ * @param {"full"|"fast"} ctx.mode
46
+ * @param {Function} ctx.sh subprocess helper (throws StepTimeout past the step's deadline)
47
+ * @param {Function} ctx.shGradle sh + the KSP-collision self-heal
48
+ * @param {Function} ctx.tryGit
49
+ * @param {Function} ctx.tryGitLines
50
+ * @param {string[]} ctx.DEGRADED_PATHS degraded-path activations the receipt reports
51
+ * @returns {{stepsForProfile: Record<string, Function[]>, DEVICE_STEPS: string[],
52
+ * FAST_EXCLUDED_NAMES: string[], STEP_FN_BY_NAME: Record<string, Function>,
53
+ * stepDeterminism: Function, releaseLease: () => void}}
54
+ */
55
+ export function createCmpSteps(ctx) {
56
+ const { ROOT, HERE, GRADLEW, RERUN, fast, determinism, profile, mode, sh, shGradle, tryGit, tryGitLines, DEGRADED_PATHS } = ctx;
57
+
58
+ // Recursive: desktopTest writes TEST-*.xml flat, but connected (instrumented) results
59
+ // land one directory level down per device (build/outputs/androidTest-results/connected/
60
+ // debug/<device>/TEST-*.xml) — both shapes are summarized by the same walk.
61
+ function junitSummary(dir) {
62
+ if (!fs.existsSync(dir)) return null;
63
+ let tests = 0, failures = 0, errors = 0, skipped = 0;
64
+ const walk = (d) => {
65
+ for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
66
+ const p = path.join(d, entry.name);
67
+ if (entry.isDirectory()) {
68
+ walk(p);
69
+ continue;
70
+ }
71
+ if (!entry.name.startsWith("TEST-") || !entry.name.endsWith(".xml")) continue;
72
+ const xml = fs.readFileSync(p, "utf8");
73
+ const m = xml.match(/<testsuite[^>]*tests="(\d+)"[^>]*skipped="(\d+)"[^>]*failures="(\d+)"[^>]*errors="(\d+)"/);
74
+ if (m) {
75
+ tests += Number(m[1]);
76
+ skipped += Number(m[2]);
77
+ failures += Number(m[3]);
78
+ errors += Number(m[4]);
79
+ }
80
+ }
81
+ };
82
+ walk(dir);
83
+ return { tests, failures, errors, skipped };
84
+ }
85
+
86
+ function deviceAttached() {
87
+ const res = sh("adb devices", { timeout: 10_000 });
88
+ if (!res.ok) return false;
89
+ return res.out.split("\n").slice(1).some((l) => /\tdevice$/.test(l.trim().replace(/\s+/g, "\t")));
90
+ }
91
+
92
+ // ── The machine-global device lease (qa/lib/device-lease.mjs) ───────────────
93
+ // LANE_MARKER above is per-PROJECT; the device is machine-GLOBAL. A scratch app
94
+ // in /tmp and the real app each stamp their own marker and still share the one
95
+ // emulator — nothing stopped two lanes (or a lane and a live console session)
96
+ // driving it at once, which is the observed wedged-adbd / `device offline` /
97
+ // crossed-app-state failure class. Every device-touching step below takes the
98
+ // lease before touching the device.
99
+ //
100
+ // SCOPE DECISION — once per run, not per step: the lease is acquired lazily by
101
+ // the FIRST device step that actually reaches the device and held until the
102
+ // lane exits (released in the same `finally` as LANE_MARKER). A single run must
103
+ // not thrash acquire/release between adjacent device steps, and holding through
104
+ // the desktop steps interleaved among them (a11y sits between tokenDrift and
105
+ // e2eSmoke) costs nothing — nothing else should drive the device mid-lane
106
+ // anyway, which is the whole point.
107
+ //
108
+ // ON CONTENTION THE STEP RETURNS SKIP — NEVER FAIL: nothing is broken; another
109
+ // run legitimately holds the device. This composes with the evidence ladder
110
+ // (qa/lib/evidence-level.mjs): a SKIPped device step simply does not buy its
111
+ // rung, so contention visibly DEGRADES the evidence level (L2 falls back to L1)
112
+ // instead of corrupting the run with a false red — that degradation being
113
+ // honest and visible is exactly why SKIP is the right verdict.
114
+ let laneDeviceLease = null;
115
+
116
+ /** Serials of devices currently in `device` state (same parse as deviceAttached). */
117
+ function attachedDeviceSerials() {
118
+ const res = sh("adb devices", { timeout: 10_000 });
119
+ if (!res.ok) return [];
120
+ return res.out
121
+ .split("\n")
122
+ .slice(1)
123
+ .map((l) => l.trim())
124
+ .filter(Boolean)
125
+ .map((l) => l.split(/\s+/))
126
+ .filter(([, state]) => state === "device")
127
+ .map(([serial]) => serial);
128
+ }
129
+
130
+ /**
131
+ * Acquire (or confirm) the lane's device lease for a device step.
132
+ * Returns null when the lane holds the device; otherwise the SKIP result the
133
+ * step should return verbatim. The serial leased is the one the lane will
134
+ * actually drive: the single attached device, or ANDROID_SERIAL when several
135
+ * are attached (adb/Gradle/Maestro honor the same variable). Ambiguity is
136
+ * SKIPped by name — leasing a guess would protect the wrong device.
137
+ */
138
+ function leaseDeviceForStep(stepName) {
139
+ if (laneDeviceLease) return null; // already held for this run
140
+ const serials = attachedDeviceSerials();
141
+ if (serials.length === 0) return null; // each step's own guard SKIPs "no device" with its precise reason
142
+ let serial = serials[0];
143
+ if (serials.length > 1) {
144
+ const chosen = process.env.ANDROID_SERIAL;
145
+ if (chosen && serials.includes(chosen)) {
146
+ serial = chosen;
147
+ } else {
148
+ return {
149
+ name: stepName,
150
+ verdict: "SKIP",
151
+ 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.`,
152
+ durationMs: 0,
153
+ };
154
+ }
155
+ }
156
+ const res = acquireDeviceLease({ serial, holder: `verify lane ${stepName}`, root: ROOT });
157
+ if (!res.ok) {
158
+ return {
159
+ name: stepName,
160
+ verdict: "SKIP",
161
+ reason: `device ${serial} is held by ${formatHolder(res.heldBy)} — device evidence is batched, not concurrent; wait for it or run once when it finishes`,
162
+ durationMs: 0,
163
+ };
164
+ }
165
+ if (res.reclaimed) {
166
+ console.error(`· reclaimed a dead device lease on ${serial} (was ${formatHolder(res.reclaimed)})`);
167
+ }
168
+ laneDeviceLease = res.handle;
169
+ return null;
170
+ }
171
+
172
+ // Settle adb before handing the device to whatever drives it next (Maestro, the
173
+ // instrumented runner). An install task returning 0 means the package manager accepted
174
+ // the APK — NOT that the device is ready to be driven: a reinstall over a running app
175
+ // briefly drops the emulator's adb transport. `adb devices` still says `device`, but a
176
+ // fresh adb client (Maestro's dadb, Gradle's ddmlib) gets `device offline` and dies
177
+ // before the first assertion (observed 4/4 when the live-inspector tier ran earlier in
178
+ // the lane — its port-forward traffic widens the window — and 0/4 when it was skipped).
179
+ // wait-for-device blocks only while the transport is actually down; the kill/start pair
180
+ // ahead of it clears a stale server-side transport entry that survives the device coming
181
+ // back. Neither weakens any assertion — every downstream check still passes on its own
182
+ // merits.
183
+ function settleAdb() {
184
+ sh("adb kill-server");
185
+ sh("adb start-server");
186
+ sh("adb wait-for-device");
187
+ }
188
+
189
+ // ── Steps ──────────────────────────────────────────────────────────────────
190
+ // Each returns { name, verdict, reason?, durationMs, details? }. Failure
191
+ // reasons are worded for an AI collaborator to act on.
192
+
193
+ // Spec ↔ test drift gate — pure Node, no Gradle. The clause/citation scan
194
+ // itself lives in qa/lib/spec-coverage.mjs — the SAME scan feature-brief.mjs
195
+ // derives doneness from, so this gate and the Features view can never disagree
196
+ // about a clause. This step owns only the orphan decision + bookkeeping.
197
+ // The first question any verdict depends on: is the lane that is about to
198
+ // issue it the lane this app was given?
199
+ //
200
+ // Without this the receipt is unfalsifiable in one specific way — edit
201
+ // qa/verify.mjs to force every step PASS and the receipt still validates,
202
+ // because the edited file is simply part of the hashed input surface. Hashing
203
+ // the machine-owned region against qa/harness.lock.json closes that: the lane
204
+ // cannot vouch for itself while modified.
205
+ //
206
+ // DELIBERATELY NOT MEMOIZED. Every other pure-Node step can serve a cached
207
+ // PASS when its inputs are unchanged; a cached PASS on an integrity check is
208
+ // precisely the failure it exists to prevent, and 34 file reads are too cheap
209
+ // to be worth the risk.
210
+ //
211
+ // Three states, three verdicts:
212
+ // intact PASS
213
+ // modified FAIL — named files, with the command that restores them
214
+ // unlocked SKIP — an app stamped before locks existed. Nothing is known to
215
+ // be wrong, but nothing is proven either; recording the gap keeps
216
+ // the pipeline honest instead of quietly passing.
217
+ function stepHarnessIntegrity() {
218
+ const started = Date.now();
219
+ const r = checkHarnessIntegrity(ROOT);
220
+ const base = { name: "harnessIntegrity", durationMs: Date.now() - started, harness: r };
221
+
222
+ if (r.status === "intact") {
223
+ return { ...base, verdict: "PASS", note: describeIntegrity(r) };
224
+ }
225
+ if (r.status === "unlocked") {
226
+ return {
227
+ ...base,
228
+ verdict: "SKIP",
229
+ reason: `no ${LOCK_PATH} — this app was stamped before harness locks existed. ` +
230
+ "`npx create-cmp-cli upgrade --harness` records one.",
231
+ };
232
+ }
233
+
234
+ const named = [
235
+ ...r.modified.map((f) => `modified ${f}`),
236
+ ...r.missing.map((f) => `missing ${f}`),
237
+ ...r.extra.map((f) => `unrecorded ${f}`),
238
+ ];
239
+ return {
240
+ ...base,
241
+ verdict: "FAIL",
242
+ reason:
243
+ `the verify lane has been modified since it was installed — ${describeIntegrity(r)}. ` +
244
+ "Lane code is machine-owned: it is byte-identical in every create-cmp app and carries " +
245
+ "no app content, so a local edit is either an accident, a half-applied upgrade, or an " +
246
+ "attempt to make this receipt say something the lane would not. Restore it with " +
247
+ "`npx create-cmp-cli upgrade --harness`, which also reports any genuine local patch " +
248
+ "instead of discarding it.",
249
+ files: named,
250
+ };
251
+ }
252
+
253
+ function stepSpecCoverage() {
254
+ const started = Date.now();
255
+ const specsDir = path.join(ROOT, "specs");
256
+ if (!fs.existsSync(specsDir)) {
257
+ return { name: "specCoverage", verdict: "SKIP", reason: "no specs/ directory in this project", durationMs: Date.now() - started };
258
+ }
259
+
260
+ const clauses = scanSpecClauses(ROOT);
261
+ const tags = scanCitations(ROOT);
262
+ const searchDirs = [path.join(ROOT, "composeApp/src"), path.join(ROOT, "qa/e2e")];
263
+ const files = searchDirs.flatMap((d) => walkFiles(d, [".kt", ".kts", ".yaml", ".yml"]));
264
+
265
+ const citedIds = new Set(tags.map((t) => t.id));
266
+ const orphanClauses = [...clauses.entries()].filter(([, c]) => !c.withdrawn).filter(([id]) => !citedIds.has(id));
267
+ const orphanTags = tags.filter((t) => !clauses.has(t.id) || clauses.get(t.id).withdrawn);
268
+
269
+ const tiers = clauseTierCoverage(clauses, tags);
270
+
271
+ if (orphanClauses.length === 0 && orphanTags.length === 0 && tiers.unmetTier.length === 0) {
272
+ // Tier visibility, still not a gate for UNDECLARED clauses (industry rule:
273
+ // instrument before you police). A clause cited only from desktop-tier tests can
274
+ // still hide a platform-behavior bug — both production apps shipped
275
+ // alarm/notification defects behind clauses that were "covered" by JVM tests
276
+ // androidMain never ran under. The line names them; the instrumented seam
277
+ // (androidChecks) is where such clauses earn a citation.
278
+ //
279
+ // A clause that DECLARED `[tier: …]` is policed above — that is the second move
280
+ // this note's first move was always waiting for.
281
+ return {
282
+ name: "specCoverage",
283
+ verdict: "PASS",
284
+ durationMs: Date.now() - started,
285
+ details: {
286
+ clauses: [...clauses.values()].filter((c) => !c.withdrawn).length,
287
+ withdrawn: [...clauses.values()].filter((c) => c.withdrawn).length,
288
+ tags: tags.length,
289
+ files: files.length,
290
+ tierNote: tiers.summaryLine,
291
+ },
292
+ };
293
+ }
294
+
295
+ const lines = ["Spec coverage broken — the spec and the tests have drifted apart:"];
296
+ // The competence check, first: an existing-but-blind citation is a subtler
297
+ // failure than a missing one, and its message has to say WHY the citation it
298
+ // can see does not count.
299
+ for (const u of tiers.unmetTier) {
300
+ const has = u.tiers.length ? `cited only from ${u.tiers.join(", ")}` : "cited by nothing";
301
+ lines.push(
302
+ ` [${u.id}] ${u.file} — declares [tier: ${u.requiredTier}] but is ${has}. ` +
303
+ `A test on those tiers cannot observe this promise (no process lifecycle, no OS facts, no real device). ` +
304
+ `Add a citing test in ${TIERS_SATISFYING[u.requiredTier].join(" or ")} — and note that tier SKIPPING for want of a device ` +
305
+ `leaves this clause unproven, which is the point: "I could not check this" is a failure, not a quieter rung.`,
306
+ );
307
+ }
308
+ for (const [id, c] of orphanClauses) {
309
+ 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).`);
310
+ }
311
+ for (const t of orphanTags) {
312
+ const known = clauses.get(t.id);
313
+ if (known?.withdrawn) {
314
+ 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.`);
315
+ } else {
316
+ 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.`);
317
+ }
318
+ }
319
+
320
+ return {
321
+ name: "specCoverage",
322
+ verdict: "FAIL",
323
+ reason: lines.join("\n"),
324
+ durationMs: Date.now() - started,
325
+ details: {
326
+ clauses: [...clauses.values()].filter((c) => !c.withdrawn).length,
327
+ withdrawn: [...clauses.values()].filter((c) => c.withdrawn).length,
328
+ tags: tags.length,
329
+ files: files.length,
330
+ },
331
+ };
332
+ }
333
+
334
+ // Human-approval gate (VERIFICATION-LAYER-DESIGN.md §2) — pure Node, no Gradle,
335
+ // same grouping as specCoverage. The decision itself lives in
336
+ // qa/lib/approvals.mjs (evaluateApprovalsGate); this step only adds the
337
+ // name/duration bookkeeping every step in this file carries.
338
+ function stepApprovals() {
339
+ const started = Date.now();
340
+ const { verdict, reason, statuses } = evaluateApprovalsGate(ROOT);
341
+ return {
342
+ name: "approvals",
343
+ verdict,
344
+ reason,
345
+ durationMs: Date.now() - started,
346
+ details: { artifacts: statuses.map((s) => ({ id: s.id, status: s.status, hash: s.hash })) },
347
+ };
348
+ }
349
+
350
+ // There is deliberately NO feature-doneness step here (CHANGE-FLOW-DESIGN.md
351
+ // §7): a feature's doneness is DERIVED from gates this lane already runs —
352
+ // specCoverage fails an uncited clause, the test steps fail a broken promise,
353
+ // and the receipt's inputs.hash attests the tree. A second mechanism would be
354
+ // a second truth.
355
+
356
+ // Component ↔ story parity gate (STUDIO-REDESIGN.md §3.3) — pure Node, no
357
+ // Gradle, same grouping as specCoverage/approvals. The decision itself lives
358
+ // in qa/lib/component-stories.mjs (evaluateComponentStoryParity); this step
359
+ // only adds the name/duration bookkeeping every step in this file carries.
360
+ function stepComponentStories() {
361
+ const started = Date.now();
362
+ const { verdict, reason, details } = evaluateComponentStoryParity(ROOT);
363
+ return { name: "componentStories", verdict, reason, durationMs: Date.now() - started, details };
364
+ }
365
+
366
+ // Navigation-reachability gate (task FI-7, docs/AUTONOMY-GAPS.md §3) — pure
367
+ // Node, no Gradle, same grouping as specCoverage/approvals/componentStories.
368
+ // The decision itself lives in qa/lib/reachability.mjs (evaluateReachability);
369
+ // this step only adds the name/duration bookkeeping every step in this file
370
+ // carries. Closes the exact hole a real feature slipped through: every other
371
+ // gate PASSed while its screen was wired into nothing.
372
+ function stepReachability() {
373
+ const started = Date.now();
374
+ const { verdict, reason, details } = evaluateReachability(ROOT);
375
+ return { name: "reachability", verdict, reason, durationMs: Date.now() - started, details };
376
+ }
377
+
378
+ // Architecture-doc freshness gate (Wave B, docs/proposals/architecture-document-
379
+ // standard.md §6) — pure Node, no Gradle, same grouping as specCoverage/
380
+ // approvals. The decision itself lives in qa/lib/arch-doc.mjs
381
+ // (regenerateArchDoc); this step only adds the name/duration bookkeeping every
382
+ // step in this file carries, plus wording the FAIL reason for an AI
383
+ // collaborator (name the stale/missing section, name the fix command).
384
+ function stepArchDoc() {
385
+ const started = Date.now();
386
+ const elapsed = () => Date.now() - started;
387
+
388
+ const result = regenerateArchDoc(ROOT);
389
+ if (!result.ok) {
390
+ return { name: "archDoc", verdict: "SKIP", reason: `${result.reason} — nothing to check`, durationMs: elapsed() };
391
+ }
392
+ if (result.unknownSections.length > 0) {
393
+ return {
394
+ name: "archDoc",
395
+ verdict: "FAIL",
396
+ 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.`,
397
+ durationMs: elapsed(),
398
+ };
399
+ }
400
+
401
+ const stale = result.changed || result.missingSections.length > 0;
402
+ if (!stale) {
403
+ return { name: "archDoc", verdict: "PASS", durationMs: elapsed(), details: { sectionsChecked: SECTION_IDS.length } };
404
+ }
405
+
406
+ const lines = [`${ARCH_DOC_REL_PATH} is stale — a generated section no longer matches the tree:`];
407
+ for (const id of result.changedSections) {
408
+ lines.push(` [${id}] regenerating would change this section.`);
409
+ }
410
+ for (const id of result.missingSections) {
411
+ lines.push(` [${id}] marker missing from the doc entirely — never generated.`);
412
+ }
413
+ lines.push("Run: node qa/arch-doc.mjs");
414
+ return {
415
+ name: "archDoc",
416
+ verdict: "FAIL",
417
+ reason: lines.join("\n"),
418
+ durationMs: elapsed(),
419
+ details: { changedSections: result.changedSections, missingSections: result.missingSections },
420
+ };
421
+ }
422
+
423
+ // Schema-history gate — pure Node + git, no Gradle, same grouping as the other
424
+ // evidence checks. Room's exportSchema writes one <version>.json per database per
425
+ // target under composeApp/schemas/. Every version EXCEPT the current highest is a
426
+ // frozen historical record of a database that shipped: migrations are written and
427
+ // validated against those exact bytes, so a regeneration that rewrites them
428
+ // silently corrupts the baseline every future migration is proven against. Only
429
+ // the highest version is the live, in-progress schema — free to change or appear
430
+ // (that IS the current change). This gate exists because schema regeneration
431
+ // looks like harmless build output right up until a shipped user's upgrade fails.
432
+ function stepSchemaHistory() {
433
+ const started = Date.now();
434
+ const elapsed = () => Date.now() - started;
435
+ const schemasRel = path.join("composeApp", "schemas");
436
+ const schemasRoot = path.join(ROOT, schemasRel);
437
+
438
+ if (!fs.existsSync(schemasRoot)) {
439
+ return { name: "schemaHistory", verdict: "SKIP", reason: "no exported Room schemas (composeApp/schemas/ absent) — nothing frozen to guard", durationMs: elapsed() };
440
+ }
441
+ const gitTop = tryGit("rev-parse --show-toplevel");
442
+ if (!gitTop || !tryGit("rev-parse HEAD")) {
443
+ return { name: "schemaHistory", verdict: "SKIP", reason: "no git history yet — schema versions have no committed baseline to be frozen against", durationMs: elapsed() };
444
+ }
445
+
446
+ // Every directory holding versioned schema JSONs, with its highest version on disk.
447
+ const versionFile = /^(\d+)\.json$/;
448
+ const maxVersionByDir = new Map(); // absolute dir path -> highest N among its N.json files
449
+ const walkSchemas = (dir) => {
450
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
451
+ const p = path.join(dir, entry.name);
452
+ if (entry.isDirectory()) walkSchemas(p);
453
+ else {
454
+ const m = entry.name.match(versionFile);
455
+ if (m) maxVersionByDir.set(dir, Math.max(maxVersionByDir.get(dir) ?? 0, Number(m[1])));
456
+ }
457
+ }
458
+ };
459
+ walkSchemas(schemasRoot);
460
+
461
+ // Tracked schema files whose committed bytes no longer match the tree (staged or
462
+ // unstaged; deletions included). Paths come back relative to the git toplevel.
463
+ // Untracked files never appear here — a brand-new version file is by definition
464
+ // not yet frozen history.
465
+ const dirtyFiles = tryGitLines(`diff --name-only HEAD -- "${schemasRel.replace(/\\/g, "/")}"`);
466
+
467
+ const violations = [];
468
+ for (const rel of dirtyFiles) {
469
+ const abs = path.resolve(gitTop, rel);
470
+ const m = path.basename(abs).match(versionFile);
471
+ if (!m) continue; // not a versioned schema JSON
472
+ const version = Number(m[1]);
473
+ const dirMax = maxVersionByDir.get(path.dirname(abs));
474
+ // The highest version currently on disk is the live schema — dirty is fine.
475
+ // Anything else (a lower version, or a file whose whole directory is gone)
476
+ // is rewritten/deleted history.
477
+ if (dirMax !== undefined && version === dirMax) continue;
478
+ violations.push(rel);
479
+ }
480
+
481
+ if (violations.length === 0) {
482
+ return { name: "schemaHistory", verdict: "PASS", durationMs: elapsed(), details: { schemaDirs: maxVersionByDir.size } };
483
+ }
484
+
485
+ const lines = [
486
+ "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:",
487
+ ];
488
+ for (const rel of violations) lines.push(` git checkout -- ${rel}`);
489
+ lines.push("If you intended a schema change, bump the database version so a NEW <version>.json is exported instead of overwriting history.");
490
+ return {
491
+ name: "schemaHistory",
492
+ verdict: "FAIL",
493
+ reason: lines.join("\n"),
494
+ durationMs: elapsed(),
495
+ details: { schemaDirs: maxVersionByDir.size, violations },
496
+ };
497
+ }
498
+
499
+ function stepBuild() {
500
+ const res = shGradle(`${GRADLEW} :composeApp:assembleDebug --console=plain`);
501
+ return {
502
+ name: "build",
503
+ verdict: res.ok ? "PASS" : "FAIL",
504
+ 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")}`,
505
+ durationMs: res.durationMs,
506
+ };
507
+ }
508
+
509
+ // The build nobody runs until the day they need it.
510
+ //
511
+ // assembleDebug passing says nothing about assembleRelease: R8 and `lintVital` only run on
512
+ // the release variant, and BuildConfig is generated PER BUILD TYPE, so a constant declared
513
+ // in one and not the other is a compile error that only release ever sees. All three of
514
+ // those bit this template at once, and none of them were visible from a green debug lane —
515
+ // the first release build ever attempted (2026-07-29) failed three times over.
516
+ //
517
+ // So release is proven at the checkpoint, not discovered at launch. Unsigned: signing needs
518
+ // a keystore, which belongs to whoever ships the app, and this step is about the shrinker
519
+ // and the build graph rather than the signature.
520
+ function stepReleaseBuild() {
521
+ const res = shGradle(`${GRADLEW} :composeApp:assembleRelease --console=plain`);
522
+ return {
523
+ name: "releaseBuild",
524
+ verdict: res.ok ? "PASS" : "FAIL",
525
+ reason: res.ok
526
+ ? undefined
527
+ : `assembleRelease failed — the shippable build is broken even though the debug one is fine:\n${res.out
528
+ .split("\n")
529
+ .filter((l) => /error|FAILURE|Missing class|Unresolved/i.test(l))
530
+ .slice(0, 12)
531
+ .join("\n")}`,
532
+ durationMs: res.durationMs,
533
+ };
534
+ }
535
+
536
+ // Runs a filtered slice of the JVM test tier and names the verdict after the gate it proves.
537
+ // The full suite already ran in unitTests; the filtered slices stay cheap (compilation is
538
+ // cached) while `--rerun` forces the tests themselves to EXECUTE — see stepUnitTests.
539
+ // In fast mode the flag is omitted (RERUN, defined with the mode flags above): the
540
+ // integrity mechanism belongs to the runs that produce integrity-bearing artifacts, and a
541
+ // fast receipt has already declared itself non-evidence.
542
+ function gradleTestStep(name, testsFilter, failHint) {
543
+ // Named explicitly: a function returned from a factory has no inferred name,
544
+ // so the runner narrated conformance / goldenTrees / a11y as null and gave
545
+ // them the default deadline. Same latent class as the memoized wrappers.
546
+ const step = () => {
547
+ const res = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN} --tests "${testsFilter}" --console=plain`);
548
+ return {
549
+ name,
550
+ verdict: res.ok ? "PASS" : "FAIL",
551
+ reason: res.ok
552
+ ? undefined
553
+ : `${failHint}\n${res.out.split("\n").filter((l) => /FAILED|\[(ARCH|SHELL|HOME)-\d+\]|error:/i.test(l)).slice(0, 15).join("\n")}`,
554
+ durationMs: res.durationMs,
555
+ };
556
+ };
557
+ Object.defineProperty(step, "name", { value: `step${name.charAt(0).toUpperCase()}${name.slice(1)}` });
558
+ return step;
559
+ }
560
+
561
+ function stepUnitTests() {
562
+ // `--rerun` is EVIDENCE INTEGRITY, not pedantry: without it, Gradle's build cache can
563
+ // restore a PASS recorded against a *different* tree state (deterministic re-scaffolds
564
+ // produce byte-identical sources, and golden baselines aren't compile inputs), so the
565
+ // receipt would attest tests that never executed. Compilation stays cached — only the
566
+ // test execution is forced. Scoped to FULL mode (see RERUN above): the integrity
567
+ // mechanism belongs to the runs that produce integrity-bearing artifacts, and a fast
568
+ // receipt is already declared non-evidence.
569
+ //
570
+ // Fast mode additionally scopes the suite to tests plausibly affected by the
571
+ // working-tree change (qa/lib/affected-tests.mjs): changed .kt files map to
572
+ // `--tests "*<segment>*"` patterns, with a mandatory blast-radius escape hatch (build
573
+ // files, DI, theme, shared components, qa/, anything outside composeApp/src → full
574
+ // suite) and fail-open on every uncertain case (no git, unmappable change). FALSE
575
+ // NEGATIVES ARE ACCEPTABLE HERE AND ONLY HERE: the full, unfiltered suite runs at the
576
+ // checkpoint (the full lane), where done is actually decided. The filter that ran is
577
+ // reported in the step's note and recorded in the (fast-only) receipt, so a filtered
578
+ // run can never be mistaken for the full suite.
579
+ let note;
580
+ let testsArgs = "";
581
+ let affected = null;
582
+ if (fast) {
583
+ const changed = changedWorkingTreePaths(ROOT);
584
+ if (changed === null) {
585
+ note = "full suite — git unavailable, cannot derive the change (fail open)";
586
+ } else {
587
+ const filter = deriveAffectedFilter(changed);
588
+ if (filter.mode === "filtered") {
589
+ testsArgs = filter.patterns.map((p) => ` --tests "${p}"`).join("");
590
+ note = `affected: ${filter.patterns.join(", ")} — ${filter.sourcePaths.length} changed source file(s)`;
591
+ affected = { patterns: filter.patterns, changedFiles: filter.sourcePaths.length };
592
+ } else {
593
+ note = `full suite — ${filter.reason}`;
594
+ }
595
+ }
596
+ }
597
+ let res = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN}${testsArgs} --console=plain`);
598
+ if (fast && testsArgs && !res.ok && /No tests found for given includes/.test(res.out)) {
599
+ // The heuristic filter matched no test class at all (e.g. a feature with no tests
600
+ // yet). That is the harness's guess being wrong, not the app — fall back to the
601
+ // full suite in-lane rather than false-redding on our own filter. (RERUN is empty
602
+ // here by construction — this branch only exists in fast mode.)
603
+ const retry = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN} --console=plain`);
604
+ retry.durationMs += res.durationMs;
605
+ res = retry;
606
+ note = "full suite — the affected-test filter matched no tests (fell back)";
607
+ affected = null;
608
+ DEGRADED_PATHS.push("affected-test filter matched no tests — fell back to the full desktopTest suite");
609
+ }
610
+ const summary = junitSummary(path.join(ROOT, "composeApp/build/test-results/desktopTest"));
611
+ let details = summary ?? undefined;
612
+ if (affected) details = { ...(summary ?? {}), affected };
613
+ return {
614
+ name: "unitTests",
615
+ verdict: res.ok ? "PASS" : "FAIL",
616
+ reason: res.ok
617
+ ? undefined
618
+ : `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")}`,
619
+ note,
620
+ durationMs: res.durationMs,
621
+ details,
622
+ };
623
+ }
624
+
625
+ const stepConformance = gradleTestStep(
626
+ "conformance",
627
+ "*ArchitectureConformanceTest",
628
+ "Architecture conformance violated (specs/app-base.spec.md ARCH clauses). The failing rule names the clause, files, and fix:",
629
+ );
630
+ const stepGoldenTrees = gradleTestStep(
631
+ "goldenTrees",
632
+ "*GoldenTreeTest",
633
+ "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:",
634
+ );
635
+ const stepA11y = gradleTestStep(
636
+ "a11y",
637
+ "*A11yConformanceTest",
638
+ "A11y gate failed (SHELL-04): interactive nodes must expose a testTag, text, or contentDescription:",
639
+ );
640
+
641
+ // ── Determinism probe (roadmap §10 item 8) — opt-in, ci-profile ────────────
642
+ // ARCH-13 statically bans ambient time reads — in APP code. A library the
643
+ // app calls can still read the wall clock, and a golden can still depend on
644
+ // the machine's timezone through a seam the static net cannot see (a
645
+ // ViewModel constructed without its injected clock already caused one
646
+ // overnight golden-tree drift). This probe closes that gap DYNAMICALLY: it
647
+ // runs the JVM test tier twice, under two timezones whose local calendar
648
+ // dates never agree — the offsets are 26 hours apart, so any date-derived
649
+ // value differs between the legs at every instant (see DETERMINISM_TIMEZONES
650
+ // in qa/lib/determinism.mjs for why UTC-12/UTC+14 and not UTC/UTC+14) — and
651
+ // FAILs naming every test whose outcome differs between the legs.
652
+ //
653
+ // Mechanics that carry the honesty:
654
+ // - TZ reaches the test JVM through the environment: Gradle forwards the
655
+ // client's environment to the daemon on every build, and test workers
656
+ // fork from the daemon — so the child env below is inherited all the way
657
+ // down to the JVM whose default timezone the tests see.
658
+ // - BOTH legs force --rerun. Without it Gradle would mark the second leg
659
+ // up-to-date (TZ is not a declared build input) and replay the first
660
+ // leg's results — the probe would then compare a run against its own
661
+ // echo and certify a determinism it never tested (the build-cache-replay
662
+ // lesson, again). The legs use the mode-scoped RERUN like every other
663
+ // desktopTest invocation — and because --determinism is refused alongside
664
+ // --fast up front, RERUN is always " --rerun" by the time a leg runs.
665
+ // - Only verdicts and failure output are compared; durations are never even
666
+ // parsed (qa/lib/determinism.mjs), so a timing wobble is structurally
667
+ // unable to trip the probe.
668
+ function stepDeterminism() {
669
+ const started = Date.now();
670
+ const elapsed = () => Date.now() - started;
671
+ if (!determinism) {
672
+ return {
673
+ name: "determinism",
674
+ verdict: "SKIP",
675
+ 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",
676
+ durationMs: elapsed(),
677
+ };
678
+ }
679
+
680
+ const resultsDir = path.join(ROOT, "composeApp/build/test-results/desktopTest");
681
+ const legs = [];
682
+ for (const { tz, label } of DETERMINISM_TIMEZONES) {
683
+ const res = shGradle(`${GRADLEW} :composeApp:desktopTest${RERUN} --console=plain`, { env: { ...process.env, TZ: tz } });
684
+ // Parsed NOW, before the next leg overwrites the same results directory.
685
+ const outcomes = parseJUnitOutcomes(resultsDir);
686
+ legs.push({ tz, label, ok: res.ok, outcomes, tail: res.out.split("\n").slice(-8).join("\n") });
687
+ }
688
+ const [a, b] = legs;
689
+ const labelA = `TZ=${a.tz} (${a.label})`;
690
+ const labelB = `TZ=${b.tz} (${b.label})`;
691
+ const countA = Object.keys(a.outcomes).length;
692
+ const countB = Object.keys(b.outcomes).length;
693
+
694
+ if (countA === 0 && countB === 0) {
695
+ // Neither leg produced a single test result: the suite failed before
696
+ // running anything (build error). The probe measured nothing — that is
697
+ // a FAIL that says so, never a PASS by absence of differences.
698
+ return {
699
+ name: "determinism",
700
+ verdict: "FAIL",
701
+ 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}`,
702
+ durationMs: elapsed(),
703
+ };
704
+ }
705
+ if (countA === 0 || countB === 0) {
706
+ const ran = countA > 0 ? { label: labelA, n: countA } : { label: labelB, n: countB };
707
+ const empty = countA > 0 ? b : a;
708
+ return {
709
+ name: "determinism",
710
+ verdict: "FAIL",
711
+ 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}`,
712
+ durationMs: elapsed(),
713
+ details: { timezones: DETERMINISM_TIMEZONES.map((t) => t.tz) },
714
+ };
715
+ }
716
+
717
+ const diffs = compareOutcomes(a.outcomes, b.outcomes, labelA, labelB);
718
+ if (diffs.length > 0) {
719
+ const lines = [
720
+ `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"):`,
721
+ ];
722
+ for (const d of diffs.slice(0, 20)) lines.push(` [${d.step}] ${d.test} — ${d.detail}`);
723
+ if (diffs.length > 20) lines.push(` … and ${diffs.length - 20} more differing test(s)`);
724
+ return {
725
+ name: "determinism",
726
+ verdict: "FAIL",
727
+ reason: lines.join("\n"),
728
+ durationMs: elapsed(),
729
+ details: { timezones: DETERMINISM_TIMEZONES.map((t) => t.tz), diffs: diffs.slice(0, 50) },
730
+ };
731
+ }
732
+
733
+ const failedIdentically = Object.values(a.outcomes).filter((o) => o.status !== "pass" && o.status !== "skip").length;
734
+ return {
735
+ name: "determinism",
736
+ verdict: "PASS",
737
+ // Identical red is DETERMINISTIC red: the probe's claim ("no timezone
738
+ // dependence") holds, and the failing tests already belong to
739
+ // unitTests/goldenTrees, which fail the lane on their own merits — a
740
+ // second FAIL here would report the same defect twice under a wrong name.
741
+ note:
742
+ failedIdentically > 0
743
+ ? `${failedIdentically} test(s) failed identically under both timezones — deterministic, but red (the owning test steps report it)`
744
+ : undefined,
745
+ durationMs: elapsed(),
746
+ details: { timezones: DETERMINISM_TIMEZONES.map((t) => t.tz), testsCompared: countA },
747
+ };
748
+ }
749
+
750
+ // Live tokenDrift tier (harness M4-D): when a debug app + device are available,
751
+ // fetches the declared catalog and the live semantics tree off the debug-only
752
+ // inspector server (127.0.0.1:9500, see composeApp/src/androidDebug/.../
753
+ // InspectorHttpServer.kt) and runs compareTokenDrift() over them — real runtime
754
+ // drift detection, embedded in the evidence receipt.
755
+ //
756
+ // Infrastructure absence (no device, app not running) is NEVER a FAIL — only
757
+ // actual drift is. curl (via the existing synchronous sh() helper) stands in for
758
+ // an HTTP client here because every step in this lane runs synchronously; a
759
+ // couple of short retries cover the debug app's cold start.
760
+ const INSPECTOR_PORT = 9500;
761
+
762
+ function curlJson(url, timeoutSec = 5) {
763
+ const res = sh(`curl -s -m ${timeoutSec} -w "\\n%{http_code}" "${url}"`);
764
+ if (!res.ok) return { ok: false };
765
+ const out = res.out;
766
+ const idx = out.lastIndexOf("\n");
767
+ const code = (idx >= 0 ? out.slice(idx + 1) : "").trim();
768
+ const bodyText = idx >= 0 ? out.slice(0, idx) : "";
769
+ if (code !== "200") return { ok: false };
770
+ try {
771
+ return { ok: true, body: JSON.parse(bodyText) };
772
+ } catch {
773
+ return { ok: false };
774
+ }
775
+ }
776
+
777
+ function pollHealth(port, attempts, delaySec) {
778
+ let health = curlJson(`http://127.0.0.1:${port}/inspect/health`);
779
+ for (let tries = 1; !health.ok && tries < attempts; tries += 1) {
780
+ sh(`sleep ${delaySec}`);
781
+ health = curlJson(`http://127.0.0.1:${port}/inspect/health`);
782
+ }
783
+ return health;
784
+ }
785
+
786
+ function stepTokenDrift() {
787
+ const started = Date.now();
788
+ const elapsed = () => Date.now() - started;
789
+
790
+ if (!deviceAttached()) {
791
+ return {
792
+ name: "tokenDrift",
793
+ verdict: "SKIP",
794
+ reason: "no Android device/emulator attached (adb) — runtime token drift needs the live inspector tier",
795
+ durationMs: elapsed(),
796
+ };
797
+ }
798
+
799
+ const unreachable = () => ({
800
+ name: "tokenDrift",
801
+ verdict: "SKIP",
802
+ reason: "inspector endpoint not reachable on :9500 (debug app not running?) — launch the debug build to enable the live tier",
803
+ durationMs: elapsed(),
804
+ });
805
+
806
+ // Machine-global lease before the first device touch (contention = SKIP).
807
+ const leaseSkip = leaseDeviceForStep("tokenDrift");
808
+ if (leaseSkip) return { ...leaseSkip, durationMs: elapsed() };
809
+
810
+ sh(`adb forward tcp:${INSPECTOR_PORT} tcp:${INSPECTOR_PORT}`);
811
+ try {
812
+ let health = curlJson(`http://127.0.0.1:${INSPECTOR_PORT}/inspect/health`);
813
+ if (!health.ok) {
814
+ // Debug app may not be running — try to launch it (best-effort: parse the
815
+ // applicationId out of the Android build config), then give it a moment
816
+ // to cold-start before giving up.
817
+ let applicationId = null;
818
+ try {
819
+ const gradle = fs.readFileSync(path.join(ROOT, "composeApp/build.gradle.kts"), "utf8");
820
+ applicationId = gradle.match(/applicationId\s*=\s*"([^"]+)"/)?.[1] ?? null;
821
+ } catch {
822
+ applicationId = null;
823
+ }
824
+ if (applicationId) {
825
+ sh(`adb shell am start -n ${applicationId}/.MainActivity`);
826
+ }
827
+ health = pollHealth(INSPECTOR_PORT, 5, 2);
828
+ }
829
+ if (!health.ok) return unreachable();
830
+
831
+ const designSystem = curlJson(`http://127.0.0.1:${INSPECTOR_PORT}/inspect/design-system`);
832
+ const tree = curlJson(`http://127.0.0.1:${INSPECTOR_PORT}/inspect/tree`);
833
+ if (!designSystem.ok || !tree.ok) return unreachable();
834
+
835
+ const { checked, drifted } = compareTokenDrift(designSystem.body, tree.body);
836
+
837
+ if (drifted.length === 0) {
838
+ return {
839
+ name: "tokenDrift",
840
+ verdict: "PASS",
841
+ durationMs: elapsed(),
842
+ details: { checked, drifted: 0 },
843
+ };
844
+ }
845
+
846
+ const lines = ["Runtime token drift — a component's resolved value contradicts the declared design-system catalog:"];
847
+ for (const d of drifted) {
848
+ lines.push(
849
+ ` [${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.`,
850
+ );
851
+ }
852
+ return {
853
+ name: "tokenDrift",
854
+ verdict: "FAIL",
855
+ reason: lines.join("\n"),
856
+ durationMs: elapsed(),
857
+ details: { checked, drifted },
858
+ };
859
+ } finally {
860
+ sh(`adb forward --remove tcp:${INSPECTOR_PORT}`);
861
+ }
862
+ }
863
+
864
+ function maestroAvailable() {
865
+ return sh("maestro --version", { timeout: 15_000 }).ok;
866
+ }
867
+
868
+ // The e2e guard trio, shared by every step that drives the smoke flow on a device.
869
+ // Returns null when the harness is fully available, else the SKIP result for [name].
870
+ function maestroGuards(name) {
871
+ if (!fs.existsSync(path.join(ROOT, "qa/e2e"))) {
872
+ return { name, verdict: "SKIP", reason: "e2e harness not included in this project (--no-e2e)", durationMs: 0 };
873
+ }
874
+ if (!deviceAttached()) {
875
+ return { name, verdict: "SKIP", reason: "no Android device/emulator attached (adb)", durationMs: 0 };
876
+ }
877
+ if (!maestroAvailable()) {
878
+ return { name, verdict: "SKIP", reason: "maestro CLI not installed — curl -fsSL https://get.maestro.mobile.dev | bash", durationMs: 0 };
879
+ }
880
+ return null;
881
+ }
882
+
883
+ // Drives qa/e2e/smoke.yaml against whatever build is installed, with the device hardened
884
+ // for headless/CI automation. Shared by e2eSmoke (debug APK) and releaseSmoke (release
885
+ // APK) so the hardening and the honesty sweep can never drift apart between variants.
886
+ // Without the hardening, a slow or loaded emulator produces false reds that have nothing
887
+ // to do with the app:
888
+ // - hide_error_dialogs=1 stops Android popping ANR/crash dialogs (e.g. SystemUI under load)
889
+ // that steal focus over the app — a Maestro assert would then see only the dialog;
890
+ // - MAESTRO_DRIVER_STARTUP_TIMEOUT gives the UiAutomator2 driver a generous budget to come
891
+ // up on a slow emulator (the built-in default gives up too early under load).
892
+ // Both are benign, reversible, and only touch the device while the lane is driving it —
893
+ // hide_error_dialogs is restored to its pre-run value (or deleted, returning the device
894
+ // to its default) in the finally below, on every exit path.
895
+ // hide_error_dialogs suppresses the OS dialog, NEVER the underlying event — so after the
896
+ // run we grep the device log for ANR/crash lines the dialog would have shown, and FAIL on
897
+ // them. The eyes must report what automation stability had to hide.
898
+ function runMaestroSmoke(name, priorDurationMs) {
899
+ const prevHideErrorDialogs = sh("adb shell settings get global hide_error_dialogs").out.trim();
900
+ sh("adb shell settings put global hide_error_dialogs 1");
901
+ sh("adb logcat -c"); // clear so the post-run dump only reflects this run
902
+ try {
903
+ const res = sh("maestro test qa/e2e/smoke.yaml", { env: { ...process.env, MAESTRO_DRIVER_STARTUP_TIMEOUT: "120000" } });
904
+ if (!res.ok) {
905
+ return {
906
+ name,
907
+ verdict: "FAIL",
908
+ reason: `Maestro smoke failed (flow cites the SHELL spec clauses it proves):\n${res.out.split("\n").slice(-15).join("\n")}`,
909
+ durationMs: priorDurationMs + res.durationMs,
910
+ };
911
+ }
912
+ const anrDump = sh("adb logcat -d -b system,crash,main");
913
+ const anrRe = /ANR in |FATAL EXCEPTION/i;
914
+ if (anrDump.ok && anrRe.test(anrDump.out)) {
915
+ const anrLines = anrDump.out.split("\n").filter((l) => anrRe.test(l)).slice(0, 10).join("\n");
916
+ return {
917
+ name,
918
+ verdict: "FAIL",
919
+ 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}`,
920
+ durationMs: priorDurationMs + res.durationMs,
921
+ };
922
+ }
923
+ return { name, verdict: "PASS", durationMs: priorDurationMs + res.durationMs };
924
+ } finally {
925
+ if (prevHideErrorDialogs && prevHideErrorDialogs !== "null") {
926
+ sh(`adb shell settings put global hide_error_dialogs ${prevHideErrorDialogs}`);
927
+ } else {
928
+ sh("adb shell settings delete global hide_error_dialogs");
929
+ }
930
+ }
931
+ }
932
+
933
+ function stepE2eSmoke() {
934
+ const guard = maestroGuards("e2eSmoke");
935
+ if (guard) return guard;
936
+ // Machine-global lease before the first device touch (contention = SKIP).
937
+ const leaseSkip = leaseDeviceForStep("e2eSmoke");
938
+ if (leaseSkip) return leaseSkip;
939
+ const install = shGradle(`${GRADLEW} :composeApp:installDebug --console=plain`);
940
+ if (!install.ok) {
941
+ return { name: "e2eSmoke", verdict: "FAIL", reason: "installDebug failed — the APK could not be installed on the attached device", durationMs: install.durationMs };
942
+ }
943
+ settleAdb();
944
+ return runMaestroSmoke("e2eSmoke", install.durationMs);
945
+ }
946
+
947
+ // Instrumented behavior tier (composeApp/src/androidInstrumentedTest) — the one step
948
+ // whose evidence crosses the process boundary. Alarms, notification channels,
949
+ // full-screen intents, PendingIntent identity, and audio routing are OS facts:
950
+ // desktopTest is a JVM, golden trees are structure, the conformance suite is static,
951
+ // and the Maestro smoke taps UI without asserting anything about the shade or the
952
+ // alarm table. Nine escaped platform-semantics defects across two real apps trace to
953
+ // exactly this blind spot; the hand-built precursor of this step caught two bugs the
954
+ // week it landed. `connectedDebugAndroidTest` builds, installs, and runs the
955
+ // instrumented suite in the app's real process on the attached device.
956
+ //
957
+ // SKIP (never FAIL) on missing infrastructure — no device, or no instrumented sources
958
+ // yet — mirroring e2eSmoke's stance: absence of the tier is recorded honestly, only
959
+ // broken behavior fails.
960
+ function stepAndroidChecks() {
961
+ const started = Date.now();
962
+ const instrumentedDir = path.join(ROOT, "composeApp/src/androidInstrumentedTest");
963
+ const hasSources = fs.existsSync(instrumentedDir) &&
964
+ walkFiles(instrumentedDir, [".kt"]).length > 0;
965
+ if (!hasSources) {
966
+ return {
967
+ name: "androidChecks",
968
+ verdict: "SKIP",
969
+ reason: "no instrumented tests (composeApp/src/androidInstrumentedTest has no Kotlin sources)",
970
+ durationMs: Date.now() - started,
971
+ };
972
+ }
973
+ if (!deviceAttached()) {
974
+ return {
975
+ name: "androidChecks",
976
+ verdict: "SKIP",
977
+ reason: "no Android device/emulator attached (adb) — instrumented behavior needs the real process boundary",
978
+ durationMs: Date.now() - started,
979
+ };
980
+ }
981
+ // Machine-global lease before the first device touch (contention = SKIP).
982
+ const leaseSkip = leaseDeviceForStep("androidChecks");
983
+ if (leaseSkip) return { ...leaseSkip, durationMs: Date.now() - started };
984
+ // Settle before Gradle's own install+drive: earlier lane steps (tokenDrift's
985
+ // port-forwards, e2eSmoke's reinstall) can leave the transport stale — see settleAdb.
986
+ settleAdb();
987
+ // `--rerun` for the same evidence-integrity reason as stepUnitTests: the receipt must
988
+ // attest tests that EXECUTED on this tree, never a replayed up-to-date verdict.
989
+ const res = shGradle(`${GRADLEW} :composeApp:connectedDebugAndroidTest --rerun --console=plain`);
990
+ const summary = junitSummary(path.join(ROOT, "composeApp/build/outputs/androidTest-results/connected"));
991
+ // Verdict separated from invocation (qa/lib/step-outcomes.mjs): a run that
992
+ // executed zero tests has observed nothing and must not accuse the change.
993
+ const outcome = androidChecksOutcome(res, summary, { gradlew: GRADLEW });
994
+ return {
995
+ name: "androidChecks",
996
+ verdict: outcome.verdict,
997
+ reason: outcome.reason,
998
+ durationMs: Date.now() - started,
999
+ // `executed` rides on the receipt so a reader can tell a red that measured
1000
+ // something from a red that measured nothing. Shape preserved: undefined
1001
+ // when there is no summary AND nothing to add, as before.
1002
+ details: summary ? { ...summary, executed: outcome.executed } : outcome.executed ? undefined : { executed: false },
1003
+ };
1004
+ }
1005
+
1006
+ // Release-APK smoke — the behavior half of stepReleaseBuild. assembleRelease proves R8
1007
+ // and the build graph COMPILE; two real bugs were only findable by *running* the release
1008
+ // variant (R8 behavior differs from debug). Installs the release APK and drives the same
1009
+ // Maestro smoke flow against it. Ship-time cost by design: this step exists only in the
1010
+ // `release` profile, never per-change.
1011
+ //
1012
+ // Honesty notes, both deliberate:
1013
+ // - A template-fresh app has NO release signingConfig (the keystore belongs to whoever
1014
+ // ships), and an unsigned APK cannot be installed. That is a SKIP naming what to
1015
+ // configure, never a FAIL — a fresh scaffold must not red-bar on a keystore it was
1016
+ // never given.
1017
+ // - This step reinstalls NOTHING afterwards: the release build stays on the device,
1018
+ // which is the honest state ("what is installed is what was last proven"). The next
1019
+ // debug install over it will hit INSTALL_FAILED_UPDATE_INCOMPATIBLE (release and debug
1020
+ // signatures differ) — run `adb uninstall <applicationId>` first; the same applies in
1021
+ // reverse here, so that raw Gradle error is translated into the actionable message.
1022
+ function stepReleaseSmoke() {
1023
+ const guard = maestroGuards("releaseSmoke");
1024
+ if (guard) return guard;
1025
+
1026
+ let gradleText = "";
1027
+ try {
1028
+ gradleText = fs.readFileSync(path.join(ROOT, "composeApp/build.gradle.kts"), "utf8");
1029
+ } catch {
1030
+ gradleText = "";
1031
+ }
1032
+ const applicationId = gradleText.match(/applicationId\s*=\s*"([^"]+)"/)?.[1] ?? "<applicationId>";
1033
+ if (!/signingConfig/.test(gradleText)) {
1034
+ return {
1035
+ name: "releaseSmoke",
1036
+ verdict: "SKIP",
1037
+ reason:
1038
+ "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.",
1039
+ durationMs: 0,
1040
+ };
1041
+ }
1042
+
1043
+ // Machine-global lease before the first device touch (contention = SKIP).
1044
+ // After the signing check on purpose: an unsigned template SKIPs on the
1045
+ // keystore without ever needing the device.
1046
+ const leaseSkip = leaseDeviceForStep("releaseSmoke");
1047
+ if (leaseSkip) return leaseSkip;
1048
+
1049
+ const install = shGradle(`${GRADLEW} :composeApp:installRelease --console=plain`);
1050
+ if (!install.ok) {
1051
+ if (/INSTALL_FAILED_UPDATE_INCOMPATIBLE/.test(install.out)) {
1052
+ return {
1053
+ name: "releaseSmoke",
1054
+ verdict: "FAIL",
1055
+ 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.`,
1056
+ durationMs: install.durationMs,
1057
+ };
1058
+ }
1059
+ if (/SigningConfig|not signed|INSTALL_PARSE_FAILED_NO_CERTIFICATES/i.test(install.out)) {
1060
+ return {
1061
+ name: "releaseSmoke",
1062
+ verdict: "SKIP",
1063
+ 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.",
1064
+ durationMs: install.durationMs,
1065
+ };
1066
+ }
1067
+ return {
1068
+ name: "releaseSmoke",
1069
+ verdict: "FAIL",
1070
+ 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")}`,
1071
+ durationMs: install.durationMs,
1072
+ };
1073
+ }
1074
+ settleAdb();
1075
+ return runMaestroSmoke("releaseSmoke", install.durationMs);
1076
+ }
1077
+
1078
+ // ── Audit cadence (roadmap §10 item 9) — a REPORT, never a gate ────────────
1079
+ // cmp-audit (the adversarial platform-semantics audit) found six latent
1080
+ // defects the first time a human happened to ask for it — which is exactly
1081
+ // why it must not depend on someone remembering to ask. This step is the
1082
+ // cheapest honest replacement for that memory: at ship time (release
1083
+ // profile) the receipt lists which androidMain subsystems changed since
1084
+ // their last RECORDED audit (qa/audits.jsonl, appended by
1085
+ // node qa/record-audit.mjs). The derivation lives in
1086
+ // qa/lib/audit-cadence.mjs; this step adds only the bookkeeping every step
1087
+ // carries — and by construction it maps every outcome to PASS or SKIP,
1088
+ // never FAIL: audit debt is a judgment call (a rename is not six latent
1089
+ // defects), and a gate here would teach people to game the ledger, which
1090
+ // would destroy the only value it has.
1091
+ function stepAuditCadence() {
1092
+ const started = Date.now();
1093
+ const report = evaluateAuditCadence(ROOT);
1094
+ if (!report.ok) {
1095
+ return { name: "auditCadence", verdict: "SKIP", reason: report.reason, durationMs: Date.now() - started };
1096
+ }
1097
+ return {
1098
+ name: "auditCadence",
1099
+ verdict: "PASS",
1100
+ note: report.summary,
1101
+ durationMs: Date.now() - started,
1102
+ details: {
1103
+ packageRoot: report.packageRoot,
1104
+ subsystems: report.subsystems.map((s) => ({
1105
+ name: s.name,
1106
+ status: s.status,
1107
+ changedFiles: s.changedFiles,
1108
+ lastAudit: s.audit ? { sha: s.audit.sha, at: s.audit.at, by: s.audit.by } : null,
1109
+ })),
1110
+ lines: report.lines,
1111
+ },
1112
+ };
1113
+ }
1114
+
1115
+ // ── Lane ───────────────────────────────────────────────────────────────────
1116
+
1117
+ // Device-dependent steps, in lane order. Used twice: receipt STRENGTH (which
1118
+ // on-device steps actually PASSed — see below, where the receipt is built) and
1119
+ // the --fast exclusion (with releaseBuild added), so the "device/slow tier"
1120
+ // can never mean two different lists.
1121
+ const DEVICE_STEPS = ["e2eSmoke", "tokenDrift", "androidChecks", "releaseSmoke"];
1122
+
1123
+ // ── Fast-mode memoization of the pure-Node steps (qa/lib/step-cache.mjs) ────
1124
+ // These five steps run no Gradle, shell out to nothing, and are pure functions
1125
+ // of files on disk — so in FAST mode an unchanged input set reuses the last
1126
+ // PASS as verdict "CACHED" (rendered distinctly; only a PASS is ever reused,
1127
+ // a cached FAIL/SKIP always re-runs). THE FULL LANE NEVER CONSULTS THE CACHE —
1128
+ // deliberately: it keeps the integrity property absolute rather than "absolute
1129
+ // unless a cache says otherwise". A full run still WRITES entries so the next
1130
+ // fast run benefits. schemaHistory is NOT here even though it runs no Gradle:
1131
+ // it shells out to git and its verdict depends on HEAD state, not only file
1132
+ // bytes — memoizing it on a content hash could go silently stale.
1133
+ //
1134
+ // Each input set is the step's ACTUAL read surface, over-declared where cheap
1135
+ // (a too-broad set only costs cache misses; a too-narrow one is a
1136
+ // silently-stale gate — the worst possible bug here):
1137
+ // specCoverage reads specs/*.spec.md + citations under composeApp/src
1138
+ // and qa/e2e (qa/lib/spec-coverage.mjs)
1139
+ // approvals reads qa/approvals.json + every governed artifact file:
1140
+ // specs/, docs/features/, docs/ARCHITECTURE.md, and the
1141
+ // exemplar/theme/components Kotlin under composeApp/src
1142
+ // (qa/lib/approvals.mjs listGovernedArtifacts)
1143
+ // componentStories reads commonMain presentation/components and desktopMain
1144
+ // inspector sources — both under composeApp/src
1145
+ // reachability reads commonMain Kotlin (composeApp/src) + the unrouted
1146
+ // declarations in docs/features/
1147
+ // archDoc reads docs/ARCHITECTURE.md, docs/adr/, specs/intent.md
1148
+ // (over-declared to all of specs/), and every source-set's
1149
+ // Kotlin under composeApp/src (qa/lib/arch-doc.mjs)
1150
+ const MEMOIZED_STEP_INPUTS = {
1151
+ specCoverage: ["specs", "composeApp/src", "qa/e2e"],
1152
+ approvals: ["qa/approvals.json", "specs", "docs/features", "docs/ARCHITECTURE.md", "composeApp/src"],
1153
+ componentStories: ["composeApp/src"],
1154
+ reachability: ["composeApp/src", "docs/features"],
1155
+ archDoc: ["docs/ARCHITECTURE.md", "docs/adr", "specs", "composeApp/src"],
1156
+ };
1157
+
1158
+ // The wrapper carries the step's NAME explicitly. An inner arrow returned from
1159
+ // a factory has no inferred name, so the runner's stepDisplayName() read these
1160
+ // as null — the marker narrated "specCoverage" as nothing, and its deadline
1161
+ // fell to the 30-minute default. Latent since drive-narration; surfaced by the
1162
+ // pack's own test the moment names were asserted at runtime rather than in
1163
+ // source.
1164
+ const memoized = (stepName, stepFn) => {
1165
+ const wrapped = () => memoizeStep({ fast, root: ROOT, stepName, inputs: MEMOIZED_STEP_INPUTS[stepName], run: stepFn });
1166
+ Object.defineProperty(wrapped, "name", { value: `step${stepName.charAt(0).toUpperCase()}${stepName.slice(1)}Memo` });
1167
+ return wrapped;
1168
+ };
1169
+
1170
+ const stepSpecCoverageMemo = memoized("specCoverage", stepSpecCoverage);
1171
+ const stepApprovalsMemo = memoized("approvals", stepApprovals);
1172
+ const stepComponentStoriesMemo = memoized("componentStories", stepComponentStories);
1173
+ const stepReachabilityMemo = memoized("reachability", stepReachability);
1174
+ const stepArchDocMemo = memoized("archDoc", stepArchDoc);
1175
+
1176
+ const stepsForProfile = {
1177
+ // scaffold: what `create-cmp --verify` proves at stamp time — specCoverage,
1178
+ // the full JVM tier (unit + conformance + golden + UI tests) plus the Android build.
1179
+ scaffold: [stepHarnessIntegrity, stepSpecCoverageMemo, stepApprovalsMemo, stepComponentStoriesMemo, stepReachabilityMemo, stepArchDocMemo, stepSchemaHistory, stepBuild, stepUnitTests],
1180
+ // smoke (docs/GATE-RULES.md Rule 0, docs/PRINCIPLES.md #2): the smallest
1181
+ // end-to-end lane — every pure-Node step through the REAL runner, marker,
1182
+ // receipt and journal, and NO Gradle, no device, no network. Its job is to
1183
+ // prove the framework RETURNS, fast, in both directions, before any real
1184
+ // work is pointed at it. scripts/framework-check.mjs drives it: PASS on a
1185
+ // fresh scaffold, then FAIL BY NAME on one planted spec edit, each bounded
1186
+ // in seconds. Its receipt is refused as done-evidence (qa/receipt-check.mjs)
1187
+ // exactly like --fast: it proves the instrument, never the change.
1188
+ smoke: [stepHarnessIntegrity, stepSpecCoverageMemo, stepApprovalsMemo, stepComponentStoriesMemo, stepReachabilityMemo, stepArchDocMemo, stepSchemaHistory],
1189
+ local: [
1190
+ // First, always: every verdict below is only worth what the lane issuing
1191
+ // it is worth.
1192
+ stepHarnessIntegrity,
1193
+ stepSpecCoverageMemo,
1194
+ stepApprovalsMemo,
1195
+ stepComponentStoriesMemo,
1196
+ stepReachabilityMemo,
1197
+ stepArchDocMemo,
1198
+ stepSchemaHistory,
1199
+ stepBuild,
1200
+ stepUnitTests,
1201
+ stepConformance,
1202
+ stepGoldenTrees,
1203
+ stepTokenDrift,
1204
+ stepA11y,
1205
+ // Release stays OUT of `scaffold`: stamp-time --verify promises a green first build, and
1206
+ // an R8 pass would add minutes to every scaffold to re-prove what this step proves here.
1207
+ // local + ci is where release rot gets caught before it reaches anyone.
1208
+ //
1209
+ // And it sits AFTER the cheap tier, not before it. The lane runs every step
1210
+ // regardless of failures, so the order costs nothing on a green run — but
1211
+ // ahead of them, a red unit test was reported only once R8 had finished,
1212
+ // which on a real change is minutes of waiting to be told something the JVM
1213
+ // knew in seconds. Cheap high-signal checks report first.
1214
+ stepReleaseBuild,
1215
+ stepE2eSmoke,
1216
+ // androidChecks joins local BY the file's own convention, not despite it: local's
1217
+ // contract (see USAGE) is "everything; device-dependent steps SKIP when no device is
1218
+ // attached" — device presence is the opt-in, exactly as e2eSmoke and tokenDrift
1219
+ // already work. A developer with no device attached pays nothing here; one who
1220
+ // attached an emulator has already opted into the device tier's cost. Hiding this
1221
+ // step in ci-only would make local's documented contract a lie and re-open the gap
1222
+ // this tier closes (androidMain test-invisible in the profile people actually run).
1223
+ // Last on purpose: the cheap desktop verdicts and the smoke land first.
1224
+ stepAndroidChecks,
1225
+ ],
1226
+ };
1227
+ // ci = local + the determinism probe's row — the first place ci diverges
1228
+ // from local. The probe is OPT-IN (the step SKIPs unless --determinism was
1229
+ // passed: it doubles the JVM test tier's cost), but its row lives in the ci
1230
+ // profile so a ci receipt always records whether the probe ran — an honest,
1231
+ // visible gap beats an invisible one ("SKIPs are recorded so the pipeline
1232
+ // stays honest", per the profile's own contract). local deliberately does
1233
+ // NOT carry the row: the per-change developer profile is not where a
1234
+ // deliberate double-run belongs.
1235
+ stepsForProfile.ci = [...stepsForProfile.local, stepDeterminism];
1236
+ // release = everything ci proves PLUS the audit-cadence report and the
1237
+ // release-APK behavior smoke. The expensive proofs are profile-tiered by
1238
+ // decision: per-change stays fast (local/ci pay for the release COMPILE via
1239
+ // releaseBuild, already in the set), and the release-variant *behavior* cost
1240
+ // lands once, at ship time. auditCadence (a report, never a gate) also
1241
+ // belongs to ship time — "what moved in androidMain since its last
1242
+ // adversarial audit?" is the question asked before shipping, not per edit.
1243
+ // releaseSmoke runs last so the device ends the run holding the exact build
1244
+ // that was proven.
1245
+ stepsForProfile.release = [...stepsForProfile.ci, stepAuditCadence, stepReleaseSmoke];
1246
+ // nightly (evidence-economics S6 / proposal P4): the stage for proofs whose cost
1247
+ // scales with the SUITE rather than with the change — the determinism probe
1248
+ // today (forced on above; `--determinism` is implied), and the place any
1249
+ // future mutation / load / chaos step lands, so the placement decision is made
1250
+ // once instead of per expensive step. It proves the harness and the tree's
1251
+ // invariants, not a change: qa/receipt-check.mjs refuses its receipt as
1252
+ // done-evidence, exactly as it refuses --fast. Same step set as ci on purpose —
1253
+ // what differs is what is forced, and what the receipt is allowed to mean.
1254
+ stepsForProfile.nightly = [...stepsForProfile.ci];
1255
+
1256
+ const FAST_EXCLUDED_NAMES = [...DEVICE_STEPS, "releaseBuild"];
1257
+ const STEP_FN_BY_NAME = {
1258
+ e2eSmoke: stepE2eSmoke,
1259
+ tokenDrift: stepTokenDrift,
1260
+ androidChecks: stepAndroidChecks,
1261
+ releaseSmoke: stepReleaseSmoke,
1262
+ releaseBuild: stepReleaseBuild,
1263
+ };
1264
+ for (const name of FAST_EXCLUDED_NAMES) {
1265
+ if (!STEP_FN_BY_NAME[name]) {
1266
+ // Drift guard: a new device-tier step must be mapped here or --fast would silently run it.
1267
+ console.error(`internal: fast-excluded step "${name}" has no entry in STEP_FN_BY_NAME — fix qa/verify.mjs`);
1268
+ process.exit(2);
1269
+ }
1270
+ }
1271
+
1272
+ return {
1273
+ stepsForProfile,
1274
+ DEVICE_STEPS,
1275
+ FAST_EXCLUDED_NAMES,
1276
+ STEP_FN_BY_NAME,
1277
+ stepDeterminism,
1278
+ // The device lease is held to the very end of the run (see the scope
1279
+ // decision above); the spine releases it in the runner's finally.
1280
+ releaseLease: () => {
1281
+ if (laneDeviceLease) releaseDeviceLease(laneDeviceLease);
1282
+ },
1283
+ };
1284
+ }