@adhdev/daemon-core 0.9.82-rc.35 → 0.9.82-rc.351

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 (318) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +324 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +53 -13
  37. package/dist/index.js +39817 -14303
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41436 -16047
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +164 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +420 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +218 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +216 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +77 -3
  79. package/dist/providers/contracts.d.ts +139 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +14 -0
  88. package/dist/providers/provider-instance.d.ts +15 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +322 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +59 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +26 -0
  136. package/dist/system/load-better-sqlite3.d.ts +21 -0
  137. package/dist/types.d.ts +5 -0
  138. package/package.json +7 -3
  139. package/src/agent-stream/poller.ts +2 -3
  140. package/src/agent-stream/provider-adapter.ts +1 -1
  141. package/src/boot/daemon-lifecycle.ts +55 -12
  142. package/src/boot/process-hardening.ts +89 -0
  143. package/src/build-info.ts +73 -0
  144. package/src/chat/source-machine.ts +534 -0
  145. package/src/chat/source-resolver.ts +0 -0
  146. package/src/chat/subscription-updates.ts +20 -1
  147. package/src/cli-adapter-types.d.ts +1 -0
  148. package/src/cli-adapter-types.ts +47 -2
  149. package/src/cli-adapters/cli-script-runner.ts +421 -0
  150. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  151. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  152. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  153. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  154. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  155. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  156. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  157. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  158. package/src/cli-adapters/pty-transport.ts +2 -1
  159. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  160. package/src/cli-adapters/resolve-executable.ts +90 -0
  161. package/src/cli-adapters/session-host-transport.ts +2 -1
  162. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  163. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  164. package/src/cli-adapters/terminal-screen.ts +16 -81
  165. package/src/commands/chat-commands.ts +1823 -62
  166. package/src/commands/cli-manager.ts +304 -14
  167. package/src/commands/handler.ts +809 -2
  168. package/src/commands/mesh-coordinator.ts +332 -122
  169. package/src/commands/router.ts +7505 -1311
  170. package/src/commands/stream-commands.ts +8 -0
  171. package/src/commands/upgrade-helper.ts +81 -30
  172. package/src/config/chat-history.ts +483 -24
  173. package/src/config/config.ts +12 -0
  174. package/src/config/mesh-config.ts +388 -6
  175. package/src/config/recent-activity.ts +8 -2
  176. package/src/daemon/dev-auto-implement.ts +3 -2
  177. package/src/daemon/dev-cli-debug.ts +10 -1
  178. package/src/detection/cli-detector.ts +28 -9
  179. package/src/detection/ide-detector.ts +55 -16
  180. package/src/detection/win32-ide-version.ts +106 -0
  181. package/src/git/change-impact-config.ts +354 -0
  182. package/src/git/git-commands.ts +55 -14
  183. package/src/git/git-diff.ts +53 -0
  184. package/src/git/git-executor.ts +12 -0
  185. package/src/git/git-status.ts +574 -43
  186. package/src/git/git-types.ts +14 -62
  187. package/src/git/git-worktree.ts +8 -1
  188. package/src/git/index.ts +16 -0
  189. package/src/index.ts +151 -12
  190. package/src/installer.d.ts +1 -1
  191. package/src/installer.ts +8 -6
  192. package/src/ipc/local-ipc-server.ts +278 -0
  193. package/src/launch.d.ts +1 -1
  194. package/src/launch.ts +37 -28
  195. package/src/logging/async-batch-writer.ts +55 -0
  196. package/src/logging/log-redactor.ts +100 -0
  197. package/src/logging/log-tail-reader.ts +220 -0
  198. package/src/logging/logger.ts +2 -1
  199. package/src/mesh/contracts.ts +329 -0
  200. package/src/mesh/coordinator-prompt.ts +234 -31
  201. package/src/mesh/coordinator-registry.ts +121 -0
  202. package/src/mesh/mesh-active-work.ts +667 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2303 -0
  205. package/src/mesh/mesh-events-pending.ts +567 -0
  206. package/src/mesh/mesh-events-stale.ts +307 -0
  207. package/src/mesh/mesh-events-utils.ts +381 -0
  208. package/src/mesh/mesh-events.ts +30 -1035
  209. package/src/mesh/mesh-fast-forward.ts +839 -0
  210. package/src/mesh/mesh-host-ownership.ts +73 -0
  211. package/src/mesh/mesh-init.ts +260 -0
  212. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  213. package/src/mesh/mesh-ledger.ts +590 -102
  214. package/src/mesh/mesh-missions.ts +322 -0
  215. package/src/mesh/mesh-reconcile-loop.ts +989 -0
  216. package/src/mesh/mesh-refine-batch.ts +197 -0
  217. package/src/mesh/mesh-refine-status.ts +231 -0
  218. package/src/mesh/mesh-review-inbox.ts +307 -0
  219. package/src/mesh/mesh-routing.ts +291 -0
  220. package/src/mesh/mesh-runtime-store.ts +1664 -0
  221. package/src/mesh/mesh-task-stats.ts +161 -0
  222. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  223. package/src/mesh/mesh-work-queue.ts +901 -141
  224. package/src/mesh/preview-freshness.ts +118 -0
  225. package/src/mesh/refine-config.ts +423 -0
  226. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  227. package/src/providers/acp-provider-instance.ts +25 -9
  228. package/src/providers/approval-utils.d.ts +4 -0
  229. package/src/providers/approval-utils.ts +47 -5
  230. package/src/providers/chat-message-normalization.ts +45 -5
  231. package/src/providers/cli-provider-instance.ts +1041 -99
  232. package/src/providers/contracts.d.ts +55 -0
  233. package/src/providers/contracts.ts +150 -6
  234. package/src/providers/extension-provider-instance.ts +12 -7
  235. package/src/providers/external-sources.ts +218 -0
  236. package/src/providers/ide-provider-instance.ts +35 -12
  237. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  238. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  239. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  240. package/src/providers/native-history/dispatcher.ts +340 -0
  241. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  242. package/src/providers/native-history/index.ts +30 -0
  243. package/src/providers/provider-instance-manager.ts +30 -0
  244. package/src/providers/provider-instance.ts +10 -1
  245. package/src/providers/provider-loader.ts +670 -50
  246. package/src/providers/provider-schema.ts +87 -14
  247. package/src/providers/provider-trust.ts +114 -0
  248. package/src/providers/read-chat-contract.ts +76 -16
  249. package/src/providers/sdk/README.md +49 -0
  250. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  251. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  254. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  255. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  256. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  257. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  258. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  259. package/src/providers/sdk/v1/index.ts +152 -0
  260. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  261. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  262. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  263. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  264. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  265. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  280. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  281. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  282. package/src/providers/sdk/v1/validators/index.ts +19 -0
  283. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  284. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  285. package/src/providers/spec/adapter.ts +168 -0
  286. package/src/providers/spec/cli-adapter.ts +986 -0
  287. package/src/providers/spec/evaluator.ts +345 -0
  288. package/src/providers/spec/fsm-driver.ts +1065 -0
  289. package/src/providers/spec/fsm-evaluator.ts +255 -0
  290. package/src/providers/spec/fsm-loader.ts +120 -0
  291. package/src/providers/spec/fsm-types.ts +238 -0
  292. package/src/providers/spec/native-history-executor.ts +1136 -0
  293. package/src/providers/spec/pre-launch-trust.ts +104 -0
  294. package/src/providers/spec/route.ts +51 -0
  295. package/src/providers/spec/types.ts +226 -0
  296. package/src/providers/status-monitor.d.ts +7 -7
  297. package/src/providers/status-monitor.ts +37 -22
  298. package/src/providers/transcript-v2.ts +567 -0
  299. package/src/providers/types/interactive-prompt.ts +536 -0
  300. package/src/providers/version-archive.ts +64 -24
  301. package/src/providers/working-dir.ts +23 -0
  302. package/src/repo-mesh-types.ts +378 -14
  303. package/src/sessions/registry.ts +6 -0
  304. package/src/shared-types-extra.ts +2 -4
  305. package/src/shared-types.d.ts +8 -0
  306. package/src/shared-types.ts +64 -1
  307. package/src/status/builders.ts +26 -6
  308. package/src/status/normalize.ts +2 -0
  309. package/src/status/reporter.ts +19 -1
  310. package/src/status/snapshot.ts +95 -26
  311. package/src/system/host-memory.ts +29 -12
  312. package/src/system/load-better-sqlite3.ts +68 -0
  313. package/src/types.ts +5 -0
  314. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  315. package/dist/mesh/mesh-sync.d.ts +0 -53
  316. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  317. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  318. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,255 @@
1
+ /**
2
+ * FSM evaluator — pure transition evaluation for adhdev:cli/spec@4.
3
+ *
4
+ * Given the current state, the screen, and a clock context (when the current
5
+ * state was entered, when each cursor_above region last changed), decides
6
+ * which outgoing transition fires — and records WHY every transition did or
7
+ * did not fire. That "why" trace is the whole point: it is what makes the FSM
8
+ * debuggable from the daemon API without guessing.
9
+ *
10
+ * Screen-content leaves (regex / changed) are delegated to the shared v3
11
+ * condition evaluator. Time leaves (elapsed_ms / stable_ms) are evaluated here
12
+ * against the clock context the driver passes in. No wall-clock reads happen
13
+ * in this file — the driver owns `now` so the function stays pure & testable.
14
+ */
15
+ 'use strict';
16
+
17
+ import type { Condition, SectionDef } from './types.js';
18
+ import {
19
+ resolveSections, evaluateCondition, type ResolvedSection, type TraceEntry,
20
+ } from './evaluator.js';
21
+ import {
22
+ type CliSpecV4, type FsmCondition, type FsmTransition,
23
+ outgoingTransitions, stateById,
24
+ } from './fsm-types.js';
25
+
26
+ export interface FsmClock {
27
+ /** Wall-clock now (ms). Passed in so the evaluator stays pure. */
28
+ now: number;
29
+ /** When the current state was entered (ms). */
30
+ stateEnteredAt: number;
31
+ /** Last-changed timestamp per cursor_above region. Key = cursor_above
32
+ * value (0 / undefined → whole-screen, keyed as -1). Missing key means
33
+ * "never observed changing" → treated as stable since stateEnteredAt. */
34
+ regionLastChangedAt: Map<number, number>;
35
+ }
36
+
37
+ /** Per-condition evaluation detail — the debugging payload. */
38
+ export interface CondResult {
39
+ kind: 'regex' | 'changed' | 'elapsed' | 'stable' | 'all' | 'any' | 'not';
40
+ result: boolean;
41
+ detail: string;
42
+ /** Remaining ms until a time-based condition would flip to true. 0 if
43
+ * already true or not applicable. Lets the UI show a countdown. */
44
+ remainingMs?: number;
45
+ children?: CondResult[];
46
+ }
47
+
48
+ /** One evaluated transition with its full reasoning. */
49
+ export interface TransitionEval {
50
+ to: string;
51
+ label: string;
52
+ /** Did the `from` clause include the current state? (Always true for the
53
+ * transitions we return — kept for completeness.) */
54
+ eligible: boolean;
55
+ /** min_hold_ms guard satisfied? */
56
+ holdSatisfied: boolean;
57
+ holdRemainingMs: number;
58
+ /** Guard condition result (true if no `when`). */
59
+ condResult: boolean;
60
+ cond?: CondResult;
61
+ /** Overall: would this transition fire? */
62
+ fires: boolean;
63
+ priority: number;
64
+ }
65
+
66
+ export interface FsmEvaluation {
67
+ /** Sections resolved from the screen (shared with v3 shape). */
68
+ sections: ResolvedSection[];
69
+ /** Every outgoing transition from the current state, priority-ordered,
70
+ * each annotated with why it fired or didn't. */
71
+ transitions: TransitionEval[];
72
+ /** The transition that fires (first in priority order with fires===true),
73
+ * or null to stay in the current state. */
74
+ fired: TransitionEval | null;
75
+ /** v3-compatible trace lines for the legacy inspector. */
76
+ trace: TraceEntry[];
77
+ }
78
+
79
+ const WHOLE_SCREEN = -1;
80
+
81
+ function regionKey(cursorAbove: number | undefined): number {
82
+ return cursorAbove && cursorAbove > 0 ? cursorAbove : WHOLE_SCREEN;
83
+ }
84
+
85
+ function isRegex(c: FsmCondition): c is import('./types.js').RegexCondition {
86
+ return 'matches' in c;
87
+ }
88
+ function isChanged(c: FsmCondition): c is import('./types.js').ChangedCondition {
89
+ return 'cursor_above' in c && 'changed' in c;
90
+ }
91
+ function isElapsed(c: FsmCondition): c is import('./fsm-types.js').ElapsedCondition {
92
+ return 'elapsed_ms' in c;
93
+ }
94
+ function isStable(c: FsmCondition): c is import('./fsm-types.js').StableCondition {
95
+ return 'stable_ms' in c;
96
+ }
97
+ function isAll(c: FsmCondition): c is import('./fsm-types.js').FsmAllCondition {
98
+ return 'all' in c;
99
+ }
100
+ function isAny(c: FsmCondition): c is import('./fsm-types.js').FsmAnyCondition {
101
+ return 'any' in c;
102
+ }
103
+ function isNot(c: FsmCondition): c is import('./fsm-types.js').FsmNotCondition {
104
+ return 'not' in c;
105
+ }
106
+
107
+ /**
108
+ * Evaluate a single FSM condition into a {result, detail, remainingMs, children}.
109
+ * Recurses through all/any/not; defers regex/changed to the shared evaluator;
110
+ * handles elapsed_ms/stable_ms against the clock.
111
+ */
112
+ function evalCond(
113
+ cond: FsmCondition,
114
+ sections: ResolvedSection[],
115
+ fullScreen: string,
116
+ cursor: { row: number; col: number } | undefined,
117
+ prevLines: string[] | undefined,
118
+ clock: FsmClock,
119
+ legacyTrace: TraceEntry[],
120
+ stateId: string,
121
+ ): CondResult {
122
+ if (isAll(cond)) {
123
+ const children = cond.all.map(c =>
124
+ evalCond(c, sections, fullScreen, cursor, prevLines, clock, legacyTrace, stateId));
125
+ const result = children.every(c => c.result);
126
+ const remainingMs = result ? 0 : Math.max(0, ...children.filter(c => !c.result).map(c => c.remainingMs ?? 0));
127
+ return { kind: 'all', result, detail: `all(${children.length})`, remainingMs, children };
128
+ }
129
+ if (isAny(cond)) {
130
+ const children = cond.any.map(c =>
131
+ evalCond(c, sections, fullScreen, cursor, prevLines, clock, legacyTrace, stateId));
132
+ const result = children.some(c => c.result);
133
+ // remaining = the soonest child that could flip true
134
+ const pending = children.filter(c => !c.result).map(c => c.remainingMs ?? Infinity);
135
+ const remainingMs = result ? 0 : (pending.length ? Math.min(...pending) : 0);
136
+ return { kind: 'any', result, detail: `any(${children.length})`, remainingMs: Number.isFinite(remainingMs) ? remainingMs : 0, children };
137
+ }
138
+ if (isNot(cond)) {
139
+ const child = evalCond(cond.not, sections, fullScreen, cursor, prevLines, clock, legacyTrace, stateId);
140
+ return { kind: 'not', result: !child.result, detail: `not`, remainingMs: 0, children: [child] };
141
+ }
142
+ if (isElapsed(cond)) {
143
+ const age = clock.now - clock.stateEnteredAt;
144
+ const result = age >= cond.elapsed_ms;
145
+ const remainingMs = result ? 0 : cond.elapsed_ms - age;
146
+ return { kind: 'elapsed', result, detail: `elapsed ${age}ms / ${cond.elapsed_ms}ms`, remainingMs };
147
+ }
148
+ if (isStable(cond)) {
149
+ const key = regionKey(cond.cursor_above);
150
+ // If we never saw the region change, treat it as stable since the
151
+ // state was entered (conservative — avoids a premature "stable" on
152
+ // the very first frame).
153
+ const lastChanged = clock.regionLastChangedAt.get(key) ?? clock.stateEnteredAt;
154
+ const stableFor = clock.now - lastChanged;
155
+ const result = stableFor >= cond.stable_ms;
156
+ const remainingMs = result ? 0 : cond.stable_ms - stableFor;
157
+ const where = key === WHOLE_SCREEN ? 'screen' : `cursor_above=${cond.cursor_above}`;
158
+ return { kind: 'stable', result, detail: `stable ${where} ${stableFor}ms / ${cond.stable_ms}ms`, remainingMs };
159
+ }
160
+ // regex / changed → shared evaluator (operates on v3 Condition shape)
161
+ if (isRegex(cond) || isChanged(cond)) {
162
+ const result = evaluateCondition(cond as Condition, sections, fullScreen, cursor, prevLines, legacyTrace, stateId);
163
+ const kind = isRegex(cond) ? 'regex' : 'changed';
164
+ const detail = isRegex(cond)
165
+ ? `${(cond as any).section ?? '*'}~/${(cond as any).matches}/`
166
+ : `cursor_above=${(cond as any).cursor_above} changed=${(cond as any).changed}`;
167
+ return { kind, result, detail };
168
+ }
169
+ return { kind: 'all', result: false, detail: 'unknown condition' };
170
+ }
171
+
172
+ function fromLabel(t: FsmTransition): string {
173
+ const from = Array.isArray(t.from) ? t.from.join('|') : t.from;
174
+ return t.label ?? `${from}→${t.to}`;
175
+ }
176
+
177
+ /**
178
+ * Evaluate the FSM: given the current state id and screen, return every
179
+ * outgoing transition annotated with why it fires/doesn't, plus the one that
180
+ * fires (if any).
181
+ */
182
+ export function evaluateFsm(
183
+ spec: CliSpecV4,
184
+ currentStateId: string,
185
+ screenText: string,
186
+ cursor: { row: number; col: number } | undefined,
187
+ prevLines: string[] | undefined,
188
+ clock: FsmClock,
189
+ ): FsmEvaluation {
190
+ const legacyTrace: TraceEntry[] = [];
191
+ const lines = screenText.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
192
+ const cleanScreen = lines.join('\n');
193
+ const sections = resolveSections(spec.sections ?? {}, lines);
194
+
195
+ const outgoing = outgoingTransitions(spec, currentStateId);
196
+ const transitions: TransitionEval[] = [];
197
+ let fired: TransitionEval | null = null;
198
+
199
+ for (const t of outgoing) {
200
+ const holdMs = t.min_hold_ms ?? 0;
201
+ const heldFor = clock.now - clock.stateEnteredAt;
202
+ const holdSatisfied = heldFor >= holdMs;
203
+ const holdRemainingMs = holdSatisfied ? 0 : holdMs - heldFor;
204
+
205
+ let cond: CondResult | undefined;
206
+ let condResult = true;
207
+ if (t.when) {
208
+ cond = evalCond(t.when, sections, cleanScreen, cursor, prevLines, clock, legacyTrace, `${currentStateId}→${t.to}`);
209
+ condResult = cond.result;
210
+ }
211
+
212
+ const fires = holdSatisfied && condResult;
213
+ const te: TransitionEval = {
214
+ to: t.to,
215
+ label: fromLabel(t),
216
+ eligible: true,
217
+ holdSatisfied,
218
+ holdRemainingMs,
219
+ condResult,
220
+ cond,
221
+ fires,
222
+ priority: t.priority ?? 0,
223
+ };
224
+ transitions.push(te);
225
+ if (fires && !fired) fired = te;
226
+ }
227
+
228
+ // Validate destination exists (defensive — loader should catch this).
229
+ if (fired && !stateById(spec, fired.to)) {
230
+ legacyTrace.push({ kind: 'state_skip', text: `transition target ${fired.to} not found` });
231
+ fired = null;
232
+ }
233
+
234
+ return { sections, transitions, fired, trace: legacyTrace };
235
+ }
236
+
237
+ /**
238
+ * Evaluate a single condition against a screen + section map — for the spec
239
+ * editor's live preview ("does this regex match the current screen right
240
+ * now?"). Time leaves (elapsed_ms/stable_ms) are evaluated against a synthetic
241
+ * clock where the state was just entered, so they report their countdown
242
+ * rather than firing; the preview is about screen-content match, not timing.
243
+ */
244
+ export function evaluateConditionPreview(
245
+ cond: FsmCondition,
246
+ sections: Record<string, SectionDef> | undefined,
247
+ screenText: string,
248
+ cursor?: { row: number; col: number },
249
+ ): CondResult {
250
+ const lines = screenText.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
251
+ const cleanScreen = lines.join('\n');
252
+ const resolved = resolveSections(sections ?? {}, lines);
253
+ const clock: FsmClock = { now: 0, stateEnteredAt: 0, regionLastChangedAt: new Map() };
254
+ return evalCond(cond, resolved, cleanScreen, cursor, undefined, clock, [], 'preview');
255
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * FSM spec (adhdev:cli/spec@4) loader + validator.
3
+ *
4
+ * Validation is intentionally code-based (not AJV) so a spec authored live in
5
+ * the debug panel gets precise, human-readable errors ("transition[2].to
6
+ * references unknown state 'budy'") instead of a JSON-schema path. Every error
7
+ * is something a spec author can act on without reading the engine.
8
+ */
9
+ 'use strict';
10
+
11
+ import * as fs from 'node:fs';
12
+ import { type CliSpecV4, type FsmCondition, isV4Spec } from './fsm-types.js';
13
+
14
+ export interface FsmLoadOk { ok: true; spec: CliSpecV4; sourcePath: string; }
15
+ export interface FsmLoadErr { ok: false; errors: string[]; sourcePath: string; }
16
+
17
+ export function loadFsmSpec(sourcePath: string): FsmLoadOk | FsmLoadErr {
18
+ let raw: unknown;
19
+ try {
20
+ raw = JSON.parse(fs.readFileSync(sourcePath, 'utf8'));
21
+ } catch (err) {
22
+ return { ok: false, errors: [`Failed to read/parse spec: ${(err as Error).message}`], sourcePath };
23
+ }
24
+ const errors = validateFsmSpec(raw);
25
+ if (errors.length) return { ok: false, errors, sourcePath };
26
+ return { ok: true, spec: raw as CliSpecV4, sourcePath };
27
+ }
28
+
29
+ /** Pure validator — usable from a "validate before save" API in the panel. */
30
+ export function validateFsmSpec(raw: unknown): string[] {
31
+ const errs: string[] = [];
32
+ if (!isV4Spec(raw)) return ['$schema must be "adhdev:cli/spec@4"'];
33
+ const spec = raw as CliSpecV4;
34
+
35
+ if (!spec.id) errs.push('id is required');
36
+ if (!spec.binary) errs.push('binary is required');
37
+ if (!spec.send_message?.submit_key) errs.push('send_message.submit_key is required');
38
+
39
+ if (spec.pre_launch_trust !== undefined) {
40
+ const t = spec.pre_launch_trust as { settings_path?: unknown; key?: unknown };
41
+ if (!t || typeof t !== 'object' || Array.isArray(t)) {
42
+ errs.push('pre_launch_trust must be an object');
43
+ } else {
44
+ if (typeof t.settings_path !== 'string' || !t.settings_path) errs.push('pre_launch_trust.settings_path is required');
45
+ if (typeof t.key !== 'string' || !t.key) errs.push('pre_launch_trust.key is required');
46
+ }
47
+ }
48
+
49
+ if (spec.refocus_when_stalled_ms !== undefined) {
50
+ if (typeof spec.refocus_when_stalled_ms !== 'number' || !(spec.refocus_when_stalled_ms > 0)) {
51
+ errs.push('refocus_when_stalled_ms must be a positive number');
52
+ } else if (!Array.isArray(spec.send_on_spawn) || spec.send_on_spawn.length === 0) {
53
+ errs.push('refocus_when_stalled_ms requires send_on_spawn (the wake sequence to re-inject)');
54
+ }
55
+ }
56
+
57
+ if (!Array.isArray(spec.states) || spec.states.length === 0) {
58
+ errs.push('states[] must be a non-empty array');
59
+ return errs;
60
+ }
61
+ if (!Array.isArray(spec.transitions)) {
62
+ errs.push('transitions[] must be an array');
63
+ return errs;
64
+ }
65
+
66
+ const ids = new Set<string>();
67
+ let initialCount = 0;
68
+ for (const [i, s] of spec.states.entries()) {
69
+ if (!s.id) { errs.push(`states[${i}].id is required`); continue; }
70
+ if (ids.has(s.id)) errs.push(`states[${i}].id "${s.id}" is duplicated`);
71
+ ids.add(s.id);
72
+ if (!s.label) errs.push(`states[${i}].label is required`);
73
+ if (s.initial) initialCount += 1;
74
+ if (s.status && !['idle', 'generating', 'approval'].includes(s.status)) {
75
+ errs.push(`states[${i}].status "${s.status}" must be idle|generating|approval`);
76
+ }
77
+ }
78
+ if (initialCount === 0) errs.push('exactly one state must have initial:true (none found)');
79
+ if (initialCount > 1) errs.push(`exactly one state must have initial:true (${initialCount} found)`);
80
+
81
+ const sectionIds = new Set(Object.keys(spec.sections ?? {}));
82
+ for (const [i, t] of spec.transitions.entries()) {
83
+ const froms = t.from === '*' ? [] : (Array.isArray(t.from) ? t.from : [t.from]);
84
+ for (const f of froms) {
85
+ if (!ids.has(f)) errs.push(`transitions[${i}].from references unknown state "${f}"`);
86
+ }
87
+ if (t.from !== '*' && froms.length === 0) errs.push(`transitions[${i}].from is required`);
88
+ if (!t.to) errs.push(`transitions[${i}].to is required`);
89
+ else if (!ids.has(t.to)) errs.push(`transitions[${i}].to references unknown state "${t.to}"`);
90
+ if (t.when) errs.push(...validateCondition(t.when, sectionIds, `transitions[${i}].when`));
91
+ }
92
+
93
+ // Section refs in state.extract
94
+ for (const [i, s] of spec.states.entries()) {
95
+ const sec = s.extract?.title?.section;
96
+ if (sec && !sectionIds.has(sec)) errs.push(`states[${i}].extract.title.section "${sec}" unknown`);
97
+ const bsec = s.extract?.buttons?.section;
98
+ if (bsec && !sectionIds.has(bsec)) errs.push(`states[${i}].extract.buttons.section "${bsec}" unknown`);
99
+ }
100
+
101
+ return errs;
102
+ }
103
+
104
+ function validateCondition(c: FsmCondition, sectionIds: Set<string>, path: string): string[] {
105
+ const errs: string[] = [];
106
+ const w = c as any;
107
+ if ('all' in w) { w.all.forEach((x: FsmCondition, i: number) => errs.push(...validateCondition(x, sectionIds, `${path}.all[${i}]`))); return errs; }
108
+ if ('any' in w) { w.any.forEach((x: FsmCondition, i: number) => errs.push(...validateCondition(x, sectionIds, `${path}.any[${i}]`))); return errs; }
109
+ if ('not' in w) { errs.push(...validateCondition(w.not, sectionIds, `${path}.not`)); return errs; }
110
+ if ('matches' in w) {
111
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path}.section "${w.section}" unknown`);
112
+ try { new RegExp(w.matches, w.flags ?? 'i'); } catch (e) { errs.push(`${path}.matches invalid regex: ${(e as Error).message}`); }
113
+ return errs;
114
+ }
115
+ if ('cursor_above' in w && 'changed' in w) return errs;
116
+ if ('elapsed_ms' in w) { if (typeof w.elapsed_ms !== 'number') errs.push(`${path}.elapsed_ms must be a number`); return errs; }
117
+ if ('stable_ms' in w) { if (typeof w.stable_ms !== 'number') errs.push(`${path}.stable_ms must be a number`); return errs; }
118
+ errs.push(`${path} is not a recognized condition`);
119
+ return errs;
120
+ }
@@ -0,0 +1,238 @@
1
+ /**
2
+ * adhdev:cli/spec@4 — declarative FSM spec.
3
+ *
4
+ * A v4 spec describes a finite state machine the same way a Unity animator
5
+ * layer does: states are nodes, transitions are directed edges with a guard
6
+ * condition. The engine (fsm-driver.ts) holds ZERO CLI-specific knowledge —
7
+ * every concept that used to live in the driver as a hard-coded debounce
8
+ * (startup grace, busy hold, completion marker, idle hold) is now expressed
9
+ * declaratively as either a state, a transition condition, or a transition
10
+ * guard. To support a new CLI you write a spec; you never touch the engine.
11
+ *
12
+ * Reuses v3's section system (sections{}) and condition system (regex /
13
+ * changed / all / any) verbatim — see types.ts. v4 only adds the FSM layer
14
+ * (states[] + transitions[]) on top and two new leaf conditions that are
15
+ * inherently time-based:
16
+ *
17
+ * - elapsed_ms : true once N ms have passed since the CURRENT state was
18
+ * entered. Replaces startup_grace_ms (a `starting` state with
19
+ * one `elapsed_ms` transition to idle).
20
+ * - stable_ms : true once the cursor_above region has been UNCHANGED for
21
+ * N ms. Replaces screen_active_hold_ms / the old changed:false
22
+ * + stable_ms combo. Pure region-stability gate.
23
+ *
24
+ * Both are evaluated by the driver (which owns the clock); the shared
25
+ * condition evaluator handles the screen-content leaves (regex / changed).
26
+ */
27
+ 'use strict';
28
+
29
+ import type {
30
+ RegexCondition, ChangedCondition,
31
+ Control, NotificationRule, DelegateTrigger,
32
+ NativeHistoryConfig, SectionDef, ExtractTitle, ExtractButtons,
33
+ } from './types.js';
34
+
35
+ // ─────────────────────────────────────────────────────────────────────────────
36
+ // Conditions (v4)
37
+ //
38
+ // Superset of v3 conditions. Adds the two time-based leaves. The shared
39
+ // evaluator handles regex/changed; the driver handles elapsed_ms/stable_ms
40
+ // because they need the wall clock and per-region change timestamps.
41
+ // ─────────────────────────────────────────────────────────────────────────────
42
+
43
+ /** True once `ms` have elapsed since the current state was entered. */
44
+ export interface ElapsedCondition {
45
+ elapsed_ms: number;
46
+ }
47
+
48
+ /** True once the region `cursor_above` lines above the cursor has been
49
+ * unchanged for `ms`. A stability gate — the inverse of a busy signal. */
50
+ export interface StableCondition {
51
+ stable_ms: number;
52
+ /** Lines above the cursor that must be stable. Default: whole screen. */
53
+ cursor_above?: number;
54
+ }
55
+
56
+ export interface FsmAllCondition {
57
+ all: FsmCondition[];
58
+ }
59
+
60
+ export interface FsmAnyCondition {
61
+ any: FsmCondition[];
62
+ }
63
+
64
+ /** Negation — true when the inner condition is false. Lets a transition say
65
+ * "go busy unless the completion marker is present", etc. */
66
+ export interface FsmNotCondition {
67
+ not: FsmCondition;
68
+ }
69
+
70
+ export type FsmCondition =
71
+ | RegexCondition
72
+ | ChangedCondition
73
+ | ElapsedCondition
74
+ | StableCondition
75
+ | FsmAllCondition
76
+ | FsmAnyCondition
77
+ | FsmNotCondition;
78
+
79
+ // ─────────────────────────────────────────────────────────────────────────────
80
+ // States & transitions (v4)
81
+ // ─────────────────────────────────────────────────────────────────────────────
82
+
83
+ export interface FsmState {
84
+ id: string;
85
+ label: string;
86
+ /** Exactly one state must be `initial: true` — the state at spawn. */
87
+ initial?: boolean;
88
+ /** Modal states (approval/picker) expose modal buttons in the UI and are
89
+ * treated as "interesting" — the dashboard surfaces them distinctly. */
90
+ modal?: boolean;
91
+ /** Status this state maps to for the dashboard/cli-adapter status field.
92
+ * One of: idle | generating | approval. Defaults: modal→approval,
93
+ * initial→idle, id==='busy'→generating, else idle. Explicit wins. */
94
+ status?: 'idle' | 'generating' | 'approval';
95
+ /** Optional extraction run whenever this state is the committed state —
96
+ * used by modal states to surface a title + buttons. */
97
+ extract?: {
98
+ title?: ExtractTitle;
99
+ buttons?: ExtractButtons;
100
+ };
101
+ }
102
+
103
+ export interface FsmTransition {
104
+ /** Source state id, or list of source ids, or "*" for any state. */
105
+ from: string | string[];
106
+ /** Destination state id. */
107
+ to: string;
108
+ /** Guard condition. Omitted → always eligible (only gated by `from` +
109
+ * min_hold_ms). Evaluated against the current screen + clock. */
110
+ when?: FsmCondition;
111
+ /** Minimum time the machine must have been in `from` before this edge can
112
+ * fire. Replaces busy_hold_ms / idle_hold_ms (per-edge, not global). */
113
+ min_hold_ms?: number;
114
+ /** Higher priority transitions are evaluated first. Default 0. Ties broken
115
+ * by declaration order. */
116
+ priority?: number;
117
+ /** Human label for the debugger. */
118
+ label?: string;
119
+ }
120
+
121
+ /**
122
+ * Declarative "trust this folder before spawn" config. Some agent CLIs gate the
123
+ * first run in a new folder behind an interactive trust prompt and persist the
124
+ * answer as a string array in a JSON settings file. Declaring this lets the
125
+ * engine add the workspace path to that array before spawn so the prompt never
126
+ * appears — the robust alternative to detecting and auto-clicking the modal.
127
+ * CLIs without such a gate omit this field and the engine does nothing.
128
+ */
129
+ export interface PreLaunchTrust {
130
+ /** Path to the CLI's JSON settings file. A leading `~` expands to $HOME. */
131
+ settings_path: string;
132
+ /** Key of the string-array of trusted folder paths within that file. */
133
+ key: string;
134
+ }
135
+
136
+ // ─────────────────────────────────────────────────────────────────────────────
137
+ // CliSpecV4 — the v4 runtime spec
138
+ // ─────────────────────────────────────────────────────────────────────────────
139
+
140
+ export interface CliSpecV4 {
141
+ $schema: 'adhdev:cli/spec@4';
142
+ id: string;
143
+ name: string;
144
+ binary: string;
145
+ spawn_args?: string[];
146
+ env?: Record<string, string>;
147
+ cli_version_range?: string;
148
+ /**
149
+ * Optional raw byte sequences written to the PTY once, shortly after spawn,
150
+ * to prime a TUI that gates its input handling on a terminal event the
151
+ * daemon would otherwise never emit. The canonical case is a focus-event
152
+ * TUI (Ink `useStdin`/`useFocus`, e.g. antigravity's `agy`) that enables
153
+ * focus reporting (`CSI ?1004h`) and treats its input box as unfocused —
154
+ * silently dropping the first programmatic write — until it receives a
155
+ * focus-in event (`ESC [ I`). Declaring `[""]` here wakes the input
156
+ * stream on spawn so the first delegated message lands without a manual
157
+ * keystroke. CLIs that do not focus-gate input simply omit this field; the
158
+ * engine writes nothing extra for them, so it stays CLI-agnostic.
159
+ */
160
+ send_on_spawn?: string[];
161
+ /** Delay (ms) after spawn before writing `send_on_spawn`. Default 250. */
162
+ send_on_spawn_delay_ms?: number;
163
+ /**
164
+ * Opt-in stall recovery for focus-gated TUIs. The same CLIs that need
165
+ * `send_on_spawn` (focus-event TUIs like antigravity's `agy`) also stop
166
+ * rendering / flushing output the moment they believe they have lost focus
167
+ * MID-TURN — the screen freezes and only repaints once the user presses a
168
+ * key, which the daemon never does on its own. When this field is set and
169
+ * the machine is in a `generating`-status state whose screen has not changed
170
+ * for `refocus_when_stalled_ms`, the engine re-injects the `send_on_spawn`
171
+ * prime (the focus-in event) once to wake the render loop, then waits for the
172
+ * screen to change or for the stall window to lapse again before re-priming
173
+ * (a cooldown that prevents a tight re-prime loop). Requires `send_on_spawn`
174
+ * to carry the wake sequence; with no `send_on_spawn` there is nothing to
175
+ * re-inject and the engine does nothing. Omitted by every non-focus-gated
176
+ * CLI spec, so the engine stays CLI-agnostic.
177
+ */
178
+ refocus_when_stalled_ms?: number;
179
+ /**
180
+ * Optional pre-spawn folder-trust step. When present, the engine adds the
181
+ * launch workspace path to the declared trusted-folders array before
182
+ * spawning, so a CLI that gates first run on a "trust this folder?" prompt
183
+ * (e.g. antigravity's `agy`) starts trusted and never blocks. Omitted for
184
+ * CLIs without such a gate. See pre-launch-trust.ts.
185
+ */
186
+ pre_launch_trust?: PreLaunchTrust;
187
+ send_message: {
188
+ submit_key: string;
189
+ delay_ms_before_submit?: number;
190
+ delay_ms_per_char?: number;
191
+ };
192
+ sections: Record<string, SectionDef>;
193
+ states: FsmState[];
194
+ transitions: FsmTransition[];
195
+ control_bar?: Control[];
196
+ notifications?: NotificationRule[];
197
+ delegate?: DelegateTrigger[];
198
+ native_history?: NativeHistoryConfig;
199
+ requiresFinalAssistantBeforeIdle?: boolean;
200
+ }
201
+
202
+ export function isV4Spec(raw: unknown): raw is CliSpecV4 {
203
+ return !!raw && typeof raw === 'object'
204
+ && (raw as { $schema?: string }).$schema === 'adhdev:cli/spec@4';
205
+ }
206
+
207
+ export function initialState(spec: CliSpecV4): FsmState {
208
+ return spec.states.find(s => s.initial) ?? spec.states[0];
209
+ }
210
+
211
+ export function stateById(spec: CliSpecV4, id: string): FsmState | undefined {
212
+ return spec.states.find(s => s.id === id);
213
+ }
214
+
215
+ /** Outgoing transitions from `stateId`, highest priority first, declaration
216
+ * order as tiebreak. Includes wildcard ("*") and list-membership sources. */
217
+ export function outgoingTransitions(spec: CliSpecV4, stateId: string): FsmTransition[] {
218
+ const matches = spec.transitions.filter(t => {
219
+ if (t.from === '*') return true;
220
+ if (Array.isArray(t.from)) return t.from.includes(stateId);
221
+ return t.from === stateId;
222
+ });
223
+ // Stable sort by priority desc; Array.prototype.sort is stable in V8 so
224
+ // equal-priority edges keep declaration order.
225
+ return matches
226
+ .map((t, i) => ({ t, i }))
227
+ .sort((a, b) => (b.t.priority ?? 0) - (a.t.priority ?? 0) || a.i - b.i)
228
+ .map(x => x.t);
229
+ }
230
+
231
+ /** Map a state to the dashboard status string, applying the documented
232
+ * defaults when `status` is not explicit. */
233
+ export function statusForState(state: FsmState): 'idle' | 'generating' | 'approval' {
234
+ if (state.status) return state.status;
235
+ if (state.modal) return 'approval';
236
+ if (state.id === 'busy' || state.id === 'generating') return 'generating';
237
+ return 'idle';
238
+ }