lecodes-cli 0.20.2 → 1.0.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 (105) hide show
  1. package/README.md +56 -57
  2. package/dist/index.js +5918 -5020
  3. package/package.json +7 -5
  4. package/runtime/materials/decal-relief.mat +12 -1
  5. package/runtime/materials/decal.mat +17 -3
  6. package/runtime/materials/lightmap-baked-lite.mat +6 -1
  7. package/runtime/materials/lightmap-baked.mat +6 -1
  8. package/runtime/materials/lightmap.mat +3 -0
  9. package/runtime/scene-harness.json +1 -1
  10. package/runtime/sdk-types.json +1 -1
  11. package/runtime/web/assets/createViewerLite-DHqTFhWB.js +866 -0
  12. package/runtime/web/assets/{index-BMt7AnC5.js → index-Q06c6oHx.js} +1 -1
  13. package/runtime/web/embed.js +1 -1
  14. package/src/api.ts +1 -302
  15. package/src/cli/args.ts +37 -0
  16. package/src/cli/command.ts +113 -0
  17. package/src/cli/errors.ts +13 -0
  18. package/src/cli/help.ts +133 -0
  19. package/src/cli/index.ts +7 -0
  20. package/src/cli/output.ts +102 -0
  21. package/src/cli/run.ts +106 -0
  22. package/src/commands/{appAndroid.ts → app/android.ts} +451 -42
  23. package/src/commands/{appDesktop.ts → app/desktop.ts} +63 -32
  24. package/src/commands/{appDesktopMac.ts → app/desktopMac.ts} +24 -18
  25. package/src/commands/{appIcon.ts → app/icon.ts} +2 -2
  26. package/src/commands/{app.ts → app/index.ts} +397 -289
  27. package/src/commands/{appShared.ts → app/shared.ts} +30 -39
  28. package/src/commands/{appTemplatesAndroid.ts → app/templates/android.ts} +62 -28
  29. package/src/commands/{appTemplatesGradlew.ts → app/templates/gradlew.ts} +1 -1
  30. package/src/commands/{appTemplates.ts → app/templates/ios.ts} +1 -1
  31. package/src/commands/assets.ts +23 -21
  32. package/src/commands/clone.ts +48 -51
  33. package/src/commands/compile.ts +62 -88
  34. package/src/commands/create.ts +46 -47
  35. package/src/commands/design/comments.ts +361 -0
  36. package/src/commands/design/context.ts +101 -0
  37. package/src/commands/design/index.ts +391 -0
  38. package/src/commands/design/snapshot.ts +134 -0
  39. package/src/commands/{designTemplates.ts → design/templates.ts} +4 -3
  40. package/src/commands/desktop.ts +90 -82
  41. package/src/commands/dev.ts +201 -176
  42. package/src/commands/diff.ts +39 -51
  43. package/src/commands/index.ts +60 -0
  44. package/src/commands/{init.ts → init/index.ts} +199 -191
  45. package/src/commands/install.ts +80 -67
  46. package/src/commands/lightmap.ts +203 -171
  47. package/src/commands/link.ts +87 -94
  48. package/src/commands/login.ts +25 -23
  49. package/src/commands/navmesh.ts +168 -138
  50. package/src/commands/pn.ts +201 -244
  51. package/src/commands/pull.ts +49 -56
  52. package/src/commands/push.ts +48 -54
  53. package/src/commands/render.ts +158 -99
  54. package/src/commands/scene.ts +58 -55
  55. package/src/commands/{shaders.ts → shaders/index.ts} +61 -42
  56. package/src/commands/{shadersNew.ts → shaders/new.ts} +2 -2
  57. package/src/commands/shared.ts +79 -0
  58. package/src/commands/status.ts +22 -26
  59. package/src/commands/test.ts +398 -371
  60. package/src/commands/thumbs.ts +185 -175
  61. package/src/commands/update/index.ts +226 -0
  62. package/src/commands/{types.ts → update/types.ts} +31 -22
  63. package/src/compile/collect.ts +5 -5
  64. package/src/compile/collectLocal.ts +3 -3
  65. package/src/compile/designCompile.ts +3 -3
  66. package/src/compile/headlessBundle.ts +133 -129
  67. package/src/compile/projectCompile.ts +2 -2
  68. package/src/compile/sceneCompile.ts +10 -8
  69. package/src/compile/screenEntry.ts +123 -127
  70. package/src/compile/shaders.ts +3 -3
  71. package/src/dev/androidDev.ts +1 -1
  72. package/src/dev/devServer.ts +3 -3
  73. package/src/dev/webRunner.ts +1 -1
  74. package/src/{cmgenTool.ts → hosts/cmgenTool.ts} +1 -1
  75. package/src/{desktopRenderer.ts → hosts/desktopRenderer.ts} +6 -5
  76. package/src/{desktopScript.ts → hosts/desktopScript.ts} +1 -1
  77. package/src/{distRoot.ts → hosts/distRoot.ts} +9 -5
  78. package/src/{matcTool.ts → hosts/matcTool.ts} +1 -1
  79. package/src/{peerInstall.ts → hosts/peerInstall.ts} +2 -2
  80. package/src/{releases.ts → hosts/releases.ts} +1 -1
  81. package/src/index.ts +32 -480
  82. package/src/platform/api.ts +302 -0
  83. package/src/{browserAuth.ts → platform/browserAuth.ts} +1 -1
  84. package/src/{config.ts → platform/config.ts} +1 -1
  85. package/src/{serverDiff.ts → platform/serverDiff.ts} +3 -3
  86. package/src/{projectEnv.ts → project/env.ts} +33 -2
  87. package/src/{localFiles.ts → project/localFiles.ts} +1 -1
  88. package/src/{manifest.ts → project/manifest.ts} +1 -1
  89. package/src/{project.ts → project/materialize.ts} +2 -2
  90. package/src/project/paths.ts +20 -0
  91. package/src/{textDiff.ts → project/textDiff.ts} +1 -1
  92. package/src/{types.ts → project/types.ts} +0 -0
  93. package/runtime/web/assets/createViewerLite-Ct_PZdof.js +0 -852
  94. package/src/commands/design.ts +0 -846
  95. package/src/commands/update.ts +0 -211
  96. package/src/util.ts +0 -146
  97. /package/src/commands/{projectTemplates.ts → init/templates.ts} +0 -0
  98. /package/src/{lecodes-3d-editor.d.ts → declarations/lecodes-3d-editor.d.ts} +0 -0
  99. /package/src/{lecodes-assets.d.ts → declarations/lecodes-assets.d.ts} +0 -0
  100. /package/src/{lecodes-design.d.ts → declarations/lecodes-design.d.ts} +0 -0
  101. /package/src/{lecodes-renderer.d.ts → declarations/lecodes-renderer.d.ts} +0 -0
  102. /package/src/{qrcode-terminal.d.ts → declarations/qrcode-terminal.d.ts} +0 -0
  103. /package/src/{peers.ts → hosts/peers.ts} +0 -0
  104. /package/src/{designMeta.ts → project/designMeta.ts} +0 -0
  105. /package/src/{ignore.ts → project/ignore.ts} +0 -0
@@ -1,371 +1,398 @@
1
- import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs"
2
- import { dirname, resolve } from "node:path"
3
- import { compileHeadlessBundle } from "../compile/headlessBundle"
4
- import { desktopDefaultViewport, desktopPluginLibraries, resolveDesktopRenderer } from "./appShared"
5
- import { fileScenarioIO, requireRenderer, resolveFixtures, resolveSafeAreaChoice } from "./render"
6
- import { buildBundle } from "./compile"
7
- import { findProjectRoot } from "../manifest"
8
- import { runDesktopRender } from "../desktopRenderer"
9
- import { evaluateDesktopRun, translateScenario } from "../desktopScript"
10
- import { CliError, c, flagBool, flagStr, log, logErr, note, warnErr, type Args } from "../util"
11
-
12
- /*
13
- * `lecodes test` — run the project's headless flow tests (needs the optional `lecodes-renderer`
14
- * package). Two sources, both executed as scenario step lists against a fresh session each:
15
- *
16
- * 1. `tests/*.flow.json` — hand-written scenarios (same schema as `lecodes render --script`:
17
- * tap / type / scroll / wait / expect / screenshot / json steps).
18
- * 2. The design graph: when `design/meta.json` exists, every edge with an `activator` between two
19
- * real screens becomes a flow test — walk to the edge's `from` screen along activator edges
20
- * from the start screen, tap the activator, expect a screen named `to`. This checks the BUILT
21
- * app against the DESIGNED navigation — it requires the app to keep the design's `name`s on
22
- * interactive elements and to name each screen root with its design screen id.
23
- * Edges without an activator (backend-driven) or targeting an `@state` are reported as
24
- * "unverifiable"; edges whose `from` has no activator path (e.g. tab-bar navigation, which is
25
- * a surface, not edges) are "unreachable" — cover those with a hand-written flow file.
26
- *
27
- * A failing step stops its flow and dumps the failing frame (JSON + PNG when @napi-rs/canvas is
28
- * installed) under tests/.artifacts/<flow>/ so a red test explains itself without a rerun.
29
- */
30
-
31
- type DesignEdge = { from: string, to: string, label?: string, activator?: string }
32
- type DesignMeta = { screens?: Record<string, unknown>, edges?: DesignEdge[] }
33
-
34
- type FlowCase = {
35
- name: string
36
- kind: "file" | "flow"
37
- steps: unknown
38
- /** Canned fetch responses for this case's session. File scenarios: their envelope `fixtures`
39
- * (inline or a path). Design flows: the project pack (tests/fixtures.json / --fixtures). */
40
- fixtures?: import("lecodes-renderer/headless").Fixtures
41
- /** Per-file envelope overrides (file scenarios only). */
42
- width?: number
43
- height?: number
44
- settle?: number
45
- device?: string
46
- safeArea?: string
47
- }
48
-
49
- type SkippedFlow = { name: string, reason: string }
50
-
51
- /** Derive flow cases from the design graph. Returns the runnable flows + the ones that can't be
52
- * machine-verified (documented, not failed). */
53
- export const deriveDesignFlows = (meta: DesignMeta, entryScreen: string): { flows: FlowCase[], skipped: SkippedFlow[] } => {
54
- const edges = meta.edges ?? []
55
- const isState = (id: string) => id.includes("@")
56
- const verifiable = edges.filter((e) => e.activator && !isState(e.from) && !isState(e.to))
57
-
58
- // BFS shortest activator-path from the entry screen (over verifiable edges only).
59
- const prev = new Map<string, DesignEdge>()
60
- const visited = new Set<string>([entryScreen])
61
- const queue = [entryScreen]
62
- while (queue.length > 0) {
63
- const at = queue.shift()!
64
- for (const e of verifiable) {
65
- if (e.from !== at || visited.has(e.to)) continue
66
- visited.add(e.to)
67
- prev.set(e.to, e)
68
- queue.push(e.to)
69
- }
70
- }
71
- const pathTo = (screen: string): DesignEdge[] | null => {
72
- if (screen === entryScreen) return []
73
- if (!visited.has(screen)) return null
74
- const hops: DesignEdge[] = []
75
- for (let at = screen; at !== entryScreen; at = hops[0].from) hops.unshift(prev.get(at)!)
76
- return hops
77
- }
78
-
79
- const flows: FlowCase[] = []
80
- const skipped: SkippedFlow[] = []
81
- for (const e of edges) {
82
- const name = `${e.from} —${e.activator ?? "?"}→ ${e.to}`
83
- if (!e.activator) {
84
- skipped.push({ name, reason: "no activator (backend/gesture-driven) — cover it with a tests/*.flow.json" })
85
- continue
86
- }
87
- if (isState(e.from) || isState(e.to)) {
88
- skipped.push({ name, reason: "screen-state edge (@state) — states are runtime conditions, not screens" })
89
- continue
90
- }
91
- const path = pathTo(e.from)
92
- if (path === null) {
93
- skipped.push({ name, reason: `"${e.from}" has no activator path from "${entryScreen}" (tab-bar navigation?) — cover it with a tests/*.flow.json` })
94
- continue
95
- }
96
- // A `fill` precedes every activator tap: submits are commonly disabled until their form is
97
- // filled, and the graph tests NAVIGATION — dummy input satisfies local gates, the fixture pack
98
- // answers what the submit then fetches. A no-op on screens without inputs.
99
- flows.push({
100
- name,
101
- kind: "flow",
102
- steps: [
103
- ...path.flatMap((hop) => [{ fill: {} }, { tap: hop.activator!, expect: { screen: hop.to } }]),
104
- { fill: {} },
105
- { tap: e.activator, expect: { screen: e.to } },
106
- ],
107
- })
108
- }
109
- return { flows, skipped }
110
- }
111
-
112
- const slug = (s: string): string => s.replace(/[^a-zA-Z0-9-_]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "case"
113
-
114
- /** Read one tests/*.flow.json (envelope + steps, or a bare step array). */
115
- const readFlowFile = (abs: string, displayName: string): FlowCase => {
116
- let raw: unknown
117
- try {
118
- raw = JSON.parse(readFileSync(abs, "utf8"))
119
- } catch (e) {
120
- throw new CliError(`Can't read "${displayName}": ${e instanceof Error ? e.message : String(e)}`)
121
- }
122
- if (Array.isArray(raw)) return { name: displayName, kind: "file", steps: raw }
123
- if (typeof raw !== "object" || raw === null || (raw as { steps?: unknown }).steps === undefined) {
124
- throw new CliError(`"${displayName}" must be a JSON object with "steps" (or a bare step array).`)
125
- }
126
- const file = raw as { name?: string, width?: number, height?: number, settle?: number, device?: string, safeArea?: string, fixtures?: Record<string, unknown> | string, steps: unknown }
127
- return {
128
- name: file.name ?? displayName, kind: "file", steps: file.steps,
129
- fixtures: resolveFixtures(file.fixtures, dirname(abs)),
130
- width: file.width, height: file.height, settle: file.settle, device: file.device, safeArea: file.safeArea,
131
- }
132
- }
133
-
134
- export const test = async (args: Args) => {
135
- // --desktop: run every file scenario through the NATIVE host (desktopScript.ts — coordinates
136
- // only, expect.log checked, semantic expects reported skipped). Design-derived flows tap by
137
- // activator NAME, which the host can't resolve, so they stay headless-only.
138
- const desktop = flagBool(args, "desktop")
139
- if (desktop && flagBool(args, "flows")) throw new CliError("--flows needs the headless renderer (design flows tap by name) — drop --desktop.")
140
- // --desktop: ONE renderer decision (host binary + the staged .filamat variant). The root is
141
- // recomputed here because `root` below comes from the headless bundle, which --desktop skips.
142
- let desktopRoot: string
143
- try { desktopRoot = findProjectRoot(process.cwd()) } catch { desktopRoot = process.cwd() }
144
- const desktopRenderer = desktop ? resolveDesktopRenderer(desktopRoot, args) : undefined
145
- const native = desktop ? await buildBundle(args, undefined, { localAssets: true, desktopRenderer }) : null
146
- const headless = desktop ? null : await compileHeadlessBundle(args)
147
- const warnings = headless?.warnings ?? []
148
- const useLocalAssets = headless?.useLocalAssets ?? false
149
- const js = headless?.js ?? ""
150
- let root: string
151
- if (headless) root = headless.root
152
- else { try { root = findProjectRoot(process.cwd()) } catch { root = process.cwd() } }
153
- const renderer = desktop ? null : await requireRenderer()
154
- const nativeFrames = Number(flagStr(args, "frames")) || 60
155
- const fixedDtFlag = flagStr(args, "fixed-dt")
156
- const nativeFixedDt = fixedDtFlag !== undefined ? Number(fixedDtFlag) : 16
157
- if (!Number.isFinite(nativeFixedDt) || nativeFixedDt < 0 || nativeFixedDt > 1000) throw new CliError(`--fixed-dt wants a number of ms (0 = wall clock, max 1000), got "${fixedDtFlag}".`)
158
- // Desktop-only projects (app.json desktop block, no ios/android) run flows desktop-sized.
159
- const projectViewport = desktopDefaultViewport(root)
160
-
161
- const testsDir = resolve(root, flagStr(args, "dir") ?? "tests")
162
- const designMetaPath = resolve(root, flagStr(args, "design-dir") ?? "design", "meta.json")
163
- const asJson = flagBool(args, "json")
164
- const out = asJson ? logErr : log // --json owns stdout; the human report moves to stderr
165
-
166
- // 1. File scenarios: the given paths, or every tests/*.flow.json.
167
- const cases: FlowCase[] = []
168
- if (args._.length > 0) {
169
- for (const given of args._) {
170
- const candidates = [resolve(given), resolve(testsDir, given), resolve(testsDir, `${given}.flow.json`)]
171
- const abs = candidates.find((p) => existsSync(p))
172
- if (!abs) throw new CliError(`No such test: "${given}" (looked in ${testsDir}).`)
173
- cases.push(readFlowFile(abs, given))
174
- }
175
- } else if (existsSync(testsDir)) {
176
- for (const f of readdirSync(testsDir).filter((f) => f.endsWith(".flow.json")).sort()) {
177
- cases.push(readFlowFile(resolve(testsDir, f), f))
178
- }
179
- }
180
-
181
- // The project fixture pack: backing data for the design-derived flows (whose success paths are
182
- // usually backend-gated). `tests/fixtures.json` is picked up automatically; --fixtures overrides
183
- // the path. File scenarios do NOT inherit it — they declare their own via the envelope, so a
184
- // deliberately-offline scenario (error states) stays offline.
185
- const fixturesFlag = flagStr(args, "fixtures")
186
- const defaultPack = resolve(testsDir, "fixtures.json")
187
- const flowFixtures = fixturesFlag !== undefined
188
- ? resolveFixtures(fixturesFlag, ".")
189
- : existsSync(defaultPack) ? resolveFixtures("fixtures.json", testsDir) : undefined
190
-
191
- // 2. Design-graph flows (opt out with --no-flows; --flows runs ONLY these).
192
- const flowsOnly = flagBool(args, "flows")
193
- const wantFlows = !flagBool(args, "no-flows") && args._.length === 0
194
- if (flowsOnly) cases.length = 0
195
- let skipped: SkippedFlow[] = []
196
- let entryScreen: string | null = null
197
- if (desktop && wantFlows && existsSync(designMetaPath)) {
198
- note("Design-derived flows skipped with --desktop (they tap by name; run `lecodes test` headless for them).")
199
- }
200
- if (!desktop && (wantFlows || flowsOnly) && existsSync(designMetaPath)) {
201
- let meta: DesignMeta
202
- try {
203
- meta = JSON.parse(readFileSync(designMetaPath, "utf8")) as DesignMeta
204
- } catch (e) {
205
- throw new CliError(`Can't read ${designMetaPath}: ${e instanceof Error ? e.message : String(e)}`)
206
- }
207
- if ((meta.edges ?? []).length > 0) {
208
- // Probe the app for its start screen — the BFS origin of every derived flow.
209
- note("Probing the start screen…")
210
- const probe = await renderer!.createSession(js, { raster: false, localAssets: useLocalAssets, fixtures: flowFixtures })
211
- entryScreen = probe.screenName()
212
- probe.dispose()
213
- if (entryScreen === null) {
214
- warnErr("Design flows skipped: the app's start screen root has no `name`. Name each screen root with its design screen id (e.g. UIScreen([...], { name: \"login\" })).")
215
- } else {
216
- const derived = deriveDesignFlows(meta, entryScreen)
217
- cases.push(...derived.flows.map((f) => ({ ...f, fixtures: flowFixtures })))
218
- skipped = derived.skipped
219
- }
220
- }
221
- } else if (flowsOnly) {
222
- throw new CliError(`--flows needs a design graph (${designMetaPath} not found).`)
223
- }
224
-
225
- if (cases.length === 0) {
226
- for (const w of warnings) warnErr(w)
227
- throw new CliError(`No tests found. Write tests/*.flow.json scenarios, or draw activator edges in the design board (design/meta.json).`)
228
- }
229
-
230
- // Hard timeout across the whole run (each case is bounded by settles, but a pathological app can
231
- // still spin) — generous per-case allowance, overridable.
232
- const timeoutMs = Number(flagStr(args, "timeout")) || (desktop ? 60000 + cases.length * 60000 : 20000 + cases.length * 10000)
233
- const killer = setTimeout(() => {
234
- warnErr(`Test run timed out after ${timeoutMs}ms (raise --timeout or lower --settle).`)
235
- process.exit(1)
236
- }, timeoutMs)
237
- killer.unref?.()
238
-
239
- const onConsole = flagBool(args, "logs")
240
- ? (level: string, text: string) => logErr(`${c.dim(`[${level}]`)} ${text}`)
241
- : undefined
242
- const artifactsRoot = resolve(root, flagStr(args, "artifacts") ?? resolve(testsDir, ".artifacts"))
243
-
244
- type CaseResult = {
245
- name: string
246
- kind: FlowCase["kind"]
247
- ok: boolean
248
- steps: { desc: string, ok: boolean, error?: string, skipped?: string[] }[]
249
- error?: string
250
- artifacts: string[]
251
- }
252
- const results: CaseResult[] = []
253
-
254
- // Native case runner: each case is its own host process (fresh state, like a fresh session);
255
- // per-step screenshots + the final frame land under the case's artifacts folder.
256
- const runNativeCase = async (kase: FlowCase): Promise<CaseResult> => {
257
- const caseDir = resolve(artifactsRoot, slug(kase.name))
258
- const plan = translateScenario(kase.steps, { outDir: caseDir, headroomFrames: nativeFrames })
259
- for (const st of plan.steps) if (st.screenshot) mkdirSync(dirname(st.screenshot), { recursive: true })
260
- mkdirSync(caseDir, { recursive: true })
261
- const finalPng = resolve(caseDir, "final.png")
262
- const { output } = await runDesktopRender(native!.js, native!.resources, {
263
- renderer: desktopRenderer,
264
- pluginDirs: desktopPluginLibraries(root).dirs,
265
- width: Number(flagStr(args, "width")) || kase.width || projectViewport?.width || 390,
266
- height: Number(flagStr(args, "height")) || kase.height || projectViewport?.height || 844,
267
- frames: plan.frameCap, outPng: finalPng, logs: flagBool(args, "logs"),
268
- timeoutMs: 60000 + plan.steps.length * 5000, script: plan.text, fixedDtMs: nativeFixedDt,
269
- })
270
- const r = evaluateDesktopRun(plan, output)
271
- if (!r.loaded) throw new CliError("This desktop host doesn't support scripted input (CREATOR_SCRIPT). Update it: lecodes desktop update (or point LECODES_DESKTOP_EXE at a newer build).")
272
- return {
273
- name: kase.name, kind: kase.kind, ok: r.ok,
274
- steps: r.steps.map((s) => ({ desc: s.desc, ok: s.ok, error: s.error, skipped: s.skipped.length > 0 ? s.skipped : undefined })),
275
- error: r.ended ? undefined : "the host stopped before the script finished (frame cap / crash)",
276
- artifacts: r.ok ? [] : [finalPng],
277
- }
278
- }
279
-
280
- for (const kase of cases) {
281
- const flagSettle = flagStr(args, "settle")
282
- let result: CaseResult
283
- if (desktop) {
284
- try {
285
- result = await runNativeCase(kase)
286
- } catch (e) {
287
- if (e instanceof CliError && /doesn't support scripted input/.test(e.message)) throw e
288
- result = { name: kase.name, kind: kase.kind, ok: false, steps: [], error: e instanceof Error ? e.message : String(e), artifacts: [] }
289
- }
290
- results.push(result)
291
- reportCase(result)
292
- continue
293
- }
294
- try {
295
- const steps = renderer!.parseScenarioSteps(kase.steps)
296
- // Every case runs in a FRESH session — no state bleeds between flows.
297
- const session = await renderer!.createSession(js, {
298
- width: Number(flagStr(args, "width")) || kase.width || projectViewport?.width || 390,
299
- height: Number(flagStr(args, "height")) || kase.height || projectViewport?.height || 844,
300
- settleMs: flagSettle !== undefined ? Number(flagSettle) : kase.settle,
301
- waitNetwork: flagBool(args, "wait-network"),
302
- localAssets: useLocalAssets,
303
- fixtures: kase.fixtures,
304
- ...resolveSafeAreaChoice(flagStr(args, "safe-area") ?? kase.safeArea, flagStr(args, "device") ?? kase.device),
305
- onConsole,
306
- })
307
- try {
308
- const io = fileScenarioIO(resolve(artifactsRoot, slug(kase.name)))
309
- const outcome = await renderer!.runScenario(session, steps, io)
310
- result = {
311
- name: kase.name, kind: kase.kind, ok: outcome.ok,
312
- steps: outcome.steps.map((s) => ({ desc: s.desc, ok: s.ok, error: s.error })),
313
- artifacts: outcome.failureArtifacts.map((p) => resolve(artifactsRoot, slug(kase.name), p)),
314
- }
315
- } finally {
316
- session.dispose()
317
- }
318
- } catch (e) {
319
- // A malformed scenario / session crash is a failed case, not a dead run.
320
- result = { name: kase.name, kind: kase.kind, ok: false, steps: [], error: e instanceof Error ? e.message : String(e), artifacts: [] }
321
- }
322
- results.push(result)
323
- reportCase(result)
324
- }
325
-
326
- function reportCase(result: CaseResult): void {
327
- const skippedCount = result.steps.reduce((n, s) => n + (s.skipped?.length ?? 0), 0)
328
- if (result.ok) {
329
- out(`${c.green("✓")} ${result.name}${skippedCount > 0 ? c.dim(` (${skippedCount} semantic check${skippedCount === 1 ? "" : "s"} skipped on --desktop)`) : ""}`)
330
- } else {
331
- out(`${c.red("✗")} ${result.name}`)
332
- if (result.error) out(` ${c.red(result.error)}`)
333
- for (const s of result.steps) {
334
- out(s.ok ? c.dim(` ✓ ${s.desc}`) : ` ${c.red(`✗ ${s.desc} — ${s.error}`)}`)
335
- for (const sk of s.skipped ?? []) out(c.dim(` – skipped: ${sk}`))
336
- }
337
- if (result.artifacts.length > 0) out(c.dim(` failing frame: ${result.artifacts.join(", ")}`))
338
- }
339
- }
340
-
341
- for (const w of warnings) warnErr(w)
342
- const passed = results.filter((r) => r.ok).length
343
- const failed = results.length - passed
344
- if (skipped.length > 0) {
345
- out("")
346
- out(c.dim(`Not machine-verifiable (${skipped.length}):`))
347
- for (const s of skipped) out(c.dim(` - ${s.name}: ${s.reason}`))
348
- }
349
- out("")
350
- const flowCount = results.filter((r) => r.kind === "flow").length
351
- const summary = [
352
- `${passed} passed`,
353
- failed > 0 ? c.red(`${failed} failed`) : undefined,
354
- skipped.length > 0 ? `${skipped.length} unverifiable` : undefined,
355
- flowCount > 0 ? c.dim(`(${flowCount} from the design graph${entryScreen ? `, start: ${entryScreen}` : ""})`) : undefined,
356
- ].filter(Boolean).join(", ")
357
- out(failed > 0 ? `${c.red("✗")} ${summary}` : `${c.green("✓")} ${summary}`)
358
-
359
- if (asJson) {
360
- process.stdout.write(JSON.stringify({
361
- ok: failed === 0,
362
- passed, failed,
363
- entryScreen,
364
- cases: results,
365
- unverifiable: skipped,
366
- }, null, 2) + "\n")
367
- }
368
-
369
- clearTimeout(killer)
370
- process.exit(failed > 0 ? 1 : 0)
371
- }
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs"
2
+ import { dirname, resolve } from "node:path"
3
+ import { compileHeadlessBundle } from "../compile/headlessBundle"
4
+ import { desktopDefaultViewport, desktopPluginLibraries, resolveDesktopRenderer } from "./app/shared"
5
+ import { desktopRenderFlags, fileScenarioIO, requireRenderer, resolveFixtures, resolveSafeAreaChoice, viewportFlags } from "./render"
6
+ import { buildBundle } from "./compile"
7
+ import { findProjectRoot } from "../project/manifest"
8
+ import { runDesktopRender } from "../hosts/desktopRenderer"
9
+ import { evaluateDesktopRun, translateScenario } from "../hosts/desktopScript"
10
+ import { CliError, bool, c, defineCommand, log, logErr, note, num, str, warnErr, type FlagValues } from "../cli"
11
+ import { bundleFlags, bundleOptions } from "./shared"
12
+
13
+ /*
14
+ * `lecodes test` — run the project's headless flow tests (needs the optional `lecodes-renderer`
15
+ * package). Two sources, both executed as scenario step lists against a fresh session each:
16
+ *
17
+ * 1. `tests/*.flow.json` — hand-written scenarios (same schema as `lecodes render --script`:
18
+ * tap / type / scroll / wait / expect / screenshot / json steps).
19
+ * 2. The design graph: when `design/meta.json` exists, every edge with an `activator` between two
20
+ * real screens becomes a flow test — walk to the edge's `from` screen along activator edges
21
+ * from the start screen, tap the activator, expect a screen named `to`. This checks the BUILT
22
+ * app against the DESIGNED navigation — it requires the app to keep the design's `name`s on
23
+ * interactive elements and to name each screen root with its design screen id.
24
+ * Edges without an activator (backend-driven) or targeting an `@state` are reported as
25
+ * "unverifiable"; edges whose `from` has no activator path (e.g. tab-bar navigation, which is
26
+ * a surface, not edges) are "unreachable" — cover those with a hand-written flow file.
27
+ *
28
+ * A failing step stops its flow and dumps the failing frame (JSON + PNG when @napi-rs/canvas is
29
+ * installed) under tests/.artifacts/<flow>/ so a red test explains itself without a rerun.
30
+ *
31
+ * `--desktop` runs the file scenarios through the NATIVE host (desktopScript.ts — coordinates only,
32
+ * expect.log checked, semantic expects reported skipped). Design-derived flows tap by activator
33
+ * NAME, which the host can't resolve, so they stay headless-only. The viewport / timing and
34
+ * --desktop flags are `lecodes render`'s own groups.
35
+ */
36
+
37
+ type DesignEdge = { from: string, to: string, label?: string, activator?: string }
38
+ type DesignMeta = { screens?: Record<string, unknown>, edges?: DesignEdge[] }
39
+
40
+ type FlowCase = {
41
+ name: string
42
+ kind: "file" | "flow"
43
+ steps: unknown
44
+ /** Canned fetch responses for this case's session. File scenarios: their envelope `fixtures`
45
+ * (inline or a path). Design flows: the project pack (tests/fixtures.json / --fixtures). */
46
+ fixtures?: import("lecodes-renderer/headless").Fixtures
47
+ /** Per-file envelope overrides (file scenarios only). */
48
+ width?: number
49
+ height?: number
50
+ settle?: number
51
+ device?: string
52
+ safeArea?: string
53
+ }
54
+
55
+ type SkippedFlow = { name: string, reason: string }
56
+
57
+ /** Derive flow cases from the design graph. Returns the runnable flows + the ones that can't be
58
+ * machine-verified (documented, not failed). */
59
+ export const deriveDesignFlows = (meta: DesignMeta, entryScreen: string): { flows: FlowCase[], skipped: SkippedFlow[] } => {
60
+ const edges = meta.edges ?? []
61
+ const isState = (id: string) => id.includes("@")
62
+ const verifiable = edges.filter((e) => e.activator && !isState(e.from) && !isState(e.to))
63
+
64
+ // BFS shortest activator-path from the entry screen (over verifiable edges only).
65
+ const prev = new Map<string, DesignEdge>()
66
+ const visited = new Set<string>([entryScreen])
67
+ const queue = [entryScreen]
68
+ while (queue.length > 0) {
69
+ const at = queue.shift()!
70
+ for (const e of verifiable) {
71
+ if (e.from !== at || visited.has(e.to)) continue
72
+ visited.add(e.to)
73
+ prev.set(e.to, e)
74
+ queue.push(e.to)
75
+ }
76
+ }
77
+ const pathTo = (screen: string): DesignEdge[] | null => {
78
+ if (screen === entryScreen) return []
79
+ if (!visited.has(screen)) return null
80
+ const hops: DesignEdge[] = []
81
+ for (let at = screen; at !== entryScreen; at = hops[0].from) hops.unshift(prev.get(at)!)
82
+ return hops
83
+ }
84
+
85
+ const flows: FlowCase[] = []
86
+ const skipped: SkippedFlow[] = []
87
+ for (const e of edges) {
88
+ const name = `${e.from} —${e.activator ?? "?"}→ ${e.to}`
89
+ if (!e.activator) {
90
+ skipped.push({ name, reason: "no activator (backend/gesture-driven) — cover it with a tests/*.flow.json" })
91
+ continue
92
+ }
93
+ if (isState(e.from) || isState(e.to)) {
94
+ skipped.push({ name, reason: "screen-state edge (@state) — states are runtime conditions, not screens" })
95
+ continue
96
+ }
97
+ const path = pathTo(e.from)
98
+ if (path === null) {
99
+ skipped.push({ name, reason: `"${e.from}" has no activator path from "${entryScreen}" (tab-bar navigation?) — cover it with a tests/*.flow.json` })
100
+ continue
101
+ }
102
+ // A `fill` precedes every activator tap: submits are commonly disabled until their form is
103
+ // filled, and the graph tests NAVIGATION — dummy input satisfies local gates, the fixture pack
104
+ // answers what the submit then fetches. A no-op on screens without inputs.
105
+ flows.push({
106
+ name,
107
+ kind: "flow",
108
+ steps: [
109
+ ...path.flatMap((hop) => [{ fill: {} }, { tap: hop.activator!, expect: { screen: hop.to } }]),
110
+ { fill: {} },
111
+ { tap: e.activator, expect: { screen: e.to } },
112
+ ],
113
+ })
114
+ }
115
+ return { flows, skipped }
116
+ }
117
+
118
+ const slug = (s: string): string => s.replace(/[^a-zA-Z0-9-_]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64) || "case"
119
+
120
+ /** Read one tests/*.flow.json (envelope + steps, or a bare step array). */
121
+ const readFlowFile = (abs: string, displayName: string): FlowCase => {
122
+ let raw: unknown
123
+ try {
124
+ raw = JSON.parse(readFileSync(abs, "utf8"))
125
+ } catch (e) {
126
+ throw new CliError(`Can't read "${displayName}": ${e instanceof Error ? e.message : String(e)}`)
127
+ }
128
+ if (Array.isArray(raw)) return { name: displayName, kind: "file", steps: raw }
129
+ if (typeof raw !== "object" || raw === null || (raw as { steps?: unknown }).steps === undefined) {
130
+ throw new CliError(`"${displayName}" must be a JSON object with "steps" (or a bare step array).`)
131
+ }
132
+ const file = raw as { name?: string, width?: number, height?: number, settle?: number, device?: string, safeArea?: string, fixtures?: Record<string, unknown> | string, steps: unknown }
133
+ return {
134
+ name: file.name ?? displayName, kind: "file", steps: file.steps,
135
+ fixtures: resolveFixtures(file.fixtures, dirname(abs)),
136
+ width: file.width, height: file.height, settle: file.settle, device: file.device, safeArea: file.safeArea,
137
+ }
138
+ }
139
+
140
+ const testFlags = {
141
+ flows: bool("run ONLY the design-derived flows"),
142
+ "no-flows": bool("run ONLY the tests/*.flow.json files"),
143
+ fixtures: str("fixture pack for the design flows (overrides the tests/fixtures.json default)", { value: "<file>" }),
144
+ json: bool("machine-readable report on stdout"),
145
+ dir: str("tests folder", { value: "<folder>", default: "tests" }),
146
+ "design-dir": str("design folder", { value: "<dir>", default: "design" }),
147
+ artifacts: str("failure-artifact folder override (default <tests>/.artifacts)", { value: "<dir>" }),
148
+ timeout: num("hard cap on the whole run (default 20000 + 10000 per case; --desktop 60000 + 60000 per case)", { value: "<ms>" }),
149
+ ...viewportFlags,
150
+ ...bundleFlags,
151
+ ...desktopRenderFlags,
152
+ desktop: bool("run the file scenarios through the NATIVE host (coordinates only; expect.log checked, text/node/screen/value skipped; design flows stay headless). --frames / --fixed-dt as in render --desktop"),
153
+ }
154
+
155
+ type TestFlags = FlagValues<typeof testFlags>
156
+
157
+ export default defineCommand({
158
+ name: "test",
159
+ summary: "Run the flow tests (tests/*.flow.json + design-derived flows)",
160
+ usage: "[name…]",
161
+ description: "Headless flow tests: tests/*.flow.json scenarios, plus flows derived from the design graph (design/meta.json activator edges — checks the built app against the designed navigation; needs named elements + screen roots). Failing steps dump the frame (JSON + PNG) under tests/.artifacts/<flow>/.\n\nDesign flows read tests/fixtures.json automatically (canned fetch responses) so backend-gated transitions run headless; file scenarios declare their own via the \"fixtures\" envelope. [name…] runs only those files (a path, or a name under the tests folder).",
162
+ flags: testFlags,
163
+ examples: ["lecodes test", "lecodes test hero --logs", "lecodes test --flows --json", "lecodes test --desktop"],
164
+ run: ({ args, flags }) => runTests(args, flags),
165
+ })
166
+
167
+ const runTests = async (args: string[], flags: TestFlags): Promise<void> => {
168
+ const desktop = flags.desktop
169
+ if (desktop && flags.flows) throw new CliError("--flows needs the headless renderer (design flows tap by name) — drop --desktop.")
170
+ // --desktop: ONE renderer decision (host binary + the staged .filamat variant). The root is
171
+ // recomputed here because `root` below comes from the headless bundle, which --desktop skips.
172
+ let desktopRoot: string
173
+ try { desktopRoot = findProjectRoot(process.cwd()) } catch { desktopRoot = process.cwd() }
174
+ const desktopRenderer = desktop ? resolveDesktopRenderer(desktopRoot, flags.renderer) : undefined
175
+ const native = desktop ? await buildBundle(bundleOptions(flags), { localAssets: true, desktopRenderer }) : null
176
+ const headless = desktop ? null : await compileHeadlessBundle({ entry: flags.entry, publicUrl: flags["public-url"], remoteAssets: flags["remote-assets"], waitNetwork: flags["wait-network"] })
177
+ const warnings = headless?.warnings ?? []
178
+ const useLocalAssets = headless?.useLocalAssets ?? false
179
+ const js = headless?.js ?? ""
180
+ let root: string
181
+ if (headless) root = headless.root
182
+ else { try { root = findProjectRoot(process.cwd()) } catch { root = process.cwd() } }
183
+ const renderer = desktop ? null : await requireRenderer()
184
+ const nativeFrames = flags.frames || 60
185
+ const nativeFixedDt = flags["fixed-dt"] ?? 16
186
+ if (nativeFixedDt < 0 || nativeFixedDt > 1000) throw new CliError(`--fixed-dt wants a number of ms (0 = wall clock, max 1000), got "${nativeFixedDt}".`)
187
+ // Desktop-only projects (app.json desktop block, no ios/android) run flows desktop-sized.
188
+ const projectViewport = desktopDefaultViewport(root)
189
+
190
+ const testsDir = resolve(root, flags.dir)
191
+ const designMetaPath = resolve(root, flags["design-dir"], "meta.json")
192
+ const asJson = flags.json
193
+ const out = asJson ? logErr : log // --json owns stdout; the human report moves to stderr
194
+
195
+ // 1. File scenarios: the given paths, or every tests/*.flow.json.
196
+ const cases: FlowCase[] = []
197
+ if (args.length > 0) {
198
+ for (const given of args) {
199
+ const candidates = [resolve(given), resolve(testsDir, given), resolve(testsDir, `${given}.flow.json`)]
200
+ const abs = candidates.find((p) => existsSync(p))
201
+ if (!abs) throw new CliError(`No such test: "${given}" (looked in ${testsDir}).`)
202
+ cases.push(readFlowFile(abs, given))
203
+ }
204
+ } else if (existsSync(testsDir)) {
205
+ for (const f of readdirSync(testsDir).filter((f) => f.endsWith(".flow.json")).sort()) {
206
+ cases.push(readFlowFile(resolve(testsDir, f), f))
207
+ }
208
+ }
209
+
210
+ // The project fixture pack: backing data for the design-derived flows (whose success paths are
211
+ // usually backend-gated). `tests/fixtures.json` is picked up automatically; --fixtures overrides
212
+ // the path. File scenarios do NOT inherit it — they declare their own via the envelope, so a
213
+ // deliberately-offline scenario (error states) stays offline.
214
+ const defaultPack = resolve(testsDir, "fixtures.json")
215
+ const flowFixtures = flags.fixtures !== undefined
216
+ ? resolveFixtures(flags.fixtures, ".")
217
+ : existsSync(defaultPack) ? resolveFixtures("fixtures.json", testsDir) : undefined
218
+
219
+ // 2. Design-graph flows (opt out with --no-flows; --flows runs ONLY these).
220
+ const flowsOnly = flags.flows
221
+ const wantFlows = !flags["no-flows"] && args.length === 0
222
+ if (flowsOnly) cases.length = 0
223
+ let skipped: SkippedFlow[] = []
224
+ let entryScreen: string | null = null
225
+ if (desktop && wantFlows && existsSync(designMetaPath)) {
226
+ note("Design-derived flows skipped with --desktop (they tap by name; run `lecodes test` headless for them).")
227
+ }
228
+ if (!desktop && (wantFlows || flowsOnly) && existsSync(designMetaPath)) {
229
+ let meta: DesignMeta
230
+ try {
231
+ meta = JSON.parse(readFileSync(designMetaPath, "utf8")) as DesignMeta
232
+ } catch (e) {
233
+ throw new CliError(`Can't read ${designMetaPath}: ${e instanceof Error ? e.message : String(e)}`)
234
+ }
235
+ if ((meta.edges ?? []).length > 0) {
236
+ // Probe the app for its start screen — the BFS origin of every derived flow.
237
+ note("Probing the start screen…")
238
+ const probe = await renderer!.createSession(js, { raster: false, localAssets: useLocalAssets, fixtures: flowFixtures })
239
+ entryScreen = probe.screenName()
240
+ probe.dispose()
241
+ if (entryScreen === null) {
242
+ warnErr("Design flows skipped: the app's start screen root has no `name`. Name each screen root with its design screen id (e.g. UIScreen([...], { name: \"login\" })).")
243
+ } else {
244
+ const derived = deriveDesignFlows(meta, entryScreen)
245
+ cases.push(...derived.flows.map((f) => ({ ...f, fixtures: flowFixtures })))
246
+ skipped = derived.skipped
247
+ }
248
+ }
249
+ } else if (flowsOnly) {
250
+ throw new CliError(`--flows needs a design graph (${designMetaPath} not found).`)
251
+ }
252
+
253
+ if (cases.length === 0) {
254
+ for (const w of warnings) warnErr(w)
255
+ throw new CliError(`No tests found. Write tests/*.flow.json scenarios, or draw activator edges in the design board (design/meta.json).`)
256
+ }
257
+
258
+ // Hard timeout across the whole run (each case is bounded by settles, but a pathological app can
259
+ // still spin) — generous per-case allowance, overridable.
260
+ const timeoutMs = flags.timeout || (desktop ? 60000 + cases.length * 60000 : 20000 + cases.length * 10000)
261
+ const killer = setTimeout(() => {
262
+ warnErr(`Test run timed out after ${timeoutMs}ms (raise --timeout or lower --settle).`)
263
+ process.exit(1)
264
+ }, timeoutMs)
265
+ killer.unref?.()
266
+
267
+ const onConsole = flags.logs
268
+ ? (level: string, text: string) => logErr(`${c.dim(`[${level}]`)} ${text}`)
269
+ : undefined
270
+ const artifactsRoot = resolve(root, flags.artifacts ?? resolve(testsDir, ".artifacts"))
271
+
272
+ type CaseResult = {
273
+ name: string
274
+ kind: FlowCase["kind"]
275
+ ok: boolean
276
+ steps: { desc: string, ok: boolean, error?: string, skipped?: string[] }[]
277
+ error?: string
278
+ artifacts: string[]
279
+ }
280
+ const results: CaseResult[] = []
281
+
282
+ const reportCase = (result: CaseResult): void => {
283
+ const skippedCount = result.steps.reduce((n, s) => n + (s.skipped?.length ?? 0), 0)
284
+ if (result.ok) {
285
+ out(`${c.green("✓")} ${result.name}${skippedCount > 0 ? c.dim(` (${skippedCount} semantic check${skippedCount === 1 ? "" : "s"} skipped on --desktop)`) : ""}`)
286
+ } else {
287
+ out(`${c.red("✗")} ${result.name}`)
288
+ if (result.error) out(` ${c.red(result.error)}`)
289
+ for (const s of result.steps) {
290
+ out(s.ok ? c.dim(` ✓ ${s.desc}`) : ` ${c.red(`✗ ${s.desc} — ${s.error}`)}`)
291
+ for (const sk of s.skipped ?? []) out(c.dim(` – skipped: ${sk}`))
292
+ }
293
+ if (result.artifacts.length > 0) out(c.dim(` failing frame: ${result.artifacts.join(", ")}`))
294
+ }
295
+ }
296
+
297
+ // Native case runner: each case is its own host process (fresh state, like a fresh session);
298
+ // per-step screenshots + the final frame land under the case's artifacts folder.
299
+ const runNativeCase = async (kase: FlowCase): Promise<CaseResult> => {
300
+ const caseDir = resolve(artifactsRoot, slug(kase.name))
301
+ const plan = translateScenario(kase.steps, { outDir: caseDir, headroomFrames: nativeFrames })
302
+ for (const st of plan.steps) if (st.screenshot) mkdirSync(dirname(st.screenshot), { recursive: true })
303
+ mkdirSync(caseDir, { recursive: true })
304
+ const finalPng = resolve(caseDir, "final.png")
305
+ const { output } = await runDesktopRender(native!.js, native!.resources, {
306
+ renderer: desktopRenderer,
307
+ pluginDirs: desktopPluginLibraries(root).dirs,
308
+ width: flags.width || kase.width || projectViewport?.width || 390,
309
+ height: flags.height || kase.height || projectViewport?.height || 844,
310
+ frames: plan.frameCap, outPng: finalPng, logs: flags.logs,
311
+ timeoutMs: 60000 + plan.steps.length * 5000, script: plan.text, fixedDtMs: nativeFixedDt,
312
+ })
313
+ const r = evaluateDesktopRun(plan, output)
314
+ if (!r.loaded) throw new CliError("This desktop host doesn't support scripted input (CREATOR_SCRIPT). Update it: lecodes desktop update (or point LECODES_DESKTOP_EXE at a newer build).")
315
+ return {
316
+ name: kase.name, kind: kase.kind, ok: r.ok,
317
+ steps: r.steps.map((s) => ({ desc: s.desc, ok: s.ok, error: s.error, skipped: s.skipped.length > 0 ? s.skipped : undefined })),
318
+ error: r.ended ? undefined : "the host stopped before the script finished (frame cap / crash)",
319
+ artifacts: r.ok ? [] : [finalPng],
320
+ }
321
+ }
322
+
323
+ for (const kase of cases) {
324
+ let result: CaseResult
325
+ if (desktop) {
326
+ try {
327
+ result = await runNativeCase(kase)
328
+ } catch (e) {
329
+ if (e instanceof CliError && /doesn't support scripted input/.test(e.message)) throw e
330
+ result = { name: kase.name, kind: kase.kind, ok: false, steps: [], error: e instanceof Error ? e.message : String(e), artifacts: [] }
331
+ }
332
+ results.push(result)
333
+ reportCase(result)
334
+ continue
335
+ }
336
+ try {
337
+ const steps = renderer!.parseScenarioSteps(kase.steps)
338
+ // Every case runs in a FRESH session — no state bleeds between flows.
339
+ const session = await renderer!.createSession(js, {
340
+ width: flags.width || kase.width || projectViewport?.width || 390,
341
+ height: flags.height || kase.height || projectViewport?.height || 844,
342
+ settleMs: flags.settle ?? kase.settle,
343
+ waitNetwork: flags["wait-network"],
344
+ localAssets: useLocalAssets,
345
+ fixtures: kase.fixtures,
346
+ ...resolveSafeAreaChoice(flags["safe-area"] ?? kase.safeArea, flags.device ?? kase.device),
347
+ onConsole,
348
+ })
349
+ try {
350
+ const io = fileScenarioIO(resolve(artifactsRoot, slug(kase.name)))
351
+ const outcome = await renderer!.runScenario(session, steps, io)
352
+ result = {
353
+ name: kase.name, kind: kase.kind, ok: outcome.ok,
354
+ steps: outcome.steps.map((s) => ({ desc: s.desc, ok: s.ok, error: s.error })),
355
+ artifacts: outcome.failureArtifacts.map((p) => resolve(artifactsRoot, slug(kase.name), p)),
356
+ }
357
+ } finally {
358
+ session.dispose()
359
+ }
360
+ } catch (e) {
361
+ // A malformed scenario / session crash is a failed case, not a dead run.
362
+ result = { name: kase.name, kind: kase.kind, ok: false, steps: [], error: e instanceof Error ? e.message : String(e), artifacts: [] }
363
+ }
364
+ results.push(result)
365
+ reportCase(result)
366
+ }
367
+
368
+ for (const w of warnings) warnErr(w)
369
+ const passed = results.filter((r) => r.ok).length
370
+ const failed = results.length - passed
371
+ if (skipped.length > 0) {
372
+ out("")
373
+ out(c.dim(`Not machine-verifiable (${skipped.length}):`))
374
+ for (const s of skipped) out(c.dim(` - ${s.name}: ${s.reason}`))
375
+ }
376
+ out("")
377
+ const flowCount = results.filter((r) => r.kind === "flow").length
378
+ const summary = [
379
+ `${passed} passed`,
380
+ failed > 0 ? c.red(`${failed} failed`) : undefined,
381
+ skipped.length > 0 ? `${skipped.length} unverifiable` : undefined,
382
+ flowCount > 0 ? c.dim(`(${flowCount} from the design graph${entryScreen ? `, start: ${entryScreen}` : ""})`) : undefined,
383
+ ].filter(Boolean).join(", ")
384
+ out(failed > 0 ? `${c.red("✗")} ${summary}` : `${c.green("✓")} ${summary}`)
385
+
386
+ if (asJson) {
387
+ process.stdout.write(JSON.stringify({
388
+ ok: failed === 0,
389
+ passed, failed,
390
+ entryScreen,
391
+ cases: results,
392
+ unverifiable: skipped,
393
+ }, null, 2) + "\n")
394
+ }
395
+
396
+ clearTimeout(killer)
397
+ process.exit(failed > 0 ? 1 : 0)
398
+ }