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

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 +52 -13
  37. package/dist/index.js +39739 -14302
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41369 -16055
  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 +419 -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 +146 -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 +623 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2224 -0
  205. package/src/mesh/mesh-events-pending.ts +558 -0
  206. package/src/mesh/mesh-events-stale.ts +290 -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 +1660 -0
  221. package/src/mesh/mesh-task-stats.ts +154 -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,1065 @@
1
+ /**
2
+ * FsmDriver — runs an adhdev:cli/spec@4 finite state machine against a PTY.
3
+ *
4
+ * Drop-in compatible with SpecDriver's public surface (subscribe / dispatch /
5
+ * start / snapshot / getStateHistory / getDebugState / …) so the cli-adapter
6
+ * can use either driver behind one interface. The difference is entirely
7
+ * internal: instead of a stack of hard-coded debounce layers, this driver
8
+ * holds ONE piece of state — the current FSM node — and on every screen change
9
+ * asks the FSM evaluator "which outgoing transition fires?". All timing
10
+ * (startup grace, busy hold, completion stability) is expressed in the spec as
11
+ * transition guards (min_hold_ms) and time conditions (elapsed_ms / stable_ms).
12
+ *
13
+ * Because the engine carries no CLI knowledge, the only way it can be "wrong"
14
+ * is if a spec's transitions are wrong — and that is fully inspectable via
15
+ * getFsmDebug(), which reports every outgoing transition with its per-condition
16
+ * match result and countdown. That is the contract: debug the spec, not the
17
+ * engine.
18
+ */
19
+ 'use strict';
20
+
21
+ import * as fs from 'node:fs';
22
+ import * as os from 'node:os';
23
+ import * as path from 'node:path';
24
+ import { TerminalAdapter, type TerminalAdapterOpts } from './adapter.js';
25
+ import { resolveCliSpawnPlanFromParts } from '../../cli-adapters/provider-cli-runtime.js';
26
+ import type { PtyTransportFactory } from '../../cli-adapters/pty-transport.js';
27
+ import { DEFAULT_SESSION_HOST_COLS, DEFAULT_SESSION_HOST_ROWS } from '@adhdev/session-host-core';
28
+ import {
29
+ resolveSections, sectionText, extractTitle, extractButtonsFromRule,
30
+ type ResolvedSection, type TraceEntry,
31
+ } from './evaluator.js';
32
+ import { evaluateFsm, type FsmClock, type TransitionEval, type FsmEvaluation } from './fsm-evaluator.js';
33
+ import {
34
+ type CliSpecV4, type FsmState, type FsmTransition,
35
+ initialState, stateById, statusForState, outgoingTransitions,
36
+ } from './fsm-types.js';
37
+ import { loadFsmSpec } from './fsm-loader.js';
38
+ import { applyPreLaunchTrust } from './pre-launch-trust.js';
39
+ import type { Control, DelegateTrigger } from './types.js';
40
+ import { LOG } from '../../logging/logger.js';
41
+
42
+ // ── Shared driver types (formerly in driver.ts) ───────────────────────────
43
+
44
+ export type DashboardEvent =
45
+ | { kind: 'pty_data'; chunk: string }
46
+ | { kind: 'state_changed'; state: { id: string; label: string; title: string | null; status: 'idle' | 'generating' | 'approval' };
47
+ modal: { title: string | null; buttons: { index: number; label: string }[] } | null;
48
+ controls: { id: string; label: string; action_type: string }[] }
49
+ | { kind: 'notification'; id: string; title: string; body: string }
50
+ | { kind: 'delegate'; id: string; task: string }
51
+ | { kind: 'spec_trace'; entries: TraceEntry[] }
52
+ | { kind: 'exit'; exit_code: number }
53
+ | { kind: 'spec_error'; errors: string[] };
54
+
55
+ export type DashboardCommand =
56
+ | { kind: 'send_message'; text: string }
57
+ | { kind: 'pty_write'; data: string }
58
+ | { kind: 'click_control'; control_id: string; payload?: unknown }
59
+ | { kind: 'click_modal_button'; index: number }
60
+ | { kind: 'attach_image'; blob: string; mime: string }
61
+ | { kind: 'resize'; cols: number; rows: number }
62
+ | { kind: 'cancel' }
63
+ | { kind: 'shutdown' };
64
+
65
+ export interface DriverHistoryEntry {
66
+ stateId: string;
67
+ label: string;
68
+ at: number;
69
+ durationMs: number;
70
+ reason: string;
71
+ matchedStateId?: string;
72
+ matchedRules?: string[];
73
+ debounceKind?: string;
74
+ idleHoldMs?: number;
75
+ busyHoldMs?: number;
76
+ via?: string;
77
+ }
78
+
79
+ /**
80
+ * A frozen snapshot of the FULL FSM evaluation captured at the instant a
81
+ * transition fired — the rich `transitions[]` table (per-transition eligible /
82
+ * hold countdown / per-condition CondResult + remainingMs) that `getFsmDebug()`
83
+ * otherwise only computes live for the current instant. Kept in a separate ring
84
+ * buffer from `stateHistory` (which stays intentionally lightweight) so the
85
+ * "why did this rule fire just before the transition" question is answerable
86
+ * after the fact. before-only: this is the evaluation that PRODUCED the
87
+ * transition, not the post-transition state.
88
+ */
89
+ export interface FsmSnapshotEntry {
90
+ /** State we transitioned out of. */
91
+ stateFrom: string;
92
+ /** State we transitioned into (the fired transition's destination). */
93
+ stateTo: string;
94
+ /** Wall-clock time the transition committed (ms). */
95
+ at: number;
96
+ /** The fired transition's destination state id (== stateTo; kept explicit
97
+ * to mirror the rule that fired). */
98
+ firedTo: string;
99
+ /** Human label of the fired transition (e.g. "approval→busy"). */
100
+ firedLabel: string;
101
+ /** Why-it-fired summary, same shape produced for stateHistory.matchedRules. */
102
+ reason: string[];
103
+ /** Every outgoing transition from `stateFrom` as evaluated at `at`, each
104
+ * with its eligible / hold / per-condition CondResult + remainingMs. This
105
+ * is the full pre-transition evaluation table — the whole point of the
106
+ * snapshot. */
107
+ transitions: TransitionEval[];
108
+ }
109
+
110
+ export interface ISpecDriver {
111
+ subscribe(listener: (ev: DashboardEvent) => void): () => void;
112
+ start(): void;
113
+ dispatch(cmd: DashboardCommand): void;
114
+ snapshot(): string;
115
+ getCursorPosition(): { row: number; col: number };
116
+ getScreen(): string;
117
+ getSpecPath(): string;
118
+ shutdown(): void;
119
+ getStateHistory(): ReadonlyArray<DriverHistoryEntry>;
120
+ getSections(): Array<{ id: string; text: string }> | null;
121
+ getLastBusyAt(): number;
122
+ hasIdleHoldPending(): boolean;
123
+ getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null;
124
+ getFsmDebug?(): unknown;
125
+ getFsmSnapshotHistory?(): ReadonlyArray<FsmSnapshotEntry>;
126
+ }
127
+
128
+ export interface SpecDriverOpts {
129
+ specPath: string;
130
+ workingDir: string;
131
+ extraEnv?: Record<string, string>;
132
+ cols?: number;
133
+ rows?: number;
134
+ hotReload?: boolean;
135
+ emitTrace?: boolean;
136
+ transportFactory?: PtyTransportFactory;
137
+ extraCliArgs?: string[];
138
+ }
139
+
140
+ function countNewlines(s: string): number {
141
+ let n = 0;
142
+ for (let i = 0; i < s.length; i += 1) if (s.charCodeAt(i) === 10) n += 1;
143
+ return n;
144
+ }
145
+
146
+ const SUBMIT_DELAY_FLOOR_MS = 200;
147
+
148
+ // win32 ConPTY submit reliability. A MULTILINE message creates an Ink
149
+ // paste/newline-accumulation window during which a lone CR is absorbed as a
150
+ // literal newline instead of submitting; the window's length is
151
+ // nondeterministic (observed 0–~2s, driven by ConPTY byte timing), so neither a
152
+ // fixed delay nor a fixed CR count reliably submits. (A/B PTY testing on win32
153
+ // ConPTY: single-line submits on the FIRST CR; multiline needs a *variable*
154
+ // number of CRs as the window expires — a fixed double-CR fails outright, and
155
+ // bracketed-paste wrapping does NOT help.) So we VERIFY instead of guessing:
156
+ // write the text, then resend the submit key on a fixed cadence until the FSM
157
+ // observes the agent has actually left the idle composer (status flips away from
158
+ // 'idle' — i.e. it submitted and is generating / showing a modal), bounded by a
159
+ // retry budget. Once submission is observed we stop so we don't spam Enter into
160
+ // the next turn. Single-line messages satisfy the check after the first CR, so
161
+ // their behaviour is unchanged. CRs absorbed as newlines during the window are
162
+ // trimmed by the TUI on submit.
163
+ const WIN32_SUBMIT_RESEND_GAP_MS = 350;
164
+ const WIN32_SUBMIT_MAX_RESENDS = 14;
165
+
166
+ export function resolveSubmitDelayMs(specBeforeSubmit: number | undefined, text: string): number {
167
+ const lines = countNewlines(text);
168
+ const linesBonus = Math.min(800, lines * 80);
169
+ const spec = typeof specBeforeSubmit === 'number' && specBeforeSubmit > 0 ? specBeforeSubmit : 0;
170
+ return Math.max(spec, SUBMIT_DELAY_FLOOR_MS + linesBonus);
171
+ }
172
+
173
+ export function guessExt(mime: string): string {
174
+ if (/png/i.test(mime)) return '.png';
175
+ if (/jpe?g/i.test(mime)) return '.jpg';
176
+ if (/gif/i.test(mime)) return '.gif';
177
+ if (/webp/i.test(mime)) return '.webp';
178
+ return '.bin';
179
+ }
180
+
181
+ // ─────────────────────────────────────────────────────────────────────────────
182
+
183
+ interface ModalSnapshot {
184
+ title: string | null;
185
+ buttons: { index: number; label: string; key: string }[];
186
+ }
187
+
188
+ interface VisibleControl {
189
+ id: string;
190
+ label: string;
191
+ actionType: 'send_keys' | 'open_picker' | 'attach_image';
192
+ }
193
+
194
+ type HistoryEntry = DriverHistoryEntry;
195
+
196
+ /** Per-state evaluation snapshot (mirrors v3 SpecEvaluation shape for the
197
+ * parts the cli-adapter / panel consume). */
198
+ interface CurrentEval {
199
+ state: { id: string; label: string; title: string | null; status: 'idle' | 'generating' | 'approval' };
200
+ modal: ModalSnapshot | null;
201
+ controls: VisibleControl[];
202
+ }
203
+
204
+ export class FsmDriver implements ISpecDriver {
205
+ private spec!: CliSpecV4;
206
+ private adapter: TerminalAdapter;
207
+ private listeners = new Set<(ev: DashboardEvent) => void>();
208
+
209
+ // ── The entire FSM state: which node we're in, and when we entered it.
210
+ private currentStateId = '';
211
+ private stateEnteredAt = 0;
212
+
213
+ // ── Clock bookkeeping for time conditions.
214
+ private startedAtMs = 0;
215
+ private prevScreenLines: string[] = [];
216
+ /** Per cursor_above region (key: cursor_above, -1 = whole screen) → last
217
+ * time that region's content changed. Drives stable_ms conditions. */
218
+ private regionLastChangedAt = new Map<number, number>();
219
+ /** Timer that re-runs evaluate() when a time-condition would flip true
220
+ * with no PTY frame to trigger it. */
221
+ private wakeTimer: ReturnType<typeof setTimeout> | null = null;
222
+ /** Timer driving the focus-gated stall watchdog (refocus_when_stalled_ms).
223
+ * Re-arms itself while the machine is generating so a re-prime can fire
224
+ * even when the PTY has gone completely quiet. */
225
+ private stallTimer: ReturnType<typeof setTimeout> | null = null;
226
+ /** Wall-clock time the last stall re-prime was injected. The cooldown gate:
227
+ * after a re-prime we don't re-inject until the screen changes (which
228
+ * resets the stall reference) or another full stall window lapses. */
229
+ private lastRefocusAt = 0;
230
+ /** Timer driving the win32 verification-based submit resend loop (see
231
+ * WIN32_SUBMIT_* and scheduleWin32Submit). Re-arms itself until the FSM
232
+ * leaves idle (submitted) or the resend budget is spent. */
233
+ private win32SubmitTimer: ReturnType<typeof setTimeout> | null = null;
234
+
235
+ private currentEval: CurrentEval | null = null;
236
+ private stateHistory: HistoryEntry[] = [];
237
+ private prevStateAt = 0;
238
+
239
+ // ── send_message queueing until the machine first reaches a non-initial,
240
+ // non-busy ("ready") state — same contract as v3's idleSeenOnce.
241
+ private readySeenOnce = false;
242
+ private pendingSends: string[] = [];
243
+
244
+ private pickerInProgress: { control_id: string; spec: Control } | null = null;
245
+ private delegateTimers = new Map<string, ReturnType<typeof setTimeout>>();
246
+ private specWatcher: fs.FSWatcher | null = null;
247
+ /** Last full FSM evaluation, kept for the debugger. */
248
+ private lastFsmEval: ReturnType<typeof evaluateFsm> | null = null;
249
+ /** Ring buffer (max 20) of the full FSM evaluation captured at each
250
+ * transition — the rich pre-transition table that lastFsmEval only keeps
251
+ * for the single most recent evaluation. Separate from stateHistory. */
252
+ private fsmSnapshotHistory: FsmSnapshotEntry[] = [];
253
+
254
+ constructor(private readonly opts: SpecDriverOpts) {
255
+ this.loadSpecOrThrow();
256
+ this.adapter = new TerminalAdapter(
257
+ this.buildAdapterOpts(),
258
+ {
259
+ init: () => this.emitInitialState(),
260
+ on_pty_data: (chunk) => this.emit({ kind: 'pty_data', chunk }),
261
+ on_screen_changed: () => this.reevaluate(),
262
+ on_exit: ({ exitCode }) => this.handleExit(exitCode),
263
+ },
264
+ );
265
+ if (this.opts.hotReload !== false) this.armSpecWatcher();
266
+ }
267
+
268
+ subscribe(listener: (ev: DashboardEvent) => void): () => void {
269
+ this.listeners.add(listener);
270
+ return () => { this.listeners.delete(listener); };
271
+ }
272
+
273
+ start(): void {
274
+ const now = Date.now();
275
+ this.startedAtMs = now;
276
+ const init = initialState(this.spec);
277
+ this.currentStateId = init.id;
278
+ this.stateEnteredAt = now;
279
+ this.prevStateAt = now;
280
+ // Pre-trust the workspace before spawning so a first-run folder-trust
281
+ // prompt never appears (best-effort; failures fall back to the FSM's
282
+ // trust-modal detection). Only runs for specs that declare it.
283
+ if (this.spec.pre_launch_trust) {
284
+ applyPreLaunchTrust(this.spec.pre_launch_trust, this.opts.workingDir);
285
+ }
286
+ this.adapter.start();
287
+ // Prime focus-gated TUIs (see CliSpecV4.send_on_spawn). Written once,
288
+ // shortly after spawn, so the input stream is awake before the first
289
+ // delegated message — without this, a focus-event CLI like antigravity
290
+ // drops the first programmatic write until a manual keystroke.
291
+ this.scheduleSpawnPrime();
292
+ // The initial state may have a purely time-based exit (elapsed_ms);
293
+ // schedule a wake so we leave it even if the PTY goes quiet.
294
+ this.scheduleWakeForState();
295
+ }
296
+
297
+ private scheduleSpawnPrime(): void {
298
+ const seqs = this.spec.send_on_spawn;
299
+ if (!Array.isArray(seqs) || seqs.length === 0) return;
300
+ const delay = Math.max(0, this.spec.send_on_spawn_delay_ms ?? 250);
301
+ setTimeout(() => this.sendSpawnPrime(), delay);
302
+ }
303
+
304
+ /** Write the declared `send_on_spawn` sequences to the PTY once. Used both
305
+ * at spawn (scheduleSpawnPrime) and, for focus-gated TUIs, by the stall
306
+ * watchdog to re-inject the focus-in wake mid-turn. No-op when the spec
307
+ * declares no prime, so non-focus-gated CLIs are never poked. */
308
+ private sendSpawnPrime(): void {
309
+ const seqs = this.spec.send_on_spawn;
310
+ if (!Array.isArray(seqs) || seqs.length === 0) return;
311
+ for (const seq of seqs) {
312
+ if (typeof seq === 'string' && seq.length > 0) this.adapter.send_keys(seq);
313
+ }
314
+ }
315
+
316
+ dispatch(cmd: DashboardCommand): void {
317
+ switch (cmd.kind) {
318
+ case 'send_message': this.handleSendMessage(cmd.text); return;
319
+ case 'pty_write': this.adapter.send_keys(cmd.data); return;
320
+ case 'click_control': this.handleClickControl(cmd.control_id, cmd.payload); return;
321
+ case 'click_modal_button': this.handleClickModalButton(cmd.index); return;
322
+ case 'attach_image': this.handleAttachImage(cmd.blob, cmd.mime); return;
323
+ case 'resize': this.adapter.resize(cmd.cols, cmd.rows); return;
324
+ case 'cancel': this.adapter.send_keys('\x03'); return;
325
+ case 'shutdown': this.shutdown(); return;
326
+ }
327
+ }
328
+
329
+ snapshot(): string { return this.adapter.snapshot(); }
330
+ getCursorPosition(): { row: number; col: number } { return this.adapter.getCursorPosition(); }
331
+ getScreen(): string { return this.adapter.snapshot(); }
332
+
333
+ /** Scrollback-inclusive screen as line array — used only for modal/button
334
+ * content extraction so a tall prompt's off-screen anchors stay matchable.
335
+ * Falls back to the viewport snapshot if scrollback read is unavailable. */
336
+ private scrollbackLines(): string[] {
337
+ let screen = '';
338
+ try {
339
+ screen = this.adapter.snapshotWithScrollback();
340
+ } catch { /* fall through to viewport */ }
341
+ if (!screen) screen = this.adapter.snapshot();
342
+ return screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
343
+ }
344
+ getSpecPath(): string { return this.opts.specPath; }
345
+
346
+ shutdown(): void {
347
+ for (const t of this.delegateTimers.values()) clearTimeout(t);
348
+ this.delegateTimers.clear();
349
+ if (this.wakeTimer) { clearTimeout(this.wakeTimer); this.wakeTimer = null; }
350
+ if (this.stallTimer) { clearTimeout(this.stallTimer); this.stallTimer = null; }
351
+ if (this.win32SubmitTimer) { clearTimeout(this.win32SubmitTimer); this.win32SubmitTimer = null; }
352
+ this.specWatcher?.close();
353
+ this.adapter.kill();
354
+ }
355
+
356
+ // ── Debug surface (the whole reason for the rewrite) ──────────────────
357
+ //
358
+ // getFsmDebug() answers, for the CURRENT instant: which state am I in,
359
+ // how long have I been here, and for every outgoing transition — does its
360
+ // guard pass right now, and if not, which sub-condition is blocking and
361
+ // how many ms until it would flip. No screenshots required.
362
+
363
+ getFsmDebug(): {
364
+ currentState: string;
365
+ label: string;
366
+ stateAgeMs: number;
367
+ status: string;
368
+ cursor: { row: number; col: number };
369
+ transitions: TransitionEval[];
370
+ } {
371
+ const now = Date.now();
372
+ const cursor = this.adapter.getCursorPosition();
373
+ const screen = this.adapter.snapshot();
374
+ const ev = this.evalFsmNow(screen, cursor, now);
375
+ const state = stateById(this.spec, this.currentStateId);
376
+ return {
377
+ currentState: this.currentStateId,
378
+ label: state?.label ?? this.currentStateId,
379
+ stateAgeMs: now - this.stateEnteredAt,
380
+ status: state ? statusForState(state) : 'idle',
381
+ cursor,
382
+ transitions: ev.transitions,
383
+ };
384
+ }
385
+
386
+ getStateHistory(): ReadonlyArray<HistoryEntry> { return this.stateHistory; }
387
+ getFsmSnapshotHistory(): ReadonlyArray<FsmSnapshotEntry> { return this.fsmSnapshotHistory; }
388
+ getSections(): Array<{ id: string; text: string }> | null {
389
+ try {
390
+ const screen = this.adapter.snapshot();
391
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
392
+ return resolveSections(this.spec.sections ?? {}, lines).map(s => ({ id: s.id, text: s.text }));
393
+ } catch { return null; }
394
+ }
395
+
396
+ /** v3-compat shims so the cli-adapter's existing debug snapshot keeps
397
+ * working without branching on driver type. */
398
+ getLastBusyAt(): number {
399
+ // Approximate: time we entered a generating-status state.
400
+ const st = stateById(this.spec, this.currentStateId);
401
+ return st && statusForState(st) === 'generating' ? this.stateEnteredAt : 0;
402
+ }
403
+ hasIdleHoldPending(): boolean {
404
+ // FSM has no separate idle-hold timer; min_hold_ms is the analog.
405
+ // Report true while any outgoing transition is hold-blocked.
406
+ return (this.lastFsmEval?.transitions ?? []).some(t => !t.holdSatisfied && t.condResult);
407
+ }
408
+ getCompletionIdleDebounceState(): { active: boolean; ageMs: number; holdMs: number; forceAfterMs: number } | null {
409
+ // Surface the busy→ready transition's stable countdown, if any, so the
410
+ // existing panel field stays meaningful.
411
+ const out = outgoingTransitions(this.spec, this.currentStateId);
412
+ const toReady = this.lastFsmEval?.transitions.find((t, i) => {
413
+ const st = stateById(this.spec, out[i]?.to ?? '');
414
+ return st && statusForState(st) === 'idle';
415
+ });
416
+ if (!toReady || !toReady.cond) return null;
417
+ const stable = findStable(toReady.cond);
418
+ if (!stable) return null;
419
+ return { active: true, ageMs: 0, holdMs: stable.totalMs, forceAfterMs: 0 };
420
+ }
421
+
422
+ // ────────────────────────────────────────────────────────────────────
423
+ // Loading & adapter wiring
424
+ // ────────────────────────────────────────────────────────────────────
425
+
426
+ private loadSpecOrThrow(): void {
427
+ const res = loadFsmSpec(this.opts.specPath);
428
+ if (!res.ok) throw new Error(`fsm spec invalid: ${res.errors.join('; ')}`);
429
+ this.spec = res.spec;
430
+ }
431
+
432
+ private buildAdapterOpts(): TerminalAdapterOpts {
433
+ // Single-source spawn resolution: route the spec's binary/args/env
434
+ // through the SAME planner the legacy ProviderCliAdapter uses
435
+ // (resolveCliSpawnPlanFromParts). This gives the spec/FSM path
436
+ // findBinary (PATH + npm-global / Node-dir fallback so an off-PATH
437
+ // `codex`/`claude` resolves), `{{workingDir}}` token substitution, shell
438
+ // wrapping for script-shims / non-absolute / non-native binaries, and a
439
+ // sanitized env with TERMINAL_CWD — none of which it had when it passed
440
+ // `this.spec.binary` straight to the PTY.
441
+ const cols = this.opts.cols ?? DEFAULT_SESSION_HOST_COLS;
442
+ const rows = this.opts.rows ?? DEFAULT_SESSION_HOST_ROWS;
443
+ const plan = resolveCliSpawnPlanFromParts({
444
+ command: this.spec.binary,
445
+ baseArgs: this.spec.spawn_args ?? [],
446
+ baseEnv: this.spec.env ?? {},
447
+ workingDir: this.opts.workingDir,
448
+ extraArgs: this.opts.extraCliArgs ?? [],
449
+ extraEnv: this.opts.extraEnv ?? {},
450
+ geometry: { cols, rows },
451
+ });
452
+ return {
453
+ binary: plan.shellCmd,
454
+ args: plan.shellArgs,
455
+ cwd: plan.ptyOptions.cwd,
456
+ // plan.ptyOptions.env is already a complete, sanitized environment —
457
+ // pass it verbatim, do not overlay process.env (see envIsComplete).
458
+ env: plan.ptyOptions.env,
459
+ envIsComplete: true,
460
+ cols,
461
+ rows,
462
+ transportFactory: this.opts.transportFactory,
463
+ };
464
+ }
465
+
466
+ private armSpecWatcher(): void {
467
+ try {
468
+ const dir = path.dirname(this.opts.specPath);
469
+ const base = path.basename(this.opts.specPath);
470
+ this.specWatcher = fs.watch(dir, { persistent: false }, (_event, filename) => {
471
+ if (filename && filename !== base) return;
472
+ const res = loadFsmSpec(this.opts.specPath);
473
+ if (!res.ok) {
474
+ this.emit({ kind: 'spec_error', errors: res.errors });
475
+ return;
476
+ }
477
+ this.spec = res.spec;
478
+ LOG.info('FsmDriver', `[${this.specTag()}] spec hot-reloaded`);
479
+ // Re-evaluate immediately with the new transitions.
480
+ this.reevaluate(true);
481
+ });
482
+ } catch { /* best-effort */ }
483
+ }
484
+
485
+ private emitInitialState(): void {
486
+ this.reevaluate(true);
487
+ }
488
+
489
+ // ────────────────────────────────────────────────────────────────────
490
+ // Core: evaluate the FSM and commit transitions
491
+ // ────────────────────────────────────────────────────────────────────
492
+
493
+ private buildClock(now: number): FsmClock {
494
+ return {
495
+ now,
496
+ stateEnteredAt: this.stateEnteredAt,
497
+ regionLastChangedAt: this.regionLastChangedAt,
498
+ };
499
+ }
500
+
501
+ private evalFsmNow(screen: string, cursor: { row: number; col: number }, now: number) {
502
+ const prev = this.prevScreenLines.length > 0 ? this.prevScreenLines : undefined;
503
+ return evaluateFsm(this.spec, this.currentStateId, screen, cursor, prev, this.buildClock(now));
504
+ }
505
+
506
+ private reevaluate(forceEmit = false): void {
507
+ const now = Date.now();
508
+ const screen = this.adapter.snapshot();
509
+ const cursor = this.adapter.getCursorPosition();
510
+ const currentLines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
511
+
512
+ // Track per-region change timestamps for stable_ms conditions BEFORE
513
+ // we overwrite prevScreenLines.
514
+ this.trackRegionChanges(currentLines, cursor, now);
515
+
516
+ const ev = this.evalFsmNow(screen, cursor, now);
517
+ this.lastFsmEval = ev;
518
+ this.prevScreenLines = currentLines;
519
+
520
+ if (ev.fired) {
521
+ this.commitTransition(ev.fired, now, ev);
522
+ // After a transition, immediately re-derive controls/modal for the
523
+ // new state and emit. Re-run once so a chain like approval→busy
524
+ // that's already satisfied doesn't wait for the next PTY frame.
525
+ this.emitStateChanged(forceEmit);
526
+ this.scheduleWakeForState();
527
+ this.scheduleStallWatchdog();
528
+ // Drain queued sends on the SAME frame the machine reaches "ready".
529
+ // The first delegated message is queued in pendingSends until the
530
+ // FSM first enters a non-initial idle state (the prompt is drawn).
531
+ // That readiness is normally reached BY a transition (e.g.
532
+ // signing_in→idle / starting→idle) — and an idle state has no
533
+ // pending time-condition, so scheduleWakeForState() arms no timer
534
+ // and, agy being quiet at the prompt, no further PTY frame arrives.
535
+ // Without this call the queued first message would strand here
536
+ // forever (the "first input never processed" bug). maybeMarkReady is
537
+ // idempotent (guarded by readySeenOnce) so calling it on both
538
+ // branches is safe.
539
+ this.maybeMarkReady();
540
+ return;
541
+ }
542
+
543
+ // No transition — refresh modal/controls (content inside the same
544
+ // state can still change, e.g. modal title/buttons) and emit if changed.
545
+ this.emitStateChanged(forceEmit);
546
+ // Schedule a wake for the soonest pending time-condition.
547
+ this.scheduleWakeForState();
548
+ this.scheduleStallWatchdog();
549
+ // Drain queued sends once we first reach a "ready" state.
550
+ this.maybeMarkReady();
551
+ }
552
+
553
+ private commitTransition(fired: TransitionEval, now: number, ev: FsmEvaluation): void {
554
+ const from = this.currentStateId;
555
+ // Capture the full pre-transition evaluation BEFORE we mutate state, so
556
+ // the snapshot records why this transition fired from `from`.
557
+ this.pushFsmSnapshot(from, fired, now, ev);
558
+ this.currentStateId = fired.to;
559
+ this.stateEnteredAt = now;
560
+ // Region change timestamps are relative to the previous state's
561
+ // activity; reset so stable_ms in the new state measures from entry.
562
+ this.regionLastChangedAt.clear();
563
+ this.pushHistory(fired.to, stateById(this.spec, fired.to)?.label ?? fired.to, {
564
+ reason: 'transition',
565
+ via: `${from}→${fired.to}`,
566
+ matchedRules: summarizeTransition(fired),
567
+ });
568
+ LOG.info('FsmDriver', `[${this.specTag()}] ${from} → ${fired.to} (${fired.label})`);
569
+ }
570
+
571
+ /** Snapshot the full FSM evaluation that produced a transition into the
572
+ * separate fsmSnapshotHistory ring buffer (max 20). The transitions[]
573
+ * table is captured by reference — it is freshly built per evaluation in
574
+ * evaluateFsm and never mutated after, so no clone is needed. */
575
+ private pushFsmSnapshot(from: string, fired: TransitionEval, now: number, ev: FsmEvaluation): void {
576
+ this.fsmSnapshotHistory.push({
577
+ stateFrom: from,
578
+ stateTo: fired.to,
579
+ at: now,
580
+ firedTo: fired.to,
581
+ firedLabel: fired.label,
582
+ reason: summarizeTransition(fired),
583
+ transitions: ev.transitions,
584
+ });
585
+ if (this.fsmSnapshotHistory.length > 20) this.fsmSnapshotHistory.shift();
586
+ }
587
+
588
+ /** Re-derive the visible modal + controls for the current state and emit a
589
+ * state_changed if anything differs from the last emit. */
590
+ private emitStateChanged(forceEmit: boolean): void {
591
+ const state = stateById(this.spec, this.currentStateId);
592
+ if (!state) return;
593
+ const screen = this.adapter.snapshot();
594
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
595
+ const sections = resolveSections(this.spec.sections ?? {}, lines);
596
+
597
+ // Modal states (approval / picker) extract their buttons + title from a
598
+ // SCROLLBACK-INCLUSIVE buffer: claude-cli renders an approval as a box,
599
+ // and when the prompt body (a big diff / long explanation) is tall the
600
+ // top of the box — including the `─────` separator that anchors the
601
+ // `modal` section — scrolls above the viewport. Matching only the
602
+ // viewport then yields < min_count buttons, deriveModal returns null,
603
+ // and auto-approve never fires (the "long prompts never auto-approve"
604
+ // bug). The viewport stays authoritative for transitions / cursor
605
+ // conditions; only this content-pattern extraction reads scrollback.
606
+ const modalLines = state.modal
607
+ ? this.scrollbackLines()
608
+ : lines;
609
+ const modalSections = state.modal
610
+ ? resolveSections(this.spec.sections ?? {}, modalLines)
611
+ : sections;
612
+ const modalFullScreen = modalLines.join('\n');
613
+
614
+ const modal = this.deriveModal(state, modalSections, modalFullScreen);
615
+ const controls = this.deriveControls(state.id);
616
+ const title = modal?.title ?? this.deriveTitle(state, modalSections, modalFullScreen);
617
+
618
+ const next: CurrentEval = {
619
+ // status is derived from the FSM state itself (statusForState), NOT from
620
+ // whether a modal was parsed this frame. A modal state whose buttons briefly
621
+ // fail to parse (PTY repaint → deriveModal returns null) must still report
622
+ // its authoritative status (e.g. 'approval'), so the adapter never collapses
623
+ // an approval/busy state to idle on a transient modal-parse miss.
624
+ state: { id: state.id, label: state.label, title, status: statusForState(state) },
625
+ modal,
626
+ controls,
627
+ };
628
+
629
+ const changed = forceEmit
630
+ || !this.currentEval
631
+ || this.currentEval.state.id !== next.state.id
632
+ || this.currentEval.state.title !== next.state.title
633
+ || !sameModal(this.currentEval.modal, next.modal)
634
+ || !sameControls(this.currentEval.controls, next.controls);
635
+
636
+ this.currentEval = next;
637
+ if (this.pickerInProgress) this.tryAdvancePicker(screen);
638
+
639
+ if (changed) {
640
+ this.emit({
641
+ kind: 'state_changed',
642
+ state: next.state,
643
+ modal: next.modal ? { title: next.modal.title, buttons: next.modal.buttons.map(b => ({ index: b.index, label: b.label })) } : null,
644
+ controls: next.controls.map(c => ({ id: c.id, label: c.label, action_type: c.actionType })),
645
+ });
646
+ this.fireNotifications(state.id, title);
647
+ this.armOrCancelDelegateTimers(state.id);
648
+ }
649
+ }
650
+
651
+ private deriveModal(state: FsmState, sections: ResolvedSection[], fullScreen: string): ModalSnapshot | null {
652
+ const rule = state.extract?.buttons;
653
+ if (!rule) return null;
654
+ const hay = sectionText(sections, rule.section, fullScreen);
655
+ const minCount = rule.min_count ?? 2;
656
+ const buttons = extractButtonsFromRule(rule, hay);
657
+ if (buttons.length < minCount) return null;
658
+ const title = this.deriveTitle(state, sections, fullScreen);
659
+ return { title, buttons };
660
+ }
661
+
662
+ private deriveTitle(state: FsmState, sections: ResolvedSection[], fullScreen: string): string | null {
663
+ const rule = state.extract?.title;
664
+ if (!rule) return null;
665
+ return extractTitle(rule, sections, fullScreen);
666
+ }
667
+
668
+ private deriveControls(stateId: string): VisibleControl[] {
669
+ const out: VisibleControl[] = [];
670
+ for (const c of this.spec.control_bar ?? []) {
671
+ if (c.visible_when_state && !c.visible_when_state.includes(stateId)) continue;
672
+ out.push({ id: c.id, label: c.label, actionType: c.action.type });
673
+ }
674
+ return out;
675
+ }
676
+
677
+ /** Track which cursor_above regions changed since the previous frame so
678
+ * stable_ms conditions can measure quiet time. We record every region
679
+ * size referenced by a stable_ms condition in the spec, plus the whole
680
+ * screen (-1). */
681
+ private trackRegionChanges(currentLines: string[], cursor: { row: number; col: number }, now: number): void {
682
+ if (this.prevScreenLines.length === 0) return;
683
+ const sizes = this.stableRegionSizes();
684
+ for (const size of sizes) {
685
+ let cur: string; let prev: string;
686
+ if (size < 0) {
687
+ cur = currentLines.join('\n');
688
+ prev = this.prevScreenLines.join('\n');
689
+ } else {
690
+ const start = Math.max(0, cursor.row - size);
691
+ cur = currentLines.slice(start, cursor.row).join('\n');
692
+ prev = this.prevScreenLines.slice(start, cursor.row).join('\n');
693
+ }
694
+ if (cur !== prev) this.regionLastChangedAt.set(size, now);
695
+ }
696
+ }
697
+
698
+ /** All cursor_above region sizes referenced by stable_ms conditions in the
699
+ * current state's outgoing transitions, plus whole-screen. Cached lazily
700
+ * per spec load would be nicer but the set is tiny. */
701
+ private stableRegionSizes(): Set<number> {
702
+ const sizes = new Set<number>([-1]);
703
+ for (const t of outgoingTransitions(this.spec, this.currentStateId)) {
704
+ collectStableSizes(t.when, sizes);
705
+ }
706
+ return sizes;
707
+ }
708
+
709
+ /** Schedule a re-evaluation for the soonest pending time-condition on any
710
+ * outgoing transition (elapsed_ms / stable_ms / min_hold_ms). Without
711
+ * this, a state whose only exit is time-based would never leave once the
712
+ * PTY goes quiet. */
713
+ private scheduleWakeForState(): void {
714
+ if (this.wakeTimer) { clearTimeout(this.wakeTimer); this.wakeTimer = null; }
715
+ const ev = this.lastFsmEval;
716
+ if (!ev) return;
717
+ let soonest = Infinity;
718
+ for (const t of ev.transitions) {
719
+ if (t.fires) continue;
720
+ if (!t.holdSatisfied) soonest = Math.min(soonest, t.holdRemainingMs);
721
+ const condRemain = t.cond ? t.cond.remainingMs ?? Infinity : Infinity;
722
+ // Only treat the cond countdown as a wake source when the rest of
723
+ // the guard (hold) is already or will be satisfied.
724
+ if (Number.isFinite(condRemain) && condRemain > 0) soonest = Math.min(soonest, condRemain);
725
+ }
726
+ if (!Number.isFinite(soonest)) return;
727
+ this.wakeTimer = setTimeout(() => { this.wakeTimer = null; this.reevaluate(); }, Math.max(soonest + 30, 50));
728
+ }
729
+
730
+ // ── Focus-gated stall watchdog (refocus_when_stalled_ms) ──────────────────
731
+ //
732
+ // A focus-event TUI (antigravity's `agy`) freezes its render loop the moment
733
+ // it thinks it has lost focus mid-turn: the screen stops updating and only
734
+ // repaints on the next keypress, which the daemon never sends. The output
735
+ // pump is wired entirely to PTY onData (no PTY data → no reevaluate, no
736
+ // on_screen_changed), so a normal time-wake that only re-reads the screen
737
+ // can't help — there is nothing new to read. The fix is to re-inject the
738
+ // focus-in wake (`send_on_spawn`) so the CLI flushes the held output itself.
739
+
740
+ /** True when this spec opts into stall recovery (declares a positive
741
+ * refocus window AND a wake sequence to re-inject). */
742
+ private stallRecoveryEnabled(): boolean {
743
+ const ms = this.spec.refocus_when_stalled_ms;
744
+ return typeof ms === 'number' && ms > 0
745
+ && Array.isArray(this.spec.send_on_spawn) && this.spec.send_on_spawn.length > 0;
746
+ }
747
+
748
+ /** Wall-clock time the screen last changed in the current state, falling
749
+ * back to state entry when it has not changed since (i.e. fully stalled
750
+ * from the start of the state). */
751
+ private lastScreenChangeAt(): number {
752
+ return this.regionLastChangedAt.get(-1) ?? this.stateEnteredAt;
753
+ }
754
+
755
+ /** Arm a timer to re-inject the focus-in prime if the screen stays frozen
756
+ * through a `generating` state. Only active for opted-in focus-gated specs;
757
+ * a no-op (and cleared) for every other CLI and every non-generating state.
758
+ * Re-arms itself so it keeps watching while the PTY is quiet. */
759
+ private scheduleStallWatchdog(): void {
760
+ if (this.stallTimer) { clearTimeout(this.stallTimer); this.stallTimer = null; }
761
+ if (!this.stallRecoveryEnabled()) return;
762
+ const st = stateById(this.spec, this.currentStateId);
763
+ if (!st || statusForState(st) !== 'generating') return;
764
+ const windowMs = this.spec.refocus_when_stalled_ms as number;
765
+ // Cooldown reference: a re-prime defers the next one by a full window,
766
+ // even if the screen has not yet repainted, so we don't tight-loop.
767
+ const since = Math.max(this.lastScreenChangeAt(), this.lastRefocusAt);
768
+ const remaining = windowMs - (Date.now() - since);
769
+ this.stallTimer = setTimeout(
770
+ () => { this.stallTimer = null; this.onStallTick(); },
771
+ Math.max(remaining + 30, 50),
772
+ );
773
+ }
774
+
775
+ /** Fire when the stall window elapses: if the screen is still frozen and we
776
+ * are still generating, re-inject the focus-in wake once, then re-arm. */
777
+ private onStallTick(): void {
778
+ if (!this.stallRecoveryEnabled()) return;
779
+ const st = stateById(this.spec, this.currentStateId);
780
+ if (!st || statusForState(st) !== 'generating') return;
781
+ const windowMs = this.spec.refocus_when_stalled_ms as number;
782
+ const now = Date.now();
783
+ const stalledFor = now - this.lastScreenChangeAt();
784
+ const sinceLastRefocus = now - this.lastRefocusAt;
785
+ if (stalledFor >= windowMs && sinceLastRefocus >= windowMs) {
786
+ LOG.info('FsmDriver', `[${this.specTag()}] stall detected (${stalledFor}ms quiet, generating) — re-injecting focus-in`);
787
+ this.sendSpawnPrime();
788
+ this.lastRefocusAt = now;
789
+ }
790
+ // Keep watching: the re-prime may not flush instantly, and a still-quiet
791
+ // screen needs the next window to come around.
792
+ this.scheduleStallWatchdog();
793
+ }
794
+
795
+ private maybeMarkReady(): void {
796
+ if (this.readySeenOnce) return;
797
+ const st = stateById(this.spec, this.currentStateId);
798
+ if (!st) return;
799
+ // "Ready" = a non-initial state whose status is idle (the prompt is up).
800
+ if (!st.initial && statusForState(st) === 'idle') {
801
+ this.readySeenOnce = true;
802
+ const queued = this.pendingSends.splice(0);
803
+ for (const text of queued) setTimeout(() => this.actuallySendMessage(text), 50);
804
+ }
805
+ }
806
+
807
+ // ────────────────────────────────────────────────────────────────────
808
+ // Notifications & delegates
809
+ // ────────────────────────────────────────────────────────────────────
810
+
811
+ private fireNotifications(stateId: string, title: string | null): void {
812
+ for (const n of this.spec.notifications ?? []) {
813
+ if (n.when_state !== stateId) continue;
814
+ const body = (n.body ?? '').replace(/\{state\.title\}/g, title ?? '');
815
+ this.emit({ kind: 'notification', id: n.id, title: n.title, body });
816
+ }
817
+ }
818
+
819
+ private armOrCancelDelegateTimers(currentStateId: string): void {
820
+ for (const d of this.spec.delegate ?? []) {
821
+ const armed = this.delegateTimers.has(d.id);
822
+ const shouldFire = d.when_state === currentStateId;
823
+ if (shouldFire && !armed) {
824
+ const delay = d.after_duration_ms ?? 0;
825
+ const t = setTimeout(() => { this.fireDelegate(d); this.delegateTimers.delete(d.id); }, delay);
826
+ this.delegateTimers.set(d.id, t);
827
+ } else if (!shouldFire && armed) {
828
+ clearTimeout(this.delegateTimers.get(d.id)!);
829
+ this.delegateTimers.delete(d.id);
830
+ }
831
+ }
832
+ }
833
+
834
+ private fireDelegate(d: DelegateTrigger): void {
835
+ const ev = this.currentEval;
836
+ const task = d.task_template
837
+ .replace(/\{node\}/g, os.hostname())
838
+ .replace(/\{state\.label\}/g, ev?.state.label ?? '')
839
+ .replace(/\{state\.title\}/g, ev?.state.title ?? '')
840
+ .replace(/\{duration_ms\}/g, String(d.after_duration_ms ?? 0));
841
+ this.emit({ kind: 'delegate', id: d.id, task });
842
+ }
843
+
844
+ // ────────────────────────────────────────────────────────────────────
845
+ // Dashboard commands (identical semantics to v3)
846
+ // ────────────────────────────────────────────────────────────────────
847
+
848
+ private handleSendMessage(text: string): void {
849
+ if (!this.readySeenOnce) { this.pendingSends.push(text); return; }
850
+ this.actuallySendMessage(text);
851
+ }
852
+
853
+ private actuallySendMessage(text: string): void {
854
+ const sm = this.spec.send_message;
855
+ const perChar = sm.delay_ms_per_char ?? 0;
856
+ const beforeSubmit = resolveSubmitDelayMs(sm.delay_ms_before_submit, text);
857
+
858
+ // win32 ConPTY submit: the text and the submit key (CR) must NOT be
859
+ // combined into one PTY write — Ink-based TUIs (claude-cli) treat a
860
+ // single write that carries text + a trailing CR as a bracketed/multi-line
861
+ // paste and absorb the CR as a literal newline. So we write the text on
862
+ // its own, then resend the submit key on a fixed cadence, VERIFYING after
863
+ // each that the agent actually left the idle composer (status flipped away
864
+ // from 'idle'). This handles the nondeterministic multiline
865
+ // paste-accumulation window where a variable number of CRs is needed; a
866
+ // fixed double-CR fails for multiline (see WIN32_SUBMIT_* above). perChar
867
+ // typing simulation is skipped on win32; correctness of submission wins
868
+ // over the typing visual there.
869
+ if (process.platform === 'win32') {
870
+ this.adapter.send_keys(text);
871
+ this.scheduleWin32Submit(sm.submit_key, beforeSubmit);
872
+ return;
873
+ }
874
+
875
+ if (perChar === 0) {
876
+ this.adapter.send_keys(text);
877
+ if (beforeSubmit > 0) setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
878
+ else this.adapter.send_keys(sm.submit_key);
879
+ return;
880
+ }
881
+ let i = 0;
882
+ const iv = setInterval(() => {
883
+ if (i >= text.length) {
884
+ clearInterval(iv);
885
+ setTimeout(() => this.adapter.send_keys(sm.submit_key), beforeSubmit);
886
+ return;
887
+ }
888
+ this.adapter.send_keys(text[i]);
889
+ i += 1;
890
+ }, perChar);
891
+ }
892
+
893
+ /** The agent's current coarse status, derived from the FSM node we're in. */
894
+ private currentStatus(): 'idle' | 'generating' | 'approval' {
895
+ const st = stateById(this.spec, this.currentStateId);
896
+ return st ? statusForState(st) : 'idle';
897
+ }
898
+
899
+ /**
900
+ * win32 verification-based submit. Sends the submit key, waits a gap, and if
901
+ * the FSM is still 'idle' (the prompt did not submit — the CR was absorbed as
902
+ * a multiline-paste newline) resends, up to WIN32_SUBMIT_MAX_RESENDS. The
903
+ * first CR always fires (so a stale/edge status never suppresses the submit);
904
+ * subsequent resends are gated on still being idle, and stop the instant the
905
+ * agent leaves idle (submitted → generating / approval). This converges the
906
+ * nondeterministic multiline window without spamming Enter into the next turn.
907
+ */
908
+ private scheduleWin32Submit(submitKey: string, initialDelayMs: number): void {
909
+ if (this.win32SubmitTimer) { clearTimeout(this.win32SubmitTimer); this.win32SubmitTimer = null; }
910
+ const fire = (attempt: number): void => {
911
+ this.win32SubmitTimer = null;
912
+ this.adapter.send_keys(submitKey);
913
+ if (attempt + 1 >= WIN32_SUBMIT_MAX_RESENDS) return;
914
+ this.win32SubmitTimer = setTimeout(() => {
915
+ // Left the idle composer → it submitted; stop resending.
916
+ if (this.currentStatus() !== 'idle') { this.win32SubmitTimer = null; return; }
917
+ fire(attempt + 1);
918
+ }, WIN32_SUBMIT_RESEND_GAP_MS);
919
+ };
920
+ if (initialDelayMs > 0) this.win32SubmitTimer = setTimeout(() => fire(0), initialDelayMs);
921
+ else fire(0);
922
+ }
923
+
924
+ private handleClickControl(controlId: string, payload?: unknown): void {
925
+ const ctl = (this.spec.control_bar ?? []).find(c => c.id === controlId);
926
+ if (!ctl) return;
927
+ if (ctl.visible_when_state && !ctl.visible_when_state.includes(this.currentStateId)) return;
928
+ const a = ctl.action;
929
+ switch (a.type) {
930
+ case 'send_keys': this.adapter.send_keys(a.keys); return;
931
+ case 'open_picker':
932
+ // Some TUIs (e.g. codex) don't register a slash command if its
933
+ // text and the submitting Enter arrive in the same write — the
934
+ // composer needs a beat to recognise the command before the CR.
935
+ // Split a trailing CR/LF off the trigger and send it after a
936
+ // short delay, mirroring send_message's delay_ms_before_submit.
937
+ {
938
+ const m = /^([\s\S]*?)([\r\n]+)$/.exec(a.trigger_keys);
939
+ if (m && m[1]) {
940
+ this.adapter.send_keys(m[1]);
941
+ setTimeout(() => this.adapter.send_keys(m[2]), 200);
942
+ } else {
943
+ this.adapter.send_keys(a.trigger_keys);
944
+ }
945
+ }
946
+ this.pickerInProgress = { control_id: ctl.id, spec: ctl };
947
+ return;
948
+ case 'attach_image': {
949
+ const p = typeof payload === 'object' && payload && (payload as any).path;
950
+ if (typeof p === 'string') this.adapter.send_keys(a.keys_template.replace(/\{path\}/g, p));
951
+ return;
952
+ }
953
+ }
954
+ }
955
+
956
+ private handleClickModalButton(index: number): void {
957
+ const m = this.currentEval?.modal;
958
+ if (!m) return;
959
+ const btn = m.buttons.find(b => b.index === index);
960
+ if (!btn) return;
961
+ this.adapter.send_keys(btn.key);
962
+ }
963
+
964
+ private handleAttachImage(blob: string, mime: string): void {
965
+ const ctl = (this.spec.control_bar ?? []).find(c => c.action.type === 'attach_image');
966
+ if (!ctl || ctl.action.type !== 'attach_image') return;
967
+ const ext = guessExt(mime);
968
+ const tmp = path.join(os.tmpdir(), `adhdev-attach-${Date.now()}${ext}`);
969
+ try { fs.writeFileSync(tmp, Buffer.from(blob, 'base64')); } catch { return; }
970
+ this.adapter.send_keys(ctl.action.keys_template.replace(/\{path\}/g, tmp));
971
+ }
972
+
973
+ private tryAdvancePicker(screen: string): void {
974
+ const picker = this.pickerInProgress;
975
+ if (!picker) return;
976
+ const action = picker.spec.action;
977
+ if (action.type !== 'open_picker' || !action.wait_for.regex) return;
978
+ const lines = screen.split('\n').map(l => l.endsWith('\r') ? l.slice(0, -1) : l);
979
+ const sections = resolveSections(this.spec.sections ?? {}, lines);
980
+ const hay = sectionText(sections, action.wait_for.section, lines.join('\n'));
981
+ const re = new RegExp(action.wait_for.regex, action.wait_for.flags ?? 'i');
982
+ if (!re.test(hay)) return;
983
+ this.pickerInProgress = null;
984
+ }
985
+
986
+ private handleExit(exitCode: number): void {
987
+ this.emit({ kind: 'exit', exit_code: exitCode });
988
+ this.shutdown();
989
+ }
990
+
991
+ private pushHistory(stateId: string, label: string, meta: { reason: string; via?: string; matchedRules?: string[] }): void {
992
+ const now = Date.now();
993
+ const durationMs = this.prevStateAt > 0 ? now - this.prevStateAt : 0;
994
+ this.prevStateAt = now;
995
+ this.stateHistory.push({
996
+ stateId, label, at: now, durationMs,
997
+ reason: meta.reason,
998
+ ...(meta.via ? { via: meta.via } : {}),
999
+ ...(meta.matchedRules ? { matchedRules: meta.matchedRules } : {}),
1000
+ });
1001
+ if (this.stateHistory.length > 50) this.stateHistory.shift();
1002
+ }
1003
+
1004
+ private specTag(): string {
1005
+ return this.opts.specPath.split('/').slice(-3).join('/');
1006
+ }
1007
+
1008
+ private emit(ev: DashboardEvent): void {
1009
+ for (const l of this.listeners) {
1010
+ try { l(ev); } catch { /* listener side */ }
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ // ── helpers ──────────────────────────────────────────────────────────────
1016
+
1017
+ function sameModal(a: ModalSnapshot | null, b: ModalSnapshot | null): boolean {
1018
+ if (!a && !b) return true;
1019
+ if (!a || !b) return false;
1020
+ if (a.title !== b.title) return false;
1021
+ if (a.buttons.length !== b.buttons.length) return false;
1022
+ for (let i = 0; i < a.buttons.length; i += 1) {
1023
+ if (a.buttons[i].label !== b.buttons[i].label) return false;
1024
+ }
1025
+ return true;
1026
+ }
1027
+
1028
+ function sameControls(a: VisibleControl[], b: VisibleControl[]): boolean {
1029
+ if (a.length !== b.length) return false;
1030
+ for (let i = 0; i < a.length; i += 1) if (a[i].id !== b[i].id) return false;
1031
+ return true;
1032
+ }
1033
+
1034
+ /** A compact one-line-per-condition summary of why a transition fired. */
1035
+ function summarizeTransition(t: TransitionEval): string[] {
1036
+ const out: string[] = [`${t.label} fired`];
1037
+ if (t.cond) flattenCond(t.cond, out, 1);
1038
+ return out;
1039
+ }
1040
+
1041
+ function flattenCond(c: import('./fsm-evaluator.js').CondResult, out: string[], depth: number): void {
1042
+ out.push(`${' '.repeat(depth)}${c.kind} ${c.detail} = ${c.result}${c.remainingMs ? ` (${c.remainingMs}ms left)` : ''}`);
1043
+ for (const child of c.children ?? []) flattenCond(child, out, depth + 1);
1044
+ }
1045
+
1046
+ function findStable(c: import('./fsm-evaluator.js').CondResult): { totalMs: number } | null {
1047
+ if (c.kind === 'stable') {
1048
+ const m = /\/ (\d+)ms/.exec(c.detail);
1049
+ return { totalMs: m ? Number(m[1]) : 0 };
1050
+ }
1051
+ for (const child of c.children ?? []) {
1052
+ const r = findStable(child);
1053
+ if (r) return r;
1054
+ }
1055
+ return null;
1056
+ }
1057
+
1058
+ function collectStableSizes(when: FsmTransition['when'], sizes: Set<number>): void {
1059
+ if (!when) return;
1060
+ const w = when as any;
1061
+ if ('stable_ms' in w) { sizes.add(w.cursor_above && w.cursor_above > 0 ? w.cursor_above : -1); return; }
1062
+ if ('all' in w) { for (const c of w.all) collectStableSizes(c, sizes); return; }
1063
+ if ('any' in w) { for (const c of w.any) collectStableSizes(c, sizes); return; }
1064
+ if ('not' in w) { collectStableSizes(w.not, sizes); return; }
1065
+ }