@adhdev/daemon-core 0.9.82-rc.26 → 0.9.82-rc.261

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 (274) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +4 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/chat/source-machine.d.ts +166 -0
  4. package/dist/chat/source-resolver.d.ts +104 -0
  5. package/dist/chat/subscription-updates.d.ts +1 -0
  6. package/dist/cli-adapter-types.d.ts +23 -2
  7. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  8. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  9. package/dist/cli-adapters/provider-cli-adapter.d.ts +106 -63
  10. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  11. package/dist/cli-adapters/provider-cli-shared.d.ts +38 -0
  12. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  13. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +3 -3
  14. package/dist/cli-adapters/terminal-backends/types.d.ts +1 -2
  15. package/dist/cli-adapters/terminal-screen.d.ts +2 -11
  16. package/dist/commands/cli-manager.d.ts +2 -1
  17. package/dist/commands/handler.d.ts +110 -0
  18. package/dist/commands/mesh-coordinator.d.ts +85 -1
  19. package/dist/commands/router.d.ts +44 -1
  20. package/dist/config/chat-history.d.ts +9 -0
  21. package/dist/config/config.d.ts +5 -0
  22. package/dist/config/mesh-config.d.ts +72 -1
  23. package/dist/git/git-commands.d.ts +9 -1
  24. package/dist/git/git-diff.d.ts +6 -0
  25. package/dist/git/git-types.d.ts +2 -0
  26. package/dist/index.d.ts +47 -11
  27. package/dist/index.js +31114 -11255
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +31615 -11852
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/installer.d.ts +1 -4
  32. package/dist/ipc/local-ipc-server.d.ts +91 -0
  33. package/dist/launch.d.ts +1 -1
  34. package/dist/logging/async-batch-writer.d.ts +10 -0
  35. package/dist/mesh/contracts.d.ts +164 -0
  36. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  37. package/dist/mesh/coordinator-registry.d.ts +59 -0
  38. package/dist/mesh/mesh-active-work.d.ts +90 -0
  39. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  40. package/dist/mesh/mesh-events-coordinator.d.ts +152 -0
  41. package/dist/mesh/mesh-events-pending.d.ts +40 -0
  42. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  43. package/dist/mesh/mesh-events-utils.d.ts +16 -0
  44. package/dist/mesh/mesh-events.d.ts +5 -49
  45. package/dist/mesh/mesh-fast-forward.d.ts +41 -0
  46. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  47. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  48. package/dist/mesh/mesh-ledger.d.ts +77 -1
  49. package/dist/mesh/mesh-missions.d.ts +58 -0
  50. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  51. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  52. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  53. package/dist/mesh/mesh-routing.d.ts +70 -0
  54. package/dist/mesh/mesh-runtime-store.d.ts +327 -0
  55. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  56. package/dist/mesh/mesh-work-queue.d.ts +160 -5
  57. package/dist/mesh/preview-freshness.d.ts +18 -0
  58. package/dist/mesh/refine-config.d.ts +215 -0
  59. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  60. package/dist/providers/acp-provider-instance.d.ts +2 -0
  61. package/dist/providers/approval-utils.d.ts +13 -0
  62. package/dist/providers/cli-provider-instance.d.ts +37 -3
  63. package/dist/providers/contracts.d.ts +130 -6
  64. package/dist/providers/external-sources.d.ts +71 -0
  65. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  66. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  67. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  68. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  69. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  70. package/dist/providers/native-history/index.d.ts +13 -0
  71. package/dist/providers/provider-instance-manager.d.ts +13 -0
  72. package/dist/providers/provider-instance.d.ts +13 -1
  73. package/dist/providers/provider-loader.d.ts +26 -4
  74. package/dist/providers/provider-trust.d.ts +31 -0
  75. package/dist/providers/read-chat-contract.d.ts +29 -0
  76. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  77. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  78. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  79. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  80. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  81. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  82. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  83. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  84. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  85. package/dist/providers/sdk/v1/index.d.ts +30 -0
  86. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  87. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  88. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  89. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  90. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  91. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  92. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  93. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  94. package/dist/providers/spec/adapter.d.ts +52 -0
  95. package/dist/providers/spec/cli-adapter.d.ts +140 -0
  96. package/dist/providers/spec/evaluator.d.ts +23 -0
  97. package/dist/providers/spec/fsm-driver.d.ts +273 -0
  98. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  99. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  100. package/dist/providers/spec/fsm-types.d.ts +91 -0
  101. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  102. package/dist/providers/spec/route.d.ts +4 -0
  103. package/dist/providers/spec/types.d.ts +129 -0
  104. package/dist/providers/transcript-v2.d.ts +176 -0
  105. package/dist/providers/types/interactive-prompt.d.ts +48 -0
  106. package/dist/repo-mesh-types.d.ts +126 -1
  107. package/dist/sessions/registry.d.ts +6 -0
  108. package/dist/shared-types-extra.d.ts +2 -4
  109. package/dist/shared-types.d.ts +42 -1
  110. package/dist/status/normalize.d.ts +1 -1
  111. package/dist/status/normalize.js +1 -0
  112. package/dist/status/normalize.js.map +1 -1
  113. package/dist/status/normalize.mjs +1 -0
  114. package/dist/status/normalize.mjs.map +1 -1
  115. package/dist/status/reporter.d.ts +2 -0
  116. package/dist/status/snapshot.d.ts +1 -0
  117. package/dist/types.d.ts +5 -0
  118. package/package.json +6 -3
  119. package/src/agent-stream/poller.ts +2 -3
  120. package/src/boot/daemon-lifecycle.ts +30 -10
  121. package/src/boot/process-hardening.ts +89 -0
  122. package/src/chat/source-machine.ts +534 -0
  123. package/src/chat/source-resolver.ts +0 -0
  124. package/src/chat/subscription-updates.ts +20 -1
  125. package/src/cli-adapter-types.d.ts +1 -0
  126. package/src/cli-adapter-types.ts +22 -2
  127. package/src/cli-adapters/cli-script-runner.ts +421 -0
  128. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  129. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  130. package/src/cli-adapters/provider-cli-adapter.ts +674 -1139
  131. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  132. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  133. package/src/cli-adapters/provider-cli-runtime.ts +3 -1
  134. package/src/cli-adapters/provider-cli-shared.d.ts +2 -0
  135. package/src/cli-adapters/provider-cli-shared.ts +68 -11
  136. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  137. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +35 -29
  138. package/src/cli-adapters/terminal-backends/types.ts +1 -3
  139. package/src/cli-adapters/terminal-screen.ts +11 -81
  140. package/src/commands/chat-commands.ts +1806 -60
  141. package/src/commands/cli-manager.ts +286 -14
  142. package/src/commands/handler.ts +809 -2
  143. package/src/commands/mesh-coordinator.ts +332 -122
  144. package/src/commands/router.ts +4890 -489
  145. package/src/config/chat-history.ts +95 -24
  146. package/src/config/config.ts +12 -0
  147. package/src/config/mesh-config.ts +303 -3
  148. package/src/config/recent-activity.ts +8 -2
  149. package/src/daemon/dev-auto-implement.ts +3 -2
  150. package/src/daemon/dev-cli-debug.ts +10 -1
  151. package/src/detection/ide-detector.ts +26 -16
  152. package/src/git/git-commands.ts +42 -12
  153. package/src/git/git-diff.ts +53 -0
  154. package/src/git/git-status.ts +35 -6
  155. package/src/git/git-types.ts +2 -0
  156. package/src/git/git-worktree.ts +8 -1
  157. package/src/index.ts +127 -10
  158. package/src/installer.d.ts +1 -1
  159. package/src/installer.ts +8 -6
  160. package/src/ipc/local-ipc-server.ts +278 -0
  161. package/src/launch.d.ts +1 -1
  162. package/src/launch.ts +37 -28
  163. package/src/logging/async-batch-writer.ts +55 -0
  164. package/src/logging/logger.ts +2 -1
  165. package/src/mesh/contracts.ts +329 -0
  166. package/src/mesh/coordinator-prompt.ts +219 -31
  167. package/src/mesh/coordinator-registry.ts +121 -0
  168. package/src/mesh/mesh-active-work.ts +437 -0
  169. package/src/mesh/mesh-delivery-policy.ts +315 -0
  170. package/src/mesh/mesh-events-coordinator.ts +1625 -0
  171. package/src/mesh/mesh-events-pending.ts +439 -0
  172. package/src/mesh/mesh-events-stale.ts +283 -0
  173. package/src/mesh/mesh-events-utils.ts +195 -0
  174. package/src/mesh/mesh-events.ts +26 -1035
  175. package/src/mesh/mesh-fast-forward.ts +438 -0
  176. package/src/mesh/mesh-host-ownership.ts +73 -0
  177. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  178. package/src/mesh/mesh-ledger.ts +588 -102
  179. package/src/mesh/mesh-missions.ts +151 -0
  180. package/src/mesh/mesh-refine-batch.ts +197 -0
  181. package/src/mesh/mesh-refine-status.ts +231 -0
  182. package/src/mesh/mesh-review-inbox.ts +307 -0
  183. package/src/mesh/mesh-routing.ts +272 -0
  184. package/src/mesh/mesh-runtime-store.ts +1342 -0
  185. package/src/mesh/mesh-task-stats.ts +154 -0
  186. package/src/mesh/mesh-work-queue.ts +573 -145
  187. package/src/mesh/preview-freshness.ts +118 -0
  188. package/src/mesh/refine-config.ts +403 -0
  189. package/src/mesh/worktree-bootstrap-config.ts +326 -0
  190. package/src/providers/acp-provider-instance.ts +15 -1
  191. package/src/providers/approval-utils.d.ts +4 -0
  192. package/src/providers/approval-utils.ts +47 -5
  193. package/src/providers/chat-message-normalization.ts +4 -11
  194. package/src/providers/cli-provider-instance.ts +806 -72
  195. package/src/providers/contracts.d.ts +55 -0
  196. package/src/providers/contracts.ts +141 -6
  197. package/src/providers/external-sources.ts +218 -0
  198. package/src/providers/ide-provider-instance.ts +19 -5
  199. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  200. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  201. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  202. package/src/providers/native-history/dispatcher.ts +340 -0
  203. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  204. package/src/providers/native-history/index.ts +30 -0
  205. package/src/providers/provider-instance-manager.ts +30 -0
  206. package/src/providers/provider-instance.ts +10 -1
  207. package/src/providers/provider-loader.ts +584 -50
  208. package/src/providers/provider-schema.ts +87 -14
  209. package/src/providers/provider-trust.ts +114 -0
  210. package/src/providers/read-chat-contract.ts +76 -16
  211. package/src/providers/sdk/README.md +49 -0
  212. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  213. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  214. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  215. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  216. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  217. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  218. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  219. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  220. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  221. package/src/providers/sdk/v1/index.ts +152 -0
  222. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  223. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  224. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  225. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  226. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  227. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  228. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  229. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  230. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  231. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  232. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  233. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  234. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  235. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  236. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  237. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  238. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  239. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  240. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  241. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  242. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  243. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  244. package/src/providers/sdk/v1/validators/index.ts +19 -0
  245. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  246. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  247. package/src/providers/spec/adapter.ts +145 -0
  248. package/src/providers/spec/cli-adapter.ts +730 -0
  249. package/src/providers/spec/evaluator.ts +321 -0
  250. package/src/providers/spec/fsm-driver.ts +811 -0
  251. package/src/providers/spec/fsm-evaluator.ts +255 -0
  252. package/src/providers/spec/fsm-loader.ts +102 -0
  253. package/src/providers/spec/fsm-types.ts +184 -0
  254. package/src/providers/spec/native-history-executor.ts +943 -0
  255. package/src/providers/spec/route.ts +51 -0
  256. package/src/providers/spec/types.ts +173 -0
  257. package/src/providers/transcript-v2.ts +567 -0
  258. package/src/providers/types/interactive-prompt.ts +425 -0
  259. package/src/providers/version-archive.ts +38 -20
  260. package/src/repo-mesh-types.ts +138 -1
  261. package/src/sessions/registry.ts +6 -0
  262. package/src/shared-types-extra.ts +2 -4
  263. package/src/shared-types.ts +45 -1
  264. package/src/status/builders.ts +26 -6
  265. package/src/status/normalize.ts +2 -0
  266. package/src/status/reporter.ts +15 -0
  267. package/src/status/snapshot.ts +84 -25
  268. package/src/system/host-memory.ts +29 -12
  269. package/src/types.ts +5 -0
  270. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  271. package/dist/mesh/mesh-sync.d.ts +0 -53
  272. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  273. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  274. 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,102 @@
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 (!Array.isArray(spec.states) || spec.states.length === 0) {
40
+ errs.push('states[] must be a non-empty array');
41
+ return errs;
42
+ }
43
+ if (!Array.isArray(spec.transitions)) {
44
+ errs.push('transitions[] must be an array');
45
+ return errs;
46
+ }
47
+
48
+ const ids = new Set<string>();
49
+ let initialCount = 0;
50
+ for (const [i, s] of spec.states.entries()) {
51
+ if (!s.id) { errs.push(`states[${i}].id is required`); continue; }
52
+ if (ids.has(s.id)) errs.push(`states[${i}].id "${s.id}" is duplicated`);
53
+ ids.add(s.id);
54
+ if (!s.label) errs.push(`states[${i}].label is required`);
55
+ if (s.initial) initialCount += 1;
56
+ if (s.status && !['idle', 'generating', 'approval'].includes(s.status)) {
57
+ errs.push(`states[${i}].status "${s.status}" must be idle|generating|approval`);
58
+ }
59
+ }
60
+ if (initialCount === 0) errs.push('exactly one state must have initial:true (none found)');
61
+ if (initialCount > 1) errs.push(`exactly one state must have initial:true (${initialCount} found)`);
62
+
63
+ const sectionIds = new Set(Object.keys(spec.sections ?? {}));
64
+ for (const [i, t] of spec.transitions.entries()) {
65
+ const froms = t.from === '*' ? [] : (Array.isArray(t.from) ? t.from : [t.from]);
66
+ for (const f of froms) {
67
+ if (!ids.has(f)) errs.push(`transitions[${i}].from references unknown state "${f}"`);
68
+ }
69
+ if (t.from !== '*' && froms.length === 0) errs.push(`transitions[${i}].from is required`);
70
+ if (!t.to) errs.push(`transitions[${i}].to is required`);
71
+ else if (!ids.has(t.to)) errs.push(`transitions[${i}].to references unknown state "${t.to}"`);
72
+ if (t.when) errs.push(...validateCondition(t.when, sectionIds, `transitions[${i}].when`));
73
+ }
74
+
75
+ // Section refs in state.extract
76
+ for (const [i, s] of spec.states.entries()) {
77
+ const sec = s.extract?.title?.section;
78
+ if (sec && !sectionIds.has(sec)) errs.push(`states[${i}].extract.title.section "${sec}" unknown`);
79
+ const bsec = s.extract?.buttons?.section;
80
+ if (bsec && !sectionIds.has(bsec)) errs.push(`states[${i}].extract.buttons.section "${bsec}" unknown`);
81
+ }
82
+
83
+ return errs;
84
+ }
85
+
86
+ function validateCondition(c: FsmCondition, sectionIds: Set<string>, path: string): string[] {
87
+ const errs: string[] = [];
88
+ const w = c as any;
89
+ if ('all' in w) { w.all.forEach((x: FsmCondition, i: number) => errs.push(...validateCondition(x, sectionIds, `${path}.all[${i}]`))); return errs; }
90
+ if ('any' in w) { w.any.forEach((x: FsmCondition, i: number) => errs.push(...validateCondition(x, sectionIds, `${path}.any[${i}]`))); return errs; }
91
+ if ('not' in w) { errs.push(...validateCondition(w.not, sectionIds, `${path}.not`)); return errs; }
92
+ if ('matches' in w) {
93
+ if (w.section && !sectionIds.has(w.section)) errs.push(`${path}.section "${w.section}" unknown`);
94
+ try { new RegExp(w.matches, w.flags ?? 'i'); } catch (e) { errs.push(`${path}.matches invalid regex: ${(e as Error).message}`); }
95
+ return errs;
96
+ }
97
+ if ('cursor_above' in w && 'changed' in w) return errs;
98
+ if ('elapsed_ms' in w) { if (typeof w.elapsed_ms !== 'number') errs.push(`${path}.elapsed_ms must be a number`); return errs; }
99
+ if ('stable_ms' in w) { if (typeof w.stable_ms !== 'number') errs.push(`${path}.stable_ms must be a number`); return errs; }
100
+ errs.push(`${path} is not a recognized condition`);
101
+ return errs;
102
+ }
@@ -0,0 +1,184 @@
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
+ // CliSpecV4 — the v4 runtime spec
123
+ // ─────────────────────────────────────────────────────────────────────────────
124
+
125
+ export interface CliSpecV4 {
126
+ $schema: 'adhdev:cli/spec@4';
127
+ id: string;
128
+ name: string;
129
+ binary: string;
130
+ spawn_args?: string[];
131
+ env?: Record<string, string>;
132
+ cli_version_range?: string;
133
+ send_message: {
134
+ submit_key: string;
135
+ delay_ms_before_submit?: number;
136
+ delay_ms_per_char?: number;
137
+ };
138
+ sections: Record<string, SectionDef>;
139
+ states: FsmState[];
140
+ transitions: FsmTransition[];
141
+ control_bar?: Control[];
142
+ notifications?: NotificationRule[];
143
+ delegate?: DelegateTrigger[];
144
+ native_history?: NativeHistoryConfig;
145
+ requiresFinalAssistantBeforeIdle?: boolean;
146
+ }
147
+
148
+ export function isV4Spec(raw: unknown): raw is CliSpecV4 {
149
+ return !!raw && typeof raw === 'object'
150
+ && (raw as { $schema?: string }).$schema === 'adhdev:cli/spec@4';
151
+ }
152
+
153
+ export function initialState(spec: CliSpecV4): FsmState {
154
+ return spec.states.find(s => s.initial) ?? spec.states[0];
155
+ }
156
+
157
+ export function stateById(spec: CliSpecV4, id: string): FsmState | undefined {
158
+ return spec.states.find(s => s.id === id);
159
+ }
160
+
161
+ /** Outgoing transitions from `stateId`, highest priority first, declaration
162
+ * order as tiebreak. Includes wildcard ("*") and list-membership sources. */
163
+ export function outgoingTransitions(spec: CliSpecV4, stateId: string): FsmTransition[] {
164
+ const matches = spec.transitions.filter(t => {
165
+ if (t.from === '*') return true;
166
+ if (Array.isArray(t.from)) return t.from.includes(stateId);
167
+ return t.from === stateId;
168
+ });
169
+ // Stable sort by priority desc; Array.prototype.sort is stable in V8 so
170
+ // equal-priority edges keep declaration order.
171
+ return matches
172
+ .map((t, i) => ({ t, i }))
173
+ .sort((a, b) => (b.t.priority ?? 0) - (a.t.priority ?? 0) || a.i - b.i)
174
+ .map(x => x.t);
175
+ }
176
+
177
+ /** Map a state to the dashboard status string, applying the documented
178
+ * defaults when `status` is not explicit. */
179
+ export function statusForState(state: FsmState): 'idle' | 'generating' | 'approval' {
180
+ if (state.status) return state.status;
181
+ if (state.modal) return 'approval';
182
+ if (state.id === 'busy' || state.id === 'generating') return 'generating';
183
+ return 'idle';
184
+ }