@adhdev/daemon-core 0.9.82-rc.44 → 0.9.82-rc.440

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 (425) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -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 +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +7 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +15 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +60 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +29 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +142 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +276 -2
  56. package/dist/commands/upgrade-helper.d.ts +41 -1
  57. package/dist/config/chat-history.d.ts +9 -0
  58. package/dist/config/config.d.ts +5 -0
  59. package/dist/config/mesh-config.d.ts +120 -1
  60. package/dist/config/mesh-json-config.d.ts +199 -0
  61. package/dist/config/repo-settings.d.ts +77 -0
  62. package/dist/daemon/dev-server.d.ts +0 -2
  63. package/dist/detection/ide-detector.d.ts +13 -0
  64. package/dist/detection/win32-ide-version.d.ts +37 -0
  65. package/dist/git/change-impact-config.d.ts +159 -0
  66. package/dist/git/git-commands.d.ts +11 -1
  67. package/dist/git/git-diff.d.ts +6 -0
  68. package/dist/git/git-executor.d.ts +11 -0
  69. package/dist/git/git-status.d.ts +57 -0
  70. package/dist/git/git-types.d.ts +2 -50
  71. package/dist/git/git-worktree.d.ts +71 -1
  72. package/dist/git/index.d.ts +3 -1
  73. package/dist/index.d.ts +64 -14
  74. package/dist/index.js +50679 -20122
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +47546 -17153
  77. package/dist/index.mjs.map +1 -1
  78. package/dist/installer.d.ts +1 -4
  79. package/dist/ipc/local-ipc-server.d.ts +91 -0
  80. package/dist/launch.d.ts +1 -1
  81. package/dist/logging/async-batch-writer.d.ts +10 -0
  82. package/dist/logging/log-redactor.d.ts +24 -0
  83. package/dist/logging/log-tail-reader.d.ts +81 -0
  84. package/dist/logging/logger.d.ts +1 -1
  85. package/dist/mesh/contracts.d.ts +164 -0
  86. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  87. package/dist/mesh/coordinator-registry.d.ts +59 -0
  88. package/dist/mesh/mesh-active-work.d.ts +174 -0
  89. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  90. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  91. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  92. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  93. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  94. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  95. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  96. package/dist/mesh/mesh-events-pending.d.ts +69 -0
  97. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  98. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  99. package/dist/mesh/mesh-events.d.ts +6 -49
  100. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  101. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  102. package/dist/mesh/mesh-init.d.ts +128 -0
  103. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  104. package/dist/mesh/mesh-ledger.d.ts +77 -1
  105. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  106. package/dist/mesh/mesh-missions.d.ts +189 -0
  107. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  108. package/dist/mesh/mesh-queue-assignment.d.ts +113 -0
  109. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  110. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  111. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  112. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  113. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  114. package/dist/mesh/mesh-routing.d.ts +70 -0
  115. package/dist/mesh/mesh-runtime-store.d.ts +450 -0
  116. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  117. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  118. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  119. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  120. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  121. package/dist/mesh/mesh-work-queue.d.ts +300 -5
  122. package/dist/mesh/preview-freshness.d.ts +18 -0
  123. package/dist/mesh/refine-config.d.ts +216 -0
  124. package/dist/mesh/worktree-bootstrap-config.d.ts +145 -0
  125. package/dist/providers/acp-provider-instance.d.ts +5 -0
  126. package/dist/providers/approval-utils.d.ts +20 -0
  127. package/dist/providers/chat-message-normalization.d.ts +31 -1
  128. package/dist/providers/cli-provider-instance.d.ts +252 -3
  129. package/dist/providers/contracts.d.ts +149 -6
  130. package/dist/providers/external-sources.d.ts +71 -0
  131. package/dist/providers/manual-attendance.d.ts +63 -0
  132. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  133. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  134. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  135. package/dist/providers/native-history/constants.d.ts +12 -0
  136. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  137. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  138. package/dist/providers/native-history/index.d.ts +13 -0
  139. package/dist/providers/provider-instance-manager.d.ts +29 -0
  140. package/dist/providers/provider-instance.d.ts +23 -1
  141. package/dist/providers/provider-loader.d.ts +26 -4
  142. package/dist/providers/provider-trust.d.ts +31 -0
  143. package/dist/providers/read-chat-contract.d.ts +29 -0
  144. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  145. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  146. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  147. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  148. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  149. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  150. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  151. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  152. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  153. package/dist/providers/sdk/v1/index.d.ts +30 -0
  154. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  155. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  156. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  157. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  158. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  159. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  160. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  161. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  162. package/dist/providers/spec/adapter.d.ts +91 -0
  163. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  164. package/dist/providers/spec/evaluator.d.ts +45 -0
  165. package/dist/providers/spec/fsm-driver.d.ts +422 -0
  166. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  167. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  168. package/dist/providers/spec/fsm-types.d.ts +174 -0
  169. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  170. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  171. package/dist/providers/spec/route.d.ts +4 -0
  172. package/dist/providers/spec/types.d.ts +222 -0
  173. package/dist/providers/status-monitor.d.ts +7 -7
  174. package/dist/providers/transcript-v2.d.ts +176 -0
  175. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  176. package/dist/providers/working-dir.d.ts +17 -0
  177. package/dist/repo-mesh-types.d.ts +509 -13
  178. package/dist/runtime-defaults.d.ts +2 -0
  179. package/dist/sessions/registry.d.ts +6 -0
  180. package/dist/shared-types-extra.d.ts +2 -4
  181. package/dist/shared-types.d.ts +59 -2
  182. package/dist/status/normalize.d.ts +1 -1
  183. package/dist/status/normalize.js +1 -0
  184. package/dist/status/normalize.js.map +1 -1
  185. package/dist/status/normalize.mjs +1 -0
  186. package/dist/status/normalize.mjs.map +1 -1
  187. package/dist/status/reporter.d.ts +2 -0
  188. package/dist/status/snapshot.d.ts +26 -0
  189. package/dist/system/hash.d.ts +8 -0
  190. package/dist/system/load-better-sqlite3.d.ts +21 -0
  191. package/dist/types.d.ts +5 -0
  192. package/package.json +7 -3
  193. package/src/agent-stream/poller.ts +2 -3
  194. package/src/agent-stream/provider-adapter.ts +1 -1
  195. package/src/boot/daemon-lifecycle.ts +63 -12
  196. package/src/boot/process-hardening.ts +89 -0
  197. package/src/build-info.ts +73 -0
  198. package/src/chat/source-machine.ts +534 -0
  199. package/src/chat/source-resolver.ts +0 -0
  200. package/src/chat/subscription-updates.ts +20 -1
  201. package/src/cli-adapter-types.d.ts +3 -1
  202. package/src/cli-adapter-types.ts +68 -2
  203. package/src/cli-adapters/cli-script-runner.ts +421 -0
  204. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  205. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  206. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  207. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  208. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  209. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  210. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  211. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  212. package/src/cli-adapters/pty-transport.ts +2 -1
  213. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  214. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  215. package/src/cli-adapters/resolve-executable.ts +204 -0
  216. package/src/cli-adapters/session-host-transport.ts +2 -1
  217. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  218. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  219. package/src/cli-adapters/terminal-screen.ts +16 -81
  220. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  221. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  222. package/src/commands/chat-commands-read.ts +2327 -0
  223. package/src/commands/chat-commands-scope.ts +54 -0
  224. package/src/commands/chat-commands-shared.ts +114 -0
  225. package/src/commands/chat-commands-write.ts +891 -0
  226. package/src/commands/chat-commands.ts +19 -1841
  227. package/src/commands/cli-manager.ts +572 -27
  228. package/src/commands/handler.ts +841 -2
  229. package/src/commands/high-family/index.ts +28 -0
  230. package/src/commands/high-family/mesh-coordinator-launch.ts +678 -0
  231. package/src/commands/high-family/mesh-events.ts +80 -0
  232. package/src/commands/high-family/mesh-status.ts +714 -0
  233. package/src/commands/high-family/types.ts +76 -0
  234. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  235. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  236. package/src/commands/low-family/diagnostics.ts +57 -0
  237. package/src/commands/low-family/index.ts +37 -0
  238. package/src/commands/low-family/mesh-ledger.ts +62 -0
  239. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  240. package/src/commands/low-family/notification.ts +116 -0
  241. package/src/commands/low-family/refine-config.ts +106 -0
  242. package/src/commands/low-family/session-host.ts +274 -0
  243. package/src/commands/low-family/spec-providerdev.ts +217 -0
  244. package/src/commands/low-family/status-meta.ts +112 -0
  245. package/src/commands/low-family/types.ts +39 -0
  246. package/src/commands/med-family/cli-agent.ts +238 -0
  247. package/src/commands/med-family/fast-forward.ts +230 -0
  248. package/src/commands/med-family/ide.ts +163 -0
  249. package/src/commands/med-family/index.ts +37 -0
  250. package/src/commands/med-family/mesh-crud.ts +1242 -0
  251. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  252. package/src/commands/med-family/mesh-queue.ts +167 -0
  253. package/src/commands/med-family/mesh-restart.ts +92 -0
  254. package/src/commands/med-family/types.ts +143 -0
  255. package/src/commands/mesh-coordinator.ts +334 -124
  256. package/src/commands/router.ts +2846 -3484
  257. package/src/commands/stream-commands.ts +8 -0
  258. package/src/commands/upgrade-helper.ts +310 -45
  259. package/src/config/chat-history.ts +493 -24
  260. package/src/config/config.ts +12 -0
  261. package/src/config/mesh-config.ts +593 -22
  262. package/src/config/mesh-json-config.ts +376 -0
  263. package/src/config/recent-activity.ts +8 -2
  264. package/src/config/repo-settings.ts +111 -0
  265. package/src/daemon/dev-auto-implement.ts +3 -2
  266. package/src/daemon/dev-cli-debug.ts +10 -1
  267. package/src/daemon/dev-server.ts +0 -541
  268. package/src/detection/cli-detector.ts +28 -9
  269. package/src/detection/ide-detector.ts +55 -16
  270. package/src/detection/win32-ide-version.ts +106 -0
  271. package/src/git/change-impact-config.ts +354 -0
  272. package/src/git/git-commands.ts +59 -15
  273. package/src/git/git-diff.ts +81 -11
  274. package/src/git/git-executor.ts +12 -0
  275. package/src/git/git-status.ts +767 -48
  276. package/src/git/git-types.ts +14 -62
  277. package/src/git/git-worktree.ts +261 -4
  278. package/src/git/index.ts +17 -0
  279. package/src/index.ts +196 -12
  280. package/src/installer.d.ts +1 -1
  281. package/src/installer.ts +8 -6
  282. package/src/ipc/local-ipc-server.ts +278 -0
  283. package/src/launch.d.ts +1 -1
  284. package/src/launch.ts +37 -28
  285. package/src/logging/async-batch-writer.ts +55 -0
  286. package/src/logging/command-log.ts +7 -5
  287. package/src/logging/log-redactor.ts +100 -0
  288. package/src/logging/log-tail-reader.ts +341 -0
  289. package/src/logging/logger.ts +14 -7
  290. package/src/mesh/contracts.ts +338 -0
  291. package/src/mesh/coordinator-prompt.ts +415 -34
  292. package/src/mesh/coordinator-registry.ts +121 -0
  293. package/src/mesh/mesh-active-work.ts +645 -0
  294. package/src/mesh/mesh-clone-grace.ts +68 -0
  295. package/src/mesh/mesh-coordinator-config.ts +97 -0
  296. package/src/mesh/mesh-delivery-policy.ts +315 -0
  297. package/src/mesh/mesh-event-classify.ts +51 -0
  298. package/src/mesh/mesh-event-forwarding.ts +1897 -0
  299. package/src/mesh/mesh-event-trace.ts +67 -0
  300. package/src/mesh/mesh-events-coordinator.ts +32 -0
  301. package/src/mesh/mesh-events-pending.ts +656 -0
  302. package/src/mesh/mesh-events-stale.ts +389 -0
  303. package/src/mesh/mesh-events-utils.ts +443 -0
  304. package/src/mesh/mesh-events.ts +33 -1035
  305. package/src/mesh/mesh-fast-forward.ts +843 -0
  306. package/src/mesh/mesh-host-ownership.ts +111 -0
  307. package/src/mesh/mesh-init.ts +350 -0
  308. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  309. package/src/mesh/mesh-ledger.ts +656 -102
  310. package/src/mesh/mesh-magi-status.ts +223 -0
  311. package/src/mesh/mesh-missions.ts +449 -0
  312. package/src/mesh/mesh-node-identity.ts +1887 -0
  313. package/src/mesh/mesh-queue-assignment.ts +1924 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1997 -0
  315. package/src/mesh/mesh-refine-batch.ts +205 -0
  316. package/src/mesh/mesh-refine-gates.ts +1673 -0
  317. package/src/mesh/mesh-refine-status.ts +231 -0
  318. package/src/mesh/mesh-review-inbox.ts +307 -0
  319. package/src/mesh/mesh-routing.ts +291 -0
  320. package/src/mesh/mesh-runtime-store.ts +1853 -0
  321. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  322. package/src/mesh/mesh-task-inflight.ts +70 -0
  323. package/src/mesh/mesh-task-stats.ts +161 -0
  324. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  325. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  326. package/src/mesh/mesh-work-queue.ts +1254 -141
  327. package/src/mesh/preview-freshness.ts +118 -0
  328. package/src/mesh/refine-config.ts +423 -0
  329. package/src/mesh/worktree-bootstrap-config.ts +450 -0
  330. package/src/providers/acp-provider-instance.ts +43 -10
  331. package/src/providers/approval-utils.d.ts +5 -0
  332. package/src/providers/approval-utils.ts +57 -5
  333. package/src/providers/chat-message-normalization.ts +92 -4
  334. package/src/providers/cli-provider-instance.ts +2001 -106
  335. package/src/providers/contracts.d.ts +55 -0
  336. package/src/providers/contracts.ts +160 -6
  337. package/src/providers/extension-provider-instance.ts +12 -7
  338. package/src/providers/external-sources.ts +218 -0
  339. package/src/providers/ide-provider-instance.ts +35 -12
  340. package/src/providers/manual-attendance.ts +85 -0
  341. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  342. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  343. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  344. package/src/providers/native-history/constants.ts +19 -0
  345. package/src/providers/native-history/dispatcher.ts +345 -0
  346. package/src/providers/native-history/hermes-cli-transcript.ts +260 -0
  347. package/src/providers/native-history/index.ts +30 -0
  348. package/src/providers/provider-instance-manager.ts +71 -0
  349. package/src/providers/provider-instance.ts +19 -1
  350. package/src/providers/provider-loader.ts +668 -50
  351. package/src/providers/provider-schema.ts +87 -14
  352. package/src/providers/provider-trust.ts +114 -0
  353. package/src/providers/read-chat-contract.ts +76 -16
  354. package/src/providers/sdk/README.md +49 -0
  355. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  356. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  357. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  358. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  359. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  360. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  361. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  362. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  363. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  364. package/src/providers/sdk/v1/index.ts +152 -0
  365. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  366. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  367. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  368. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  369. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  370. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  375. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  376. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  377. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  378. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  379. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  380. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  381. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  382. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  383. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  384. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  385. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  386. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  387. package/src/providers/sdk/v1/validators/index.ts +19 -0
  388. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  389. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  390. package/src/providers/spec/adapter.ts +235 -0
  391. package/src/providers/spec/cli-adapter.ts +1056 -0
  392. package/src/providers/spec/evaluator.ts +407 -0
  393. package/src/providers/spec/fsm-driver.ts +1410 -0
  394. package/src/providers/spec/fsm-evaluator.ts +272 -0
  395. package/src/providers/spec/fsm-loader.ts +120 -0
  396. package/src/providers/spec/fsm-types.ts +273 -0
  397. package/src/providers/spec/native-history-executor.ts +1143 -0
  398. package/src/providers/spec/pre-launch-trust.ts +104 -0
  399. package/src/providers/spec/route.ts +51 -0
  400. package/src/providers/spec/types.ts +262 -0
  401. package/src/providers/status-monitor.d.ts +7 -7
  402. package/src/providers/status-monitor.ts +37 -22
  403. package/src/providers/transcript-v2.ts +567 -0
  404. package/src/providers/types/interactive-prompt.ts +536 -0
  405. package/src/providers/version-archive.ts +64 -24
  406. package/src/providers/working-dir.ts +23 -0
  407. package/src/repo-mesh-types.ts +748 -14
  408. package/src/runtime-defaults.ts +39 -0
  409. package/src/sessions/registry.ts +6 -0
  410. package/src/shared-types-extra.ts +2 -4
  411. package/src/shared-types.d.ts +8 -0
  412. package/src/shared-types.ts +64 -1
  413. package/src/status/builders.ts +26 -6
  414. package/src/status/normalize.ts +2 -0
  415. package/src/status/reporter.ts +19 -1
  416. package/src/status/snapshot.ts +95 -26
  417. package/src/system/hash.ts +23 -0
  418. package/src/system/host-memory.ts +29 -12
  419. package/src/system/load-better-sqlite3.ts +68 -0
  420. package/src/types.ts +5 -0
  421. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  422. package/dist/mesh/mesh-sync.d.ts +0 -53
  423. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  424. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  425. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1853 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync } from 'fs';
2
+ import { dirname, join } from 'path';
3
+ import { LOG } from '../logging/logger.js';
4
+ import { loadBetterSqlite3 } from '../system/load-better-sqlite3.js';
5
+ import { getLedgerDir } from './mesh-ledger.js';
6
+ import { nodeSatisfiesRequiredTags, isTaskReadonly } from './mesh-work-queue.js';
7
+ import { meshNodeIdMatches, daemonIdsEquivalent, expandDaemonIdForms } from '@adhdev/mesh-shared';
8
+ import type { MeshTaskStatus, MeshWorkQueueEntry } from './mesh-work-queue.js';
9
+ import type BetterSqlite3 from 'better-sqlite3';
10
+ import type { Database as DatabaseHandle } from 'better-sqlite3';
11
+
12
+ let DatabaseCtor: typeof BetterSqlite3 | undefined;
13
+
14
+ function loadDatabaseCtor(): typeof BetterSqlite3 {
15
+ if (DatabaseCtor) return DatabaseCtor;
16
+ DatabaseCtor = loadBetterSqlite3() as typeof BetterSqlite3;
17
+ return DatabaseCtor;
18
+ }
19
+
20
+ function safeMeshId(meshId: string): string {
21
+ return meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
22
+ }
23
+
24
+ function legacyQueuePath(meshId: string): string {
25
+ return join(getLedgerDir(), `${safeMeshId(meshId)}.queue.json`);
26
+ }
27
+
28
+ let loggedMigrationFailure = false;
29
+
30
+ function meshRuntimeStorePath(): string {
31
+ const dir = getLedgerDir();
32
+ const nextPath = join(dir, 'mesh-runtime.db');
33
+ if (existsSync(nextPath)) return nextPath;
34
+
35
+ const legacyPath = join(dir, 'beads.db');
36
+ if (!existsSync(legacyPath)) return nextPath;
37
+
38
+ try {
39
+ renameSync(legacyPath, nextPath);
40
+ for (const suffix of ['-wal', '-shm']) {
41
+ const legacyCompanion = `${legacyPath}${suffix}`;
42
+ if (existsSync(legacyCompanion)) {
43
+ renameSync(legacyCompanion, `${nextPath}${suffix}`);
44
+ }
45
+ }
46
+ } catch (err: any) {
47
+ // Migration failed — most commonly win32 EPERM when a handle to the
48
+ // legacy DB is still open. Do NOT fall through to opening `nextPath`:
49
+ // that would create a fresh EMPTY store while the existing data stays
50
+ // stranded in the legacy file (split-brain / silent data loss). Instead
51
+ // keep using whichever file actually holds the data in-place — the next
52
+ // boot retries the rename. If the main rename already landed (only a
53
+ // companion file failed), the data is at nextPath; otherwise it is still
54
+ // at legacyPath.
55
+ if (!loggedMigrationFailure) {
56
+ loggedMigrationFailure = true;
57
+ LOG.warn(
58
+ 'MeshRuntimeStore',
59
+ `Legacy beads.db→mesh-runtime.db migration failed; using existing DB in-place to avoid data loss: ${err?.message || err}`,
60
+ );
61
+ }
62
+ return existsSync(nextPath) ? nextPath : legacyPath;
63
+ }
64
+ return nextPath;
65
+ }
66
+
67
+ export class MeshRuntimeStore {
68
+ private static instance: MeshRuntimeStore | undefined;
69
+ private readonly db: DatabaseHandle;
70
+ private readonly dbPath: string;
71
+ private readonly migratedMeshIds = new Set<string>();
72
+ private fingerprintSweepCounter = 0;
73
+ private walWriteCounter = 0;
74
+ // Independent cadence for the tool-call-log sweep. Must NOT share walWriteCounter:
75
+ // sharing makes each store's threshold drift by the other's write volume (WAL
76
+ // checkpoint at 500 vs tool-log sweep at 200 would interfere arbitrarily).
77
+ private toolCallLogCounter = 0;
78
+ private static readonly WAL_CHECK_INTERVAL = 500;
79
+ private static readonly WAL_MAX_BYTES = 50 * 1024 * 1024; // 50 MB
80
+
81
+ private constructor(dbPath: string) {
82
+ const dir = dirname(dbPath);
83
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
84
+
85
+ this.dbPath = dbPath;
86
+ this.db = new (loadDatabaseCtor())(dbPath);
87
+ this.db.pragma('journal_mode = WAL');
88
+ this.db.pragma('synchronous = NORMAL');
89
+ this.db.pragma('foreign_keys = ON');
90
+ this.db.pragma('busy_timeout = 5000');
91
+ this.migrate();
92
+ }
93
+
94
+ private static loggedGetInstanceFailure = false;
95
+
96
+ static getInstance(): MeshRuntimeStore {
97
+ if (!this.instance) {
98
+ try {
99
+ this.instance = new MeshRuntimeStore(meshRuntimeStorePath());
100
+ } catch (err: any) {
101
+ // SQLite store could not be opened (e.g. better-sqlite3 native
102
+ // load failure, locked/corrupt DB). Callers wrap getInstance in
103
+ // try/catch and silently degrade to JSONL-only — surface ONE warn
104
+ // so that degraded mode is diagnosable, then re-throw unchanged.
105
+ if (!MeshRuntimeStore.loggedGetInstanceFailure) {
106
+ MeshRuntimeStore.loggedGetInstanceFailure = true;
107
+ LOG.warn(
108
+ 'MeshRuntimeStore',
109
+ `getInstance failed; callers will degrade to JSONL-only: ${err?.message || err}`,
110
+ );
111
+ }
112
+ throw err;
113
+ }
114
+ }
115
+ return this.instance;
116
+ }
117
+
118
+ static resetForTests(): void {
119
+ this.instance?.close();
120
+ this.instance = undefined;
121
+ }
122
+
123
+ close(): void {
124
+ this.db.close();
125
+ }
126
+
127
+ transaction<T>(fn: () => T): T {
128
+ return this.db.transaction(fn).immediate();
129
+ }
130
+
131
+ private migrate(): void {
132
+ this.db.exec(`
133
+ CREATE TABLE IF NOT EXISTS mesh_queue (
134
+ id TEXT PRIMARY KEY,
135
+ mesh_id TEXT NOT NULL,
136
+ status TEXT NOT NULL,
137
+ target_node_id TEXT,
138
+ target_session_id TEXT,
139
+ assigned_node_id TEXT,
140
+ assigned_session_id TEXT,
141
+ created_at TEXT NOT NULL,
142
+ updated_at TEXT NOT NULL,
143
+ payload TEXT NOT NULL
144
+ );
145
+
146
+ CREATE INDEX IF NOT EXISTS idx_mesh_queue_mesh_status_created
147
+ ON mesh_queue(mesh_id, status, created_at);
148
+ CREATE INDEX IF NOT EXISTS idx_mesh_queue_assignment
149
+ ON mesh_queue(mesh_id, assigned_node_id, assigned_session_id, status);
150
+
151
+ -- mesh_id is DB-level isolation (defense-in-depth). The fingerprint STRING
152
+ -- also carries meshId as its first '::'-joined segment (see
153
+ -- buildMeshCompletionFingerprint) — that string-prefix defense is kept; this
154
+ -- column makes cross-mesh suppression impossible even if the string format
155
+ -- drifts or two meshes ever collide on a fingerprint body.
156
+ CREATE TABLE IF NOT EXISTS mesh_completion_fingerprints (
157
+ fingerprint TEXT PRIMARY KEY,
158
+ expires_at INTEGER NOT NULL,
159
+ mesh_id TEXT NOT NULL DEFAULT ''
160
+ );
161
+ -- NOTE: the (mesh_id, fingerprint) index is created in migrateMeshIsolationColumns,
162
+ -- NOT here. A pre-isolation DB still has the legacy table (CREATE IF NOT EXISTS is a
163
+ -- no-op), so referencing mesh_id in an index before the ALTER ADD COLUMN runs would
164
+ -- fail with "no such column". The migration adds the column then the index.
165
+
166
+ CREATE TABLE IF NOT EXISTS mesh_direct_dispatches (
167
+ task_id TEXT PRIMARY KEY,
168
+ mesh_id TEXT NOT NULL,
169
+ node_id TEXT,
170
+ session_id TEXT,
171
+ provider_type TEXT,
172
+ message TEXT NOT NULL,
173
+ task_mode TEXT,
174
+ via TEXT NOT NULL,
175
+ status TEXT NOT NULL DEFAULT 'dispatched',
176
+ dispatched_to_idle_session INTEGER NOT NULL DEFAULT 0,
177
+ dispatched_at TEXT NOT NULL,
178
+ updated_at TEXT NOT NULL
179
+ );
180
+
181
+ CREATE INDEX IF NOT EXISTS idx_direct_dispatches_mesh_session
182
+ ON mesh_direct_dispatches(mesh_id, session_id, status);
183
+
184
+ -- MESH-ISOLATION-LEAK: mesh_id is part of the PK so a nodeId shared across two
185
+ -- meshes (same machine in multiple repos) keeps a separate idle-session row per
186
+ -- mesh, and getRemoteIdleSessions(meshId) can never surface another mesh's
187
+ -- session for a queue claim.
188
+ CREATE TABLE IF NOT EXISTS remote_idle_sessions (
189
+ mesh_id TEXT NOT NULL,
190
+ node_id TEXT NOT NULL,
191
+ session_id TEXT NOT NULL,
192
+ provider_type TEXT NOT NULL,
193
+ expires_at INTEGER NOT NULL,
194
+ metadata TEXT,
195
+ PRIMARY KEY (mesh_id, node_id, session_id)
196
+ );
197
+
198
+ CREATE TABLE IF NOT EXISTS mesh_session_delivery (
199
+ id TEXT PRIMARY KEY,
200
+ mesh_id TEXT NOT NULL,
201
+ node_id TEXT,
202
+ session_id TEXT,
203
+ provider_type TEXT,
204
+ task_id TEXT,
205
+ kind TEXT NOT NULL,
206
+ priority INTEGER NOT NULL DEFAULT 0,
207
+ message TEXT NOT NULL,
208
+ status TEXT NOT NULL DEFAULT 'queued',
209
+ deliver_after TEXT,
210
+ expires_at TEXT,
211
+ attempt_count INTEGER NOT NULL DEFAULT 0,
212
+ source_coordinator_session_id TEXT,
213
+ source_coordinator_daemon_id TEXT,
214
+ last_error TEXT,
215
+ created_at TEXT NOT NULL,
216
+ updated_at TEXT NOT NULL
217
+ );
218
+
219
+ CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_mesh_status
220
+ ON mesh_session_delivery(mesh_id, status, created_at);
221
+ CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_session
222
+ ON mesh_session_delivery(mesh_id, session_id, status);
223
+ CREATE INDEX IF NOT EXISTS idx_mesh_session_delivery_task
224
+ ON mesh_session_delivery(mesh_id, task_id);
225
+
226
+ CREATE TABLE IF NOT EXISTS mesh_completion_conflicts (
227
+ id TEXT PRIMARY KEY,
228
+ mesh_id TEXT NOT NULL,
229
+ fingerprint TEXT NOT NULL,
230
+ conflicting_task_id TEXT,
231
+ conflicting_session_id TEXT,
232
+ original_task_id TEXT,
233
+ original_session_id TEXT,
234
+ event TEXT NOT NULL,
235
+ created_at TEXT NOT NULL
236
+ );
237
+
238
+ CREATE INDEX IF NOT EXISTS idx_mesh_completion_conflicts_mesh
239
+ ON mesh_completion_conflicts(mesh_id, created_at);
240
+
241
+ CREATE TABLE IF NOT EXISTS mesh_tool_call_log (
242
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
243
+ mesh_id TEXT NOT NULL,
244
+ tool TEXT NOT NULL,
245
+ session_id TEXT,
246
+ called_at INTEGER NOT NULL
247
+ );
248
+
249
+ CREATE INDEX IF NOT EXISTS idx_mesh_tool_call_log_mesh_tool_time
250
+ ON mesh_tool_call_log(mesh_id, tool, called_at);
251
+
252
+ -- G2: Event ledger — runtime source of truth for task/session lifecycle events.
253
+ -- JSONL files are retained as export/import/debug/legacy artifacts only.
254
+ CREATE TABLE IF NOT EXISTS mesh_event_ledger (
255
+ id TEXT PRIMARY KEY,
256
+ mesh_id TEXT NOT NULL,
257
+ timestamp TEXT NOT NULL,
258
+ kind TEXT NOT NULL,
259
+ node_id TEXT,
260
+ session_id TEXT,
261
+ provider_type TEXT,
262
+ payload TEXT NOT NULL DEFAULT '{}'
263
+ );
264
+
265
+ CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_mesh_time
266
+ ON mesh_event_ledger(mesh_id, timestamp);
267
+ CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_mesh_kind
268
+ ON mesh_event_ledger(mesh_id, kind, timestamp);
269
+ CREATE INDEX IF NOT EXISTS idx_mesh_event_ledger_session
270
+ ON mesh_event_ledger(mesh_id, session_id, timestamp);
271
+
272
+ -- G3: Pending coordinator event inbox — replaces <meshId>.pending-events.jsonl.
273
+ -- Coordinator drains this table on get_pending_mesh_events, then deletes drained rows.
274
+ CREATE TABLE IF NOT EXISTS mesh_pending_events (
275
+ id TEXT PRIMARY KEY,
276
+ mesh_id TEXT NOT NULL,
277
+ coordinator_daemon_id TEXT,
278
+ event TEXT NOT NULL,
279
+ payload TEXT NOT NULL DEFAULT '{}',
280
+ fingerprint TEXT,
281
+ queued_at INTEGER NOT NULL,
282
+ drained INTEGER NOT NULL DEFAULT 0,
283
+ drained_at INTEGER
284
+ );
285
+
286
+ CREATE INDEX IF NOT EXISTS idx_mesh_pending_events_mesh_drained
287
+ ON mesh_pending_events(mesh_id, drained, queued_at);
288
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_mesh_pending_events_fingerprint
289
+ ON mesh_pending_events(mesh_id, fingerprint)
290
+ WHERE fingerprint IS NOT NULL;
291
+
292
+ -- M3: persistent mission records. Plans live in the system, not in the
293
+ -- coordinator LLM's context. Progress is derived from task statuses at
294
+ -- query time (mission_id on queue tasks) — never stored here.
295
+ CREATE TABLE IF NOT EXISTS mesh_missions (
296
+ id TEXT PRIMARY KEY,
297
+ mesh_id TEXT NOT NULL,
298
+ title TEXT NOT NULL,
299
+ goal TEXT NOT NULL DEFAULT '',
300
+ status TEXT NOT NULL DEFAULT 'active',
301
+ source TEXT,
302
+ created_at TEXT NOT NULL,
303
+ updated_at TEXT NOT NULL
304
+ );
305
+
306
+ CREATE INDEX IF NOT EXISTS idx_mesh_missions_mesh_status
307
+ ON mesh_missions(mesh_id, status, updated_at);
308
+
309
+ -- Load-balancing scheduler: per-mesh round-robin rotation cursor. When
310
+ -- the schedulingStrategy is 'round_robin', several eligible nodes tied at
311
+ -- the least load are rotated by this cursor so the tie-break winner cycles
312
+ -- across scheduling passes instead of always favouring the same array-order
313
+ -- node. Persisted (not a module Map) so rotation survives daemon restarts
314
+ -- and stays a single source of truth across scheduling entry points.
315
+ CREATE TABLE IF NOT EXISTS mesh_scheduler_cursor (
316
+ mesh_id TEXT PRIMARY KEY,
317
+ cursor INTEGER NOT NULL DEFAULT 0
318
+ );
319
+ `);
320
+ this.migrateMeshIsolationColumns();
321
+ }
322
+
323
+ private tableColumns(table: string): Set<string> {
324
+ const rows = this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
325
+ return new Set(rows.map(r => r.name));
326
+ }
327
+
328
+ /**
329
+ * MESH-ISOLATION-LEAK migration. Two tables historically lacked a `mesh_id` column,
330
+ * letting one machine that belongs to multiple meshes (multiple repos) leak rows
331
+ * across meshes. Both migrations are idempotent and run on every boot — the column
332
+ * check short-circuits once the new schema is in place.
333
+ */
334
+ private migrateMeshIsolationColumns(): void {
335
+ try {
336
+ // 1. mesh_completion_fingerprints: ADD COLUMN + backfill mesh_id from the
337
+ // fingerprint string's first '::'-joined segment (buildMeshCompletionFingerprint
338
+ // prefixes meshId). A row whose fingerprint has no '::' (legacy/foreign format)
339
+ // backfills to '' — still strictly tighter than the prior global query.
340
+ const fpCols = this.tableColumns('mesh_completion_fingerprints');
341
+ if (!fpCols.has('mesh_id')) {
342
+ this.db.exec(`ALTER TABLE mesh_completion_fingerprints ADD COLUMN mesh_id TEXT NOT NULL DEFAULT ''`);
343
+ this.db.exec(`
344
+ UPDATE mesh_completion_fingerprints
345
+ SET mesh_id = substr(fingerprint, 1, instr(fingerprint, '::') - 1)
346
+ WHERE instr(fingerprint, '::') > 0 AND mesh_id = ''
347
+ `);
348
+ }
349
+ // The mesh_id column is now guaranteed to exist (fresh DB had it from CREATE TABLE,
350
+ // legacy DB just got it via ALTER). Create the index unconditionally — IF NOT EXISTS
351
+ // makes it a no-op once present.
352
+ this.db.exec(`
353
+ CREATE INDEX IF NOT EXISTS idx_mesh_completion_fingerprints_mesh
354
+ ON mesh_completion_fingerprints(mesh_id, fingerprint)
355
+ `);
356
+
357
+ // 2. remote_idle_sessions: the mesh_id is part of the PRIMARY KEY, which SQLite
358
+ // cannot add via ALTER. The rows are ephemeral — sessions re-register on the
359
+ // next agent:ready / agent:generating_completed — so a safe DROP+recreate is
360
+ // acceptable (per fix spec) rather than a full table rebuild + un-backfillable
361
+ // mesh_id. Only rebuild when the legacy (no mesh_id) schema is detected.
362
+ const idleCols = this.tableColumns('remote_idle_sessions');
363
+ if (!idleCols.has('mesh_id')) {
364
+ this.db.exec(`
365
+ DROP TABLE IF EXISTS remote_idle_sessions;
366
+ CREATE TABLE remote_idle_sessions (
367
+ mesh_id TEXT NOT NULL,
368
+ node_id TEXT NOT NULL,
369
+ session_id TEXT NOT NULL,
370
+ provider_type TEXT NOT NULL,
371
+ expires_at INTEGER NOT NULL,
372
+ metadata TEXT,
373
+ PRIMARY KEY (mesh_id, node_id, session_id)
374
+ );
375
+ `);
376
+ }
377
+
378
+ // 3. mesh_missions.source: nullable provenance tag ('magi' | 'coordinator').
379
+ // Pre-existing rows keep source NULL — listMeshMissionSummaries treats a
380
+ // NULL/absent source as a coordinator mission (never auto-hidden), so the
381
+ // completed-MAGI bounding only ever affects rows explicitly stamped 'magi'.
382
+ const missionCols = this.tableColumns('mesh_missions');
383
+ if (!missionCols.has('source')) {
384
+ this.db.exec(`ALTER TABLE mesh_missions ADD COLUMN source TEXT`);
385
+ }
386
+ } catch (err: any) {
387
+ // Best-effort: a failed isolation migration must not brick the store. The
388
+ // CREATE-TABLE definitions above already carry the new schema for fresh DBs;
389
+ // an existing DB that fails here keeps the old (leaky-but-functional) schema
390
+ // until the next boot retries. Surface one warn for diagnosability.
391
+ if (!loggedMigrationFailure) {
392
+ loggedMigrationFailure = true;
393
+ LOG.warn('MeshRuntimeStore', `mesh-isolation column migration failed: ${err?.message || err}`);
394
+ }
395
+ }
396
+ }
397
+
398
+ hasCompletionFingerprint(meshId: string, fingerprint: string): boolean {
399
+ const now = Date.now();
400
+ // Scope by mesh_id (defense-in-depth) AS WELL AS the fingerprint string, whose
401
+ // first '::' segment already encodes meshId. A fingerprint can only suppress a
402
+ // duplicate within its own mesh.
403
+ const row = this.db
404
+ .prepare('SELECT 1 FROM mesh_completion_fingerprints WHERE mesh_id = ? AND fingerprint = ? AND expires_at > ?')
405
+ .get(meshId, fingerprint, now) as { 1: number } | undefined;
406
+ // Sweep expired fingerprints every 100 reads so stale rows don't accumulate
407
+ // even during read-heavy (non-write) periods when recordFingerprintSeen is idle.
408
+ if (++this.fingerprintSweepCounter >= 100) {
409
+ this.fingerprintSweepCounter = 0;
410
+ this.sweepExpiredFingerprints();
411
+ }
412
+ return row !== undefined;
413
+ }
414
+
415
+ recordCompletionFingerprint(meshId: string, fingerprint: string, ttlMs: number): void {
416
+ const expiresAt = Date.now() + ttlMs;
417
+ this.db.prepare('INSERT OR REPLACE INTO mesh_completion_fingerprints (fingerprint, expires_at, mesh_id) VALUES (?, ?, ?)')
418
+ .run(fingerprint, expiresAt, meshId);
419
+ this.maybeCheckpointWal();
420
+ }
421
+
422
+ sweepExpiredFingerprints(): void {
423
+ this.db.prepare('DELETE FROM mesh_completion_fingerprints WHERE expires_at <= ?').run(Date.now());
424
+ }
425
+
426
+ private maybeCheckpointWal(): void {
427
+ if (++this.walWriteCounter < MeshRuntimeStore.WAL_CHECK_INTERVAL) return;
428
+ this.walWriteCounter = 0;
429
+ try {
430
+ const walPath = `${this.dbPath}-wal`;
431
+ if (!existsSync(walPath)) return;
432
+ const size = statSync(walPath).size;
433
+ if (size < MeshRuntimeStore.WAL_MAX_BYTES) return;
434
+ process.stderr.write(
435
+ `[adhdev-mesh] WAL file ${Math.round(size / 1024 / 1024)}MB exceeds threshold; forcing checkpoint\n`,
436
+ );
437
+ this.db.pragma('wal_checkpoint(TRUNCATE)');
438
+ } catch { /* best-effort */ }
439
+ }
440
+
441
+ private ensureLegacyQueueMigrated(meshId: string): void {
442
+ if (this.migratedMeshIds.has(meshId)) return;
443
+ this.migratedMeshIds.add(meshId);
444
+
445
+ const count = this.db
446
+ .prepare('SELECT COUNT(*) AS count FROM mesh_queue WHERE mesh_id = ?')
447
+ .get(meshId) as { count: number };
448
+ if (count.count > 0) return;
449
+
450
+ const path = legacyQueuePath(meshId);
451
+ if (!existsSync(path)) return;
452
+
453
+ try {
454
+ const entries = JSON.parse(readFileSync(path, 'utf-8')) as MeshWorkQueueEntry[];
455
+ if (!Array.isArray(entries)) return;
456
+ const insert = this.db.prepare(`
457
+ INSERT OR REPLACE INTO mesh_queue (
458
+ id, mesh_id, status, target_node_id, target_session_id,
459
+ assigned_node_id, assigned_session_id, created_at, updated_at, payload
460
+ ) VALUES (
461
+ @id, @meshId, @status, @targetNodeId, @targetSessionId,
462
+ @assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
463
+ )
464
+ `);
465
+ for (const entry of entries) {
466
+ insert.run(this.toRow(entry));
467
+ }
468
+ } catch {
469
+ return;
470
+ }
471
+ }
472
+
473
+ getQueueEntries(meshId: string, statuses?: MeshTaskStatus[]): MeshWorkQueueEntry[] {
474
+ this.ensureLegacyQueueMigrated(meshId);
475
+ if (statuses?.length) {
476
+ const placeholders = statuses.map(() => '?').join(', ');
477
+ const rows = this.db
478
+ .prepare(`SELECT payload FROM mesh_queue WHERE mesh_id = ? AND status IN (${placeholders}) ORDER BY created_at ASC`)
479
+ .all(meshId, ...statuses) as Array<{ payload: string }>;
480
+ return rows.map(row => JSON.parse(row.payload) as MeshWorkQueueEntry);
481
+ }
482
+ const rows = this.db
483
+ .prepare('SELECT payload FROM mesh_queue WHERE mesh_id = ? ORDER BY created_at ASC')
484
+ .all(meshId) as Array<{ payload: string }>;
485
+ return rows.map(row => JSON.parse(row.payload) as MeshWorkQueueEntry);
486
+ }
487
+
488
+ getQueueRevision(meshId: string): string {
489
+ this.ensureLegacyQueueMigrated(meshId);
490
+ const rows = this.db
491
+ .prepare('SELECT id, status, updated_at FROM mesh_queue WHERE mesh_id = ? ORDER BY id ASC')
492
+ .all(meshId) as Array<{ id: string; status: string; updated_at: string }>;
493
+ // Tab as field delimiter (UUIDs and ISO timestamps never contain tabs).
494
+ return rows.map(row => `${row.id}\t${row.status}\t${row.updated_at}`).join('\n');
495
+ }
496
+
497
+ replaceQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
498
+ const deleteStmt = this.db.prepare('DELETE FROM mesh_queue WHERE mesh_id = ?');
499
+ const insert = this.db.prepare(`
500
+ INSERT INTO mesh_queue (
501
+ id, mesh_id, status, target_node_id, target_session_id,
502
+ assigned_node_id, assigned_session_id, created_at, updated_at, payload
503
+ ) VALUES (
504
+ @id, @meshId, @status, @targetNodeId, @targetSessionId,
505
+ @assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
506
+ )
507
+ `);
508
+ deleteStmt.run(meshId);
509
+ for (const entry of queue) insert.run(this.toRow(entry));
510
+ this.maybeCheckpointWal();
511
+ }
512
+
513
+ deleteQueue(meshId: string): void {
514
+ this.db.prepare('DELETE FROM mesh_queue WHERE mesh_id = ?').run(meshId);
515
+ this.migratedMeshIds.delete(meshId);
516
+ }
517
+
518
+ insertQueueEntry(entry: MeshWorkQueueEntry): void {
519
+ this.db.prepare(`
520
+ INSERT INTO mesh_queue (
521
+ id, mesh_id, status, target_node_id, target_session_id,
522
+ assigned_node_id, assigned_session_id, created_at, updated_at, payload
523
+ ) VALUES (
524
+ @id, @meshId, @status, @targetNodeId, @targetSessionId,
525
+ @assignedNodeId, @assignedSessionId, @createdAt, @updatedAt, @payload
526
+ )
527
+ `).run(this.toRow(entry));
528
+ this.maybeCheckpointWal();
529
+ }
530
+
531
+ updateQueueEntry(entry: MeshWorkQueueEntry): void {
532
+ const now = new Date().toISOString();
533
+ entry.updatedAt = now;
534
+ this.db.prepare(`
535
+ UPDATE mesh_queue SET
536
+ status = @status,
537
+ target_node_id = @targetNodeId,
538
+ target_session_id = @targetSessionId,
539
+ assigned_node_id = @assignedNodeId,
540
+ assigned_session_id = @assignedSessionId,
541
+ updated_at = @updatedAt,
542
+ payload = @payload
543
+ WHERE id = @id AND mesh_id = @meshId
544
+ `).run(this.toRow(entry));
545
+ this.maybeCheckpointWal();
546
+ }
547
+
548
+ findQueueEntryById(meshId: string, id: string): MeshWorkQueueEntry | null {
549
+ this.ensureLegacyQueueMigrated(meshId);
550
+ const row = this.db.prepare(
551
+ 'SELECT payload FROM mesh_queue WHERE id = ? AND mesh_id = ?'
552
+ ).get(id, meshId) as { payload: string } | undefined;
553
+ return row ? JSON.parse(row.payload) as MeshWorkQueueEntry : null;
554
+ }
555
+
556
+ hasActiveAssignment(meshId: string, sessionId: string, nodeId: string): boolean {
557
+ this.ensureLegacyQueueMigrated(meshId);
558
+ const row = this.db.prepare(`
559
+ SELECT 1 FROM mesh_queue
560
+ WHERE mesh_id = ? AND status = 'assigned'
561
+ AND (assigned_session_id = ? OR assigned_node_id = ?)
562
+ LIMIT 1
563
+ `).get(meshId, sessionId, nodeId);
564
+ return row !== undefined;
565
+ }
566
+
567
+ /** A session may only execute one task at a time, regardless of task mode. */
568
+ private hasActiveSessionAssignment(meshId: string, sessionId: string): boolean {
569
+ const row = this.db.prepare(`
570
+ SELECT 1 FROM mesh_queue
571
+ WHERE mesh_id = ? AND status = 'assigned' AND assigned_session_id = ?
572
+ LIMIT 1
573
+ `).get(meshId, sessionId);
574
+ return row !== undefined;
575
+ }
576
+
577
+ /** A node may only execute one write task at a time (worktree isolation). */
578
+ private hasActiveNodeAssignment(meshId: string, nodeId: string): boolean {
579
+ // The serialization gate (claimNextQueueTask's `!nodeBusy`) must see a node as
580
+ // busy when ANY active row's assigned_node_id matches in ANY equivalent
581
+ // daemon-id form (config-form `daemon_mach_X` vs stamp-form `mach_X`, or the
582
+ // standalone form). A raw `assigned_node_id = ?` on a single form silently
583
+ // misses a form-variant assigned row, making an already-assigned node look idle
584
+ // and letting a second write task claim it — duplicate claim / base leak. Mirror
585
+ // the node-pinned SELECT below (the `target_node_id IN (...)` query): expand to
586
+ // every equivalent form and bind an IN (...) set so the busy gate and the
587
+ // candidate SELECT use the SAME matching rule.
588
+ const nodeIdForms = expandDaemonIdForms(nodeId);
589
+ if (nodeIdForms.length === 0) return false;
590
+ const placeholders = nodeIdForms.map(() => '?').join(', ');
591
+ const row = this.db.prepare(`
592
+ SELECT 1 FROM mesh_queue
593
+ WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id IN (${placeholders})
594
+ LIMIT 1
595
+ `).get(meshId, ...nodeIdForms);
596
+ return row !== undefined;
597
+ }
598
+
599
+ /**
600
+ * Count active (status='assigned') tasks on a node, regardless of provider or
601
+ * task mode. This is the load metric for least-loaded / round-robin ranking:
602
+ * the scheduler prefers the node with the fewest active assignments so
603
+ * untargeted work spreads instead of piling onto whichever node asks first.
604
+ */
605
+ nodeActiveAssignmentCount(meshId: string, nodeId: string): number {
606
+ const row = this.db.prepare(`
607
+ SELECT COUNT(*) as count FROM mesh_queue
608
+ WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
609
+ `).get(meshId, nodeId) as { count: number } | undefined;
610
+ return row?.count ?? 0;
611
+ }
612
+
613
+ /**
614
+ * O(1) count of queue tasks in 'pending' status for a mesh. A COUNT(*) over the
615
+ * indexed status column, so it avoids JSON.parse-ing every queue row — used as a
616
+ * cheap guard before the reconcile loop runs a full triggerMeshQueue scan.
617
+ */
618
+ pendingQueueTaskCount(meshId: string): number {
619
+ const row = this.db.prepare(`
620
+ SELECT COUNT(*) as count FROM mesh_queue
621
+ WHERE mesh_id = ? AND status = 'pending'
622
+ `).get(meshId) as { count: number } | undefined;
623
+ return row?.count ?? 0;
624
+ }
625
+
626
+ /**
627
+ * Read the current per-mesh round-robin cursor (0 when unset). Used to rotate
628
+ * the tie-break winner among nodes tied at the least load.
629
+ */
630
+ getSchedulerCursor(meshId: string): number {
631
+ const row = this.db.prepare(
632
+ 'SELECT cursor FROM mesh_scheduler_cursor WHERE mesh_id = ?'
633
+ ).get(meshId) as { cursor: number } | undefined;
634
+ return row?.cursor ?? 0;
635
+ }
636
+
637
+ /**
638
+ * Atomically advance the per-mesh round-robin cursor by one and return the
639
+ * value that was current BEFORE the bump (the value the caller should rotate
640
+ * by for this pass). UPSERT keeps it lock-free across concurrent passes.
641
+ */
642
+ bumpSchedulerCursor(meshId: string): number {
643
+ return this.transaction(() => {
644
+ const current = this.getSchedulerCursor(meshId);
645
+ this.db.prepare(`
646
+ INSERT INTO mesh_scheduler_cursor (mesh_id, cursor) VALUES (?, ?)
647
+ ON CONFLICT(mesh_id) DO UPDATE SET cursor = excluded.cursor
648
+ `).run(meshId, current + 1);
649
+ return current;
650
+ });
651
+ }
652
+
653
+ /**
654
+ * Count active (status='assigned') tasks on a (node, provider) combination,
655
+ * matched by the assignedProviderType stamped on the payload at claim time.
656
+ * Drives the per-(node, provider) maxParallel cap (RepoMeshNodePolicy
657
+ * providerRoles). The active-assignment set for a single node is tiny, so
658
+ * parsing payloads here is cheap and avoids a schema migration. Pre-cap legacy
659
+ * rows (no provider stamp) and other providers on the same node do not consume
660
+ * this provider's budget, so the cap is fully backward compatible.
661
+ */
662
+ private activeProviderAssignmentCount(meshId: string, nodeId: string, providerType: string): number {
663
+ const rows = this.db.prepare(`
664
+ SELECT payload FROM mesh_queue
665
+ WHERE mesh_id = ? AND status = 'assigned' AND assigned_node_id = ?
666
+ `).all(meshId, nodeId) as Array<{ payload: string }>;
667
+ let count = 0;
668
+ for (const row of rows) {
669
+ try {
670
+ const entry = JSON.parse(row.payload) as MeshWorkQueueEntry;
671
+ if (entry.assignedProviderType === providerType) count += 1;
672
+ } catch { /* skip unparsable row */ }
673
+ }
674
+ return count;
675
+ }
676
+
677
+ // O(1) claim: transaction ensures only one session claims a pending task
678
+ claimNextQueueTask(
679
+ meshId: string,
680
+ nodeId: string,
681
+ sessionId: string,
682
+ capabilityTags: string[] = [],
683
+ opts?: { providerType?: string; providerMaxParallel?: number; nodeIsWorktree?: boolean },
684
+ ): MeshWorkQueueEntry | null {
685
+ return this.transaction(() => {
686
+ this.ensureLegacyQueueMigrated(meshId);
687
+ // A session executes one task at a time regardless of mode — block early.
688
+ // The node-level conflict is evaluated per-candidate below so that
689
+ // read-only (live_debug_readonly) tasks can claim concurrently on a node
690
+ // that already has an active assignment, while write tasks keep the
691
+ // one-active-per-node invariant (worktree isolation).
692
+ if (this.hasActiveSessionAssignment(meshId, sessionId)) return null;
693
+ const nodeBusy = this.hasActiveNodeAssignment(meshId, nodeId);
694
+
695
+ // Per-(node, provider) maxParallel cap (RepoMeshNodePolicy providerRoles).
696
+ // Orthogonal to taskMode: this bounds the (node, provider) resource pool
697
+ // regardless of read-only vs write. When the cap is already met, this
698
+ // session cannot claim any candidate here — return null. This composes
699
+ // with the global/taskMode caps enforced in the coordinator (stricter
700
+ // wins); omitting providerMaxParallel preserves prior behavior exactly.
701
+ const providerType = typeof opts?.providerType === 'string' ? opts.providerType.trim() : '';
702
+ const providerMaxParallel = opts?.providerMaxParallel;
703
+ if (
704
+ providerType
705
+ && typeof providerMaxParallel === 'number'
706
+ && Number.isFinite(providerMaxParallel)
707
+ && providerMaxParallel >= 0
708
+ && this.activeProviderAssignmentCount(meshId, nodeId, providerType) >= providerMaxParallel
709
+ ) {
710
+ return null;
711
+ }
712
+
713
+ // The node-pinned SELECT must match a row whose target_node_id was stamped
714
+ // in ANY equivalent daemon-id form (config-form `daemon_mach_X` vs the
715
+ // claiming session's stamp-form `mach_X`). A single `= ?` bind on the
716
+ // stamp-form silently fails to fetch a config-form row, leaving the task
717
+ // pending forever (the empty-session WORKTREE-CLAIM-GATE repro). Expand to
718
+ // every equivalent form and bind an IN (...) set; the per-candidate
719
+ // targetMatches() JS gate above re-validates each fetched row.
720
+ const nodeIdForms = expandDaemonIdForms(nodeId);
721
+ const nodePinnedPlaceholders = nodeIdForms.map(() => '?').join(', ');
722
+ // Priority: session-targeted > node-targeted (no session) > unconstrained
723
+ const rows = [
724
+ ...(
725
+ this.db.prepare(`
726
+ SELECT payload FROM mesh_queue
727
+ WHERE mesh_id = ? AND status = 'pending' AND target_session_id = ?
728
+ ORDER BY created_at ASC
729
+ `).all(meshId, sessionId) as Array<{ payload: string }>
730
+ ),
731
+ ...(
732
+ this.db.prepare(`
733
+ SELECT payload FROM mesh_queue
734
+ WHERE mesh_id = ? AND status = 'pending' AND target_node_id IN (${nodePinnedPlaceholders}) AND target_session_id IS NULL
735
+ ORDER BY created_at ASC
736
+ `).all(meshId, ...nodeIdForms) as Array<{ payload: string }>
737
+ ),
738
+ ...(
739
+ this.db.prepare(`
740
+ SELECT payload FROM mesh_queue
741
+ WHERE mesh_id = ? AND status = 'pending' AND target_node_id IS NULL AND target_session_id IS NULL
742
+ ORDER BY created_at ASC
743
+ `).all(meshId) as Array<{ payload: string }>
744
+ ),
745
+ ];
746
+ const candidates = rows.map(row => JSON.parse(row.payload) as MeshWorkQueueEntry);
747
+
748
+ // M1: a task with unmet dependencies (or a system blockedReason) is not claimable.
749
+ // Resolve dependency statuses in one query over the union of referenced ids.
750
+ const depIds = [...new Set(candidates.flatMap(c => Array.isArray(c.dependsOn) ? c.dependsOn : []))];
751
+ const depStatus = new Map<string, string>();
752
+ if (depIds.length > 0) {
753
+ const placeholders = depIds.map(() => '?').join(', ');
754
+ const depRows = this.db.prepare(
755
+ `SELECT id, status FROM mesh_queue WHERE mesh_id = ? AND id IN (${placeholders})`
756
+ ).all(meshId, ...depIds) as Array<{ id: string; status: string }>;
757
+ for (const r of depRows) depStatus.set(r.id, r.status);
758
+ }
759
+ const dependenciesSatisfied = (candidate: MeshWorkQueueEntry): boolean => {
760
+ if (candidate.blockedReason) return false;
761
+ const deps = Array.isArray(candidate.dependsOn) ? candidate.dependsOn : [];
762
+ return deps.every(depId => depStatus.get(depId) === 'completed');
763
+ };
764
+
765
+ // Per-candidate node-conflict gate: write tasks require an idle node; read-only
766
+ // tasks bypass the node-busy check so N read-only diagnoses can run on one node
767
+ // at once. Read-only classification is decided solely by isTaskReadonly (the
768
+ // single predicate shared with the cap counters / auto-launch / guardrail).
769
+ const nodeConflictAllows = (candidate: MeshWorkQueueEntry): boolean => {
770
+ if (isTaskReadonly(candidate)) return true;
771
+ return !nodeBusy;
772
+ };
773
+
774
+ // WTDISPATCH-FANOUT: a `convergence` task lands its work onto base (merge →
775
+ // push → cleanup against the real checkout). It must NEVER be claimed by a
776
+ // co-located worktree-clone session — N sibling worktree sessions on one daemon
777
+ // each claiming the same convergence intent is the 4-way push/deploy fan-out the
778
+ // live repro hit. Base-only, fail-closed: when the claiming node is a worktree
779
+ // (nodeIsWorktree), exclude every convergence candidate so it stays pending for
780
+ // the base node to pull.
781
+ const nodeIsWorktree = opts?.nodeIsWorktree === true;
782
+ const convergenceAllows = (candidate: MeshWorkQueueEntry): boolean =>
783
+ candidate.taskMode !== 'convergence' || !nodeIsWorktree;
784
+
785
+ // WTDISPATCH-FANOUT: defensive exact-target gate. The prioritized SQL above
786
+ // already segregates session/node-pinned rows, but a future query change (or a
787
+ // candidate row whose stored target drifted from its column) must never let a
788
+ // sibling worktree session on the same daemon absorb another node's/session's
789
+ // pinned task. When a task carries an explicit target, require an exact match
790
+ // here too — fail-closed.
791
+ // The target id may have been stamped in a different serialization /
792
+ // daemon-id form than the claiming session's nodeId (config-form
793
+ // `daemon_mach_X` vs stamp-form `mach_X`, or the 3-way id/nodeId/node_id
794
+ // node forms). A raw `!==` here permanently strands a node-pinned task as
795
+ // an empty session. Accept the candidate when the target resolves to the
796
+ // same node under ANY equivalent form; keep targetSessionId an exact match.
797
+ const targetMatches = (candidate: MeshWorkQueueEntry): boolean => {
798
+ // SESSION-ID IS SINGLE-FORM: unlike node/daemon ids (3 serialization
799
+ // forms requiring expandDaemonIdForms), a session id is a single
800
+ // canonical UUID minted once via crypto.randomUUID() in the provider
801
+ // instance (cli/acp/extension/ide) and carried verbatim across daemons
802
+ // (resolveEventSessionId applies no transformation). So an exact `!==`
803
+ // is correct here and needs no normalization helper.
804
+ if (candidate.targetSessionId && candidate.targetSessionId !== sessionId) return false;
805
+ if (
806
+ candidate.targetNodeId
807
+ && !daemonIdsEquivalent(candidate.targetNodeId, nodeId)
808
+ && !meshNodeIdMatches({ id: candidate.targetNodeId }, nodeId)
809
+ ) {
810
+ return false;
811
+ }
812
+ return true;
813
+ };
814
+
815
+ const entry = candidates.find(candidate =>
816
+ nodeSatisfiesRequiredTags(candidate.requiredTags, capabilityTags)
817
+ && dependenciesSatisfied(candidate)
818
+ && convergenceAllows(candidate)
819
+ && targetMatches(candidate)
820
+ && nodeConflictAllows(candidate));
821
+ if (!entry) return null;
822
+
823
+ const now = new Date().toISOString();
824
+ entry.status = 'assigned';
825
+ entry.assignedNodeId = nodeId;
826
+ entry.assignedSessionId = sessionId;
827
+ if (providerType) entry.assignedProviderType = providerType;
828
+ entry.dispatchTimestamp = now;
829
+ entry.updatedAt = now;
830
+
831
+ this.db.prepare(`
832
+ UPDATE mesh_queue SET
833
+ status = 'assigned', assigned_node_id = ?, assigned_session_id = ?,
834
+ updated_at = ?, payload = ?
835
+ WHERE id = ? AND mesh_id = ?
836
+ `).run(nodeId, sessionId, now, JSON.stringify(entry), entry.id, meshId);
837
+
838
+ this.maybeCheckpointWal();
839
+ return entry;
840
+ });
841
+ }
842
+
843
+ getQueueStatsByStatus(meshId: string): { status: string; count: number }[] {
844
+ this.ensureLegacyQueueMigrated(meshId);
845
+ return this.db.prepare(
846
+ `SELECT status, COUNT(*) as count FROM mesh_queue WHERE mesh_id = ? GROUP BY status`
847
+ ).all(meshId) as { status: string; count: number }[];
848
+ }
849
+
850
+ getActiveAssignmentDetails(meshId: string): Array<{ id: string; nodeId?: string; sessionId?: string; message: string }> {
851
+ this.ensureLegacyQueueMigrated(meshId);
852
+ const rows = this.db.prepare(`
853
+ SELECT assigned_node_id, assigned_session_id, payload
854
+ FROM mesh_queue WHERE mesh_id = ? AND status = 'assigned'
855
+ `).all(meshId) as Array<{ assigned_node_id: string | null; assigned_session_id: string | null; payload: string }>;
856
+ return rows.map(r => {
857
+ let id = '', message = '';
858
+ try { const e = JSON.parse(r.payload) as MeshWorkQueueEntry; id = e.id; message = e.message; } catch { /* ignore */ }
859
+ return { id, nodeId: r.assigned_node_id ?? undefined, sessionId: r.assigned_session_id ?? undefined, message };
860
+ });
861
+ }
862
+
863
+ /**
864
+ * Resolve the `assigned` queue row a completion event belongs to.
865
+ *
866
+ * Clock-skew safety (C2): a completion event's `occurredAtIso` carries the
867
+ * REMOTE WORKER's clock, while `updated_at` carries the COORDINATOR's clock
868
+ * (set at assignment and re-bumped on every mutation). For a remote node,
869
+ * coordinator-clock > worker-clock skew used to make an `updated_at <= occurredAt`
870
+ * filter return nothing, stranding the finished task as `assigned` forever.
871
+ *
872
+ * We therefore NEVER filter completion-matching on the mutable `updated_at`:
873
+ * 1. If `taskId` is given, match the exact `assigned` row by id (no time filter).
874
+ * 2. Otherwise a session holds at most one `assigned` task — match it without a
875
+ * time filter. If several exist (shouldn't normally), disambiguate by the
876
+ * IMMUTABLE `dispatchTimestamp`: latest `dispatchTimestamp <= occurredAt`,
877
+ * and if skew makes ALL of them later than `occurredAt`, fall back to the
878
+ * most-recent `dispatchTimestamp` rather than returning null.
879
+ */
880
+ findAssignedBySession(
881
+ meshId: string,
882
+ sessionId: string,
883
+ occurredAtIso?: string,
884
+ taskId?: string,
885
+ ): MeshWorkQueueEntry | null {
886
+ this.ensureLegacyQueueMigrated(meshId);
887
+
888
+ // 1. Exact taskId match — robust against clock skew and stale rows.
889
+ if (taskId) {
890
+ const row = this.db.prepare(
891
+ `SELECT payload FROM mesh_queue WHERE mesh_id = ? AND assigned_session_id = ? AND status = 'assigned' AND id = ? LIMIT 1`
892
+ ).get(meshId, sessionId, taskId) as { payload: string } | undefined;
893
+ if (row) return JSON.parse(row.payload) as MeshWorkQueueEntry;
894
+ // Fall through to session-based matching if the id didn't line up
895
+ // (e.g. event carried a stale/foreign taskId).
896
+ }
897
+
898
+ // 2. Session-based match WITHOUT the mutable updated_at filter.
899
+ const rows = this.db.prepare(
900
+ `SELECT payload FROM mesh_queue WHERE mesh_id = ? AND assigned_session_id = ? AND status = 'assigned'`
901
+ ).all(meshId, sessionId) as Array<{ payload: string }>;
902
+ if (rows.length === 0) return null;
903
+
904
+ const entries = rows
905
+ .map(r => { try { return JSON.parse(r.payload) as MeshWorkQueueEntry; } catch { return null; } })
906
+ .filter((e): e is MeshWorkQueueEntry => e !== null);
907
+ if (entries.length === 0) return null;
908
+ if (entries.length === 1) return entries[0];
909
+
910
+ // Multiple assigned rows for one session: disambiguate by the immutable
911
+ // dispatchTimestamp (falling back to updated_at only for legacy rows that
912
+ // predate dispatchTimestamp). We use these to ORDER, never to FILTER —
913
+ // so a skewed occurredAt can never drop the live row to null.
914
+ const orderKey = (e: MeshWorkQueueEntry) => e.dispatchTimestamp ?? e.updatedAt ?? '';
915
+ const byDispatchDesc = [...entries].sort((a, b) => orderKey(b).localeCompare(orderKey(a)));
916
+ if (occurredAtIso) {
917
+ const atOrBefore = byDispatchDesc.find(e => orderKey(e) <= occurredAtIso);
918
+ if (atOrBefore) return atOrBefore;
919
+ }
920
+ // Skew made every dispatch later than occurredAt — fall back to the
921
+ // most-recently dispatched row rather than stranding the completion.
922
+ return byDispatchDesc[0];
923
+ }
924
+
925
+ private toRow(entry: MeshWorkQueueEntry): Record<string, unknown> {
926
+ return {
927
+ id: entry.id,
928
+ meshId: entry.meshId,
929
+ status: entry.status,
930
+ targetNodeId: entry.targetNodeId ?? null,
931
+ targetSessionId: entry.targetSessionId ?? null,
932
+ assignedNodeId: entry.assignedNodeId ?? null,
933
+ assignedSessionId: entry.assignedSessionId ?? null,
934
+ createdAt: entry.createdAt,
935
+ updatedAt: entry.updatedAt,
936
+ payload: JSON.stringify(entry),
937
+ };
938
+ }
939
+
940
+ // ── Direct Dispatch Tracking ─────────────────────────────────────────────
941
+
942
+ insertDirectDispatch(entry: {
943
+ taskId: string;
944
+ meshId: string;
945
+ nodeId?: string;
946
+ sessionId?: string;
947
+ providerType?: string;
948
+ message: string;
949
+ taskMode?: string;
950
+ via: string;
951
+ dispatchedToIdleSession?: boolean;
952
+ dispatchedAt: string;
953
+ }): void {
954
+ const now = new Date().toISOString();
955
+ this.db.prepare(`
956
+ INSERT OR REPLACE INTO mesh_direct_dispatches
957
+ (task_id, mesh_id, node_id, session_id, provider_type, message, task_mode, via,
958
+ status, dispatched_to_idle_session, dispatched_at, updated_at)
959
+ VALUES
960
+ (@taskId, @meshId, @nodeId, @sessionId, @providerType, @message, @taskMode, @via,
961
+ 'dispatched', @dispatchedToIdle, @dispatchedAt, @updatedAt)
962
+ `).run({
963
+ taskId: entry.taskId,
964
+ meshId: entry.meshId,
965
+ nodeId: entry.nodeId ?? null,
966
+ sessionId: entry.sessionId ?? null,
967
+ providerType: entry.providerType ?? null,
968
+ message: entry.message,
969
+ taskMode: entry.taskMode ?? null,
970
+ via: entry.via,
971
+ dispatchedToIdle: entry.dispatchedToIdleSession ? 1 : 0,
972
+ dispatchedAt: entry.dispatchedAt,
973
+ updatedAt: now,
974
+ });
975
+ }
976
+
977
+ getActiveDirectDispatches(meshId: string): Array<{
978
+ taskId: string;
979
+ meshId: string;
980
+ nodeId: string | null;
981
+ sessionId: string | null;
982
+ providerType: string | null;
983
+ message: string;
984
+ taskMode: string | null;
985
+ via: string;
986
+ status: string;
987
+ dispatchedToIdleSession: boolean;
988
+ dispatchedAt: string;
989
+ updatedAt: string;
990
+ }> {
991
+ const rows = this.db.prepare(`
992
+ SELECT task_id, mesh_id, node_id, session_id, provider_type, message, task_mode, via,
993
+ status, dispatched_to_idle_session, dispatched_at, updated_at
994
+ FROM mesh_direct_dispatches
995
+ WHERE mesh_id = ? AND status NOT IN ('completed', 'failed', 'stale')
996
+ ORDER BY dispatched_at ASC
997
+ `).all(meshId) as Array<Record<string, unknown>>;
998
+ return rows.map(r => ({
999
+ taskId: r.task_id as string,
1000
+ meshId: r.mesh_id as string,
1001
+ nodeId: r.node_id as string | null,
1002
+ sessionId: r.session_id as string | null,
1003
+ providerType: r.provider_type as string | null,
1004
+ message: r.message as string,
1005
+ taskMode: r.task_mode as string | null,
1006
+ via: r.via as string,
1007
+ status: r.status as string,
1008
+ dispatchedToIdleSession: (r.dispatched_to_idle_session as number) === 1,
1009
+ dispatchedAt: r.dispatched_at as string,
1010
+ updatedAt: r.updated_at as string,
1011
+ }));
1012
+ }
1013
+
1014
+ // CANON-B (dispatch identity): mesh_direct_dispatches is keyed by task_id (PK), but a
1015
+ // single session can host several sequential direct dispatches (re-dispatch / nudge), so
1016
+ // matching a status flip by session_id alone hits EVERY non-terminal row for that session
1017
+ // — flipping a sibling task's row and stranding the one whose event actually fired (the
1018
+ // assigned-stranded watchdog then requeues a task that is really still generating). When
1019
+ // the firing event carries a taskId, target the single PK row; the session_id match is the
1020
+ // legacy fallback only for events that arrive without a taskId.
1021
+ updateDirectDispatchStatus(meshId: string, sessionId: string, status: 'acked' | 'completed' | 'failed' | 'stale', taskId?: string): void {
1022
+ const now = new Date().toISOString();
1023
+ if (taskId) {
1024
+ this.db.prepare(`
1025
+ UPDATE mesh_direct_dispatches
1026
+ SET status = @status, updated_at = @updatedAt
1027
+ WHERE mesh_id = @meshId AND task_id = @taskId
1028
+ AND status NOT IN ('completed', 'failed')
1029
+ `).run({ status, meshId, taskId, updatedAt: now });
1030
+ return;
1031
+ }
1032
+ if (!sessionId) return; // never update rows without a session binding
1033
+ this.db.prepare(`
1034
+ UPDATE mesh_direct_dispatches
1035
+ SET status = @status, updated_at = @updatedAt
1036
+ WHERE mesh_id = @meshId AND session_id = @sessionId
1037
+ AND session_id IS NOT NULL
1038
+ AND status NOT IN ('completed', 'failed')
1039
+ `).run({ status, meshId, sessionId, updatedAt: now });
1040
+ }
1041
+
1042
+ /**
1043
+ * MESH-DISPATCH-MISROUTE (fix 3, consumer residual): resolve the task_id of the SINGLE
1044
+ * non-terminal direct dispatch a session owns. Returns the task_id only when the session
1045
+ * holds exactly ONE active ('dispatched'/'acked') row — the case where a taskId-less
1046
+ * lifecycle event (a legacy/relayed worker whose producer never stamped meshActiveTaskId)
1047
+ * unambiguously belongs to that one dispatch. With zero rows there is nothing to ack; with
1048
+ * two or more (a re-dispatch/nudge sibling) the firing event's owner is ambiguous, so we
1049
+ * return null and the caller MUST NOT fall back to the session_id sweep that would flip a
1050
+ * sibling row ("may flip a sibling dispatch row"). This narrows the legacy fallback to the
1051
+ * only safe case instead of removing the producer-side TASKIDLESS stamp's safety net.
1052
+ */
1053
+ getSoleActiveDirectDispatchTaskId(meshId: string, sessionId: string): string | null {
1054
+ if (!sessionId) return null;
1055
+ const rows = this.db.prepare(`
1056
+ SELECT task_id FROM mesh_direct_dispatches
1057
+ WHERE mesh_id = ? AND session_id = ?
1058
+ AND status NOT IN ('completed', 'failed', 'stale')
1059
+ `).all(meshId, sessionId) as Array<{ task_id: string }>;
1060
+ if (rows.length !== 1) return null;
1061
+ const taskId = typeof rows[0]?.task_id === 'string' ? rows[0].task_id.trim() : '';
1062
+ return taskId || null;
1063
+ }
1064
+
1065
+ cleanupTerminalDirectDispatches(olderThanMs: number): void {
1066
+ const cutoff = new Date(Date.now() - olderThanMs).toISOString();
1067
+ this.db.prepare(`
1068
+ DELETE FROM mesh_direct_dispatches
1069
+ WHERE status IN ('completed', 'failed', 'stale') AND updated_at < ?
1070
+ `).run(cutoff);
1071
+ }
1072
+
1073
+ deleteDirectDispatches(meshId: string): void {
1074
+ this.db.prepare(`DELETE FROM mesh_direct_dispatches WHERE mesh_id = ?`).run(meshId);
1075
+ }
1076
+
1077
+ /**
1078
+ * Delete specific direct dispatch rows by taskId for a mesh. Used by the staleDirect prune
1079
+ * path to remove orphaned/terminal dispatch records whose node/session is no longer in the
1080
+ * live mesh. Returns the number of rows actually deleted. No-op for an empty taskId list.
1081
+ */
1082
+ deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
1083
+ const ids = (taskIds || []).map(id => typeof id === 'string' ? id.trim() : '').filter(Boolean);
1084
+ if (!ids.length) return 0;
1085
+ const stmt = this.db.prepare(`DELETE FROM mesh_direct_dispatches WHERE mesh_id = ? AND task_id = ?`);
1086
+ let deleted = 0;
1087
+ const run = this.db.transaction((rows: string[]) => {
1088
+ for (const taskId of rows) {
1089
+ deleted += stmt.run(meshId, taskId).changes;
1090
+ }
1091
+ });
1092
+ run(ids);
1093
+ return deleted;
1094
+ }
1095
+
1096
+ markStaleDirectDispatches(meshId: string, olderThanMs: number): void {
1097
+ const cutoff = new Date(Date.now() - olderThanMs).toISOString();
1098
+ const now = new Date().toISOString();
1099
+ this.db.prepare(`
1100
+ UPDATE mesh_direct_dispatches
1101
+ SET status = 'stale', updated_at = ?
1102
+ WHERE mesh_id = ? AND status = 'dispatched' AND dispatched_at < ?
1103
+ `).run(now, meshId, cutoff);
1104
+ }
1105
+
1106
+ // ── Remote Idle Sessions ─────────────────────────────────────────────────
1107
+
1108
+ setRemoteIdleSession(meshId: string, nodeId: string, sessionId: string, providerType: string, expiresAt: number, metadata?: any): void {
1109
+ this.db.prepare(`
1110
+ INSERT OR REPLACE INTO remote_idle_sessions (mesh_id, node_id, session_id, provider_type, expires_at, metadata)
1111
+ VALUES (?, ?, ?, ?, ?, ?)
1112
+ `).run(meshId, nodeId, sessionId, providerType, expiresAt, metadata ? JSON.stringify(metadata) : null);
1113
+ }
1114
+
1115
+ getRemoteIdleSessions(meshId: string): Array<{ nodeId: string; sessionId: string; providerType: string; expiresAt: number; metadata?: any }> {
1116
+ // MESH-ISOLATION-LEAK: always mesh-scoped. A bare (cross-mesh) read here is what
1117
+ // let mesh B claim mesh A's idle session when both share a nodeId.
1118
+ const rows = this.db.prepare('SELECT node_id, session_id, provider_type, expires_at, metadata FROM remote_idle_sessions WHERE mesh_id = ?').all(meshId) as Array<any>;
1119
+ return rows.map(r => ({
1120
+ nodeId: r.node_id,
1121
+ sessionId: r.session_id,
1122
+ providerType: r.provider_type,
1123
+ expiresAt: r.expires_at,
1124
+ metadata: r.metadata ? JSON.parse(r.metadata) : undefined,
1125
+ }));
1126
+ }
1127
+
1128
+ deleteRemoteIdleSession(meshId: string, nodeId: string, sessionId: string): void {
1129
+ this.db.prepare('DELETE FROM remote_idle_sessions WHERE mesh_id = ? AND node_id = ? AND session_id = ?').run(meshId, nodeId, sessionId);
1130
+ }
1131
+
1132
+ pruneExpiredRemoteIdleSessions(): void {
1133
+ this.db.prepare('DELETE FROM remote_idle_sessions WHERE expires_at <= ?').run(Date.now());
1134
+ }
1135
+
1136
+ // ── Session Delivery Queue ───────────────────────────────────────────────
1137
+
1138
+ insertSessionDelivery(entry: {
1139
+ id: string;
1140
+ meshId: string;
1141
+ nodeId?: string;
1142
+ sessionId?: string;
1143
+ providerType?: string;
1144
+ taskId?: string;
1145
+ kind: string;
1146
+ priority?: number;
1147
+ message: string;
1148
+ status: string;
1149
+ deliverAfter?: string;
1150
+ expiresAt?: string;
1151
+ sourceCoordinatorSessionId?: string;
1152
+ sourceCoordinatorDaemonId?: string;
1153
+ createdAt: string;
1154
+ updatedAt: string;
1155
+ }): void {
1156
+ this.db.prepare(`
1157
+ INSERT OR REPLACE INTO mesh_session_delivery (
1158
+ id, mesh_id, node_id, session_id, provider_type, task_id, kind, priority,
1159
+ message, status, deliver_after, expires_at, attempt_count,
1160
+ source_coordinator_session_id, source_coordinator_daemon_id,
1161
+ last_error, created_at, updated_at
1162
+ ) VALUES (
1163
+ @id, @meshId, @nodeId, @sessionId, @providerType, @taskId, @kind, @priority,
1164
+ @message, @status, @deliverAfter, @expiresAt, 0,
1165
+ @sourceCoordinatorSessionId, @sourceCoordinatorDaemonId,
1166
+ NULL, @createdAt, @updatedAt
1167
+ )
1168
+ `).run({
1169
+ id: entry.id,
1170
+ meshId: entry.meshId,
1171
+ nodeId: entry.nodeId ?? null,
1172
+ sessionId: entry.sessionId ?? null,
1173
+ providerType: entry.providerType ?? null,
1174
+ taskId: entry.taskId ?? null,
1175
+ kind: entry.kind,
1176
+ priority: entry.priority ?? 0,
1177
+ message: entry.message,
1178
+ status: entry.status,
1179
+ deliverAfter: entry.deliverAfter ?? null,
1180
+ expiresAt: entry.expiresAt ?? null,
1181
+ sourceCoordinatorSessionId: entry.sourceCoordinatorSessionId ?? null,
1182
+ sourceCoordinatorDaemonId: entry.sourceCoordinatorDaemonId ?? null,
1183
+ createdAt: entry.createdAt,
1184
+ updatedAt: entry.updatedAt,
1185
+ });
1186
+ this.maybeCheckpointWal();
1187
+ }
1188
+
1189
+ updateSessionDeliveryStatus(id: string, status: string, opts?: { lastError?: string; incrementAttempt?: boolean }): void {
1190
+ const now = new Date().toISOString();
1191
+ if (opts?.incrementAttempt) {
1192
+ this.db.prepare(`
1193
+ UPDATE mesh_session_delivery
1194
+ SET status = @status, last_error = @lastError, attempt_count = attempt_count + 1, updated_at = @updatedAt
1195
+ WHERE id = @id
1196
+ `).run({ id, status, lastError: opts?.lastError ?? null, updatedAt: now });
1197
+ } else {
1198
+ this.db.prepare(`
1199
+ UPDATE mesh_session_delivery
1200
+ SET status = @status, last_error = @lastError, updated_at = @updatedAt
1201
+ WHERE id = @id
1202
+ `).run({ id, status, lastError: opts?.lastError ?? null, updatedAt: now });
1203
+ }
1204
+ }
1205
+
1206
+ getActiveSessionDeliveries(meshId: string, sessionId?: string): Array<{
1207
+ id: string; meshId: string; nodeId: string | null; sessionId: string | null;
1208
+ providerType: string | null; taskId: string | null; kind: string; priority: number;
1209
+ message: string; status: string; deliverAfter: string | null; expiresAt: string | null;
1210
+ attemptCount: number; sourceCoordinatorSessionId: string | null;
1211
+ sourceCoordinatorDaemonId: string | null; lastError: string | null;
1212
+ createdAt: string; updatedAt: string;
1213
+ }> {
1214
+ const now = new Date().toISOString();
1215
+ const sql = sessionId
1216
+ ? `SELECT * FROM mesh_session_delivery WHERE mesh_id = ? AND session_id = ? AND status NOT IN ('delivered','completed','failed','expired','cancelled') AND (expires_at IS NULL OR expires_at > ?) ORDER BY priority DESC, created_at ASC`
1217
+ : `SELECT * FROM mesh_session_delivery WHERE mesh_id = ? AND status NOT IN ('delivered','completed','failed','expired','cancelled') AND (expires_at IS NULL OR expires_at > ?) ORDER BY priority DESC, created_at ASC`;
1218
+ const rows = sessionId
1219
+ ? this.db.prepare(sql).all(meshId, sessionId, now) as Array<Record<string, unknown>>
1220
+ : this.db.prepare(sql).all(meshId, now) as Array<Record<string, unknown>>;
1221
+ return rows.map(r => ({
1222
+ id: r.id as string,
1223
+ meshId: r.mesh_id as string,
1224
+ nodeId: r.node_id as string | null,
1225
+ sessionId: r.session_id as string | null,
1226
+ providerType: r.provider_type as string | null,
1227
+ taskId: r.task_id as string | null,
1228
+ kind: r.kind as string,
1229
+ priority: r.priority as number,
1230
+ message: r.message as string,
1231
+ status: r.status as string,
1232
+ deliverAfter: r.deliver_after as string | null,
1233
+ expiresAt: r.expires_at as string | null,
1234
+ attemptCount: r.attempt_count as number,
1235
+ sourceCoordinatorSessionId: r.source_coordinator_session_id as string | null,
1236
+ sourceCoordinatorDaemonId: r.source_coordinator_daemon_id as string | null,
1237
+ lastError: r.last_error as string | null,
1238
+ createdAt: r.created_at as string,
1239
+ updatedAt: r.updated_at as string,
1240
+ }));
1241
+ }
1242
+
1243
+ /**
1244
+ * Bug B watchdog support: true when at least one delivery record for the task has
1245
+ * reached a confirmed-handed-off status (delivered / acked / completed). The
1246
+ * assigned-stranded watchdog uses this to distinguish a dispatch that was never
1247
+ * confirmed (reclaimable) from one that WAS handed to the worker (a genuinely
1248
+ * in-flight or completion-lost task, which is PHASE 4's responsibility, not this
1249
+ * watchdog's). Indexed by (mesh_id, task_id).
1250
+ */
1251
+ taskHasConfirmedDelivery(meshId: string, taskId: string): boolean {
1252
+ const row = this.db.prepare(`
1253
+ SELECT 1 FROM mesh_session_delivery
1254
+ WHERE mesh_id = ? AND task_id = ? AND status IN ('delivered','acked','completed')
1255
+ LIMIT 1
1256
+ `).get(meshId, taskId) as { 1: number } | undefined;
1257
+ return !!row;
1258
+ }
1259
+
1260
+ expireStaleSessionDeliveries(meshId: string): void {
1261
+ const now = new Date().toISOString();
1262
+ this.db.prepare(`
1263
+ UPDATE mesh_session_delivery
1264
+ SET status = 'expired', updated_at = ?
1265
+ WHERE mesh_id = ? AND expires_at IS NOT NULL AND expires_at <= ?
1266
+ AND status NOT IN ('delivered','completed','failed','expired','cancelled')
1267
+ `).run(now, meshId, now);
1268
+ }
1269
+
1270
+ deleteSessionDeliveries(meshId: string): void {
1271
+ this.db.prepare('DELETE FROM mesh_session_delivery WHERE mesh_id = ?').run(meshId);
1272
+ }
1273
+
1274
+ // ── Completion Conflict Diagnostics ──────────────────────────────────────
1275
+
1276
+ recordCompletionConflict(entry: {
1277
+ id: string;
1278
+ meshId: string;
1279
+ fingerprint: string;
1280
+ conflictingTaskId?: string;
1281
+ conflictingSessionId?: string;
1282
+ originalTaskId?: string;
1283
+ originalSessionId?: string;
1284
+ event: string;
1285
+ createdAt: string;
1286
+ }): void {
1287
+ this.db.prepare(`
1288
+ INSERT OR IGNORE INTO mesh_completion_conflicts
1289
+ (id, mesh_id, fingerprint, conflicting_task_id, conflicting_session_id,
1290
+ original_task_id, original_session_id, event, created_at)
1291
+ VALUES (@id, @meshId, @fingerprint, @conflictingTaskId, @conflictingSessionId,
1292
+ @originalTaskId, @originalSessionId, @event, @createdAt)
1293
+ `).run({
1294
+ id: entry.id,
1295
+ meshId: entry.meshId,
1296
+ fingerprint: entry.fingerprint,
1297
+ conflictingTaskId: entry.conflictingTaskId ?? null,
1298
+ conflictingSessionId: entry.conflictingSessionId ?? null,
1299
+ originalTaskId: entry.originalTaskId ?? null,
1300
+ originalSessionId: entry.originalSessionId ?? null,
1301
+ event: entry.event,
1302
+ createdAt: entry.createdAt,
1303
+ });
1304
+ this.maybeCheckpointWal();
1305
+ }
1306
+
1307
+ getRecentCompletionConflicts(meshId: string, limitMs: number = 60 * 60 * 1000): Array<{
1308
+ id: string; meshId: string; fingerprint: string; conflictingTaskId: string | null;
1309
+ conflictingSessionId: string | null; originalTaskId: string | null;
1310
+ originalSessionId: string | null; event: string; createdAt: string;
1311
+ }> {
1312
+ const cutoff = new Date(Date.now() - limitMs).toISOString();
1313
+ const rows = this.db.prepare(
1314
+ 'SELECT * FROM mesh_completion_conflicts WHERE mesh_id = ? AND created_at >= ? ORDER BY created_at DESC LIMIT 50'
1315
+ ).all(meshId, cutoff) as Array<Record<string, unknown>>;
1316
+ return rows.map(r => ({
1317
+ id: r.id as string,
1318
+ meshId: r.mesh_id as string,
1319
+ fingerprint: r.fingerprint as string,
1320
+ conflictingTaskId: r.conflicting_task_id as string | null,
1321
+ conflictingSessionId: r.conflicting_session_id as string | null,
1322
+ originalTaskId: r.original_task_id as string | null,
1323
+ originalSessionId: r.original_session_id as string | null,
1324
+ event: r.event as string,
1325
+ createdAt: r.created_at as string,
1326
+ }));
1327
+ }
1328
+
1329
+ /**
1330
+ * Record a mesh tool call and check whether this mesh+tool combination is
1331
+ * being called too rapidly (sliding window rate guard).
1332
+ *
1333
+ * Returns a rate-limit advisory string when the call rate is too high, null otherwise.
1334
+ * windowMs: sliding window size in ms (default 10s)
1335
+ * maxCalls: max allowed calls within the window (default 5)
1336
+ */
1337
+ recordMeshToolCall(opts: {
1338
+ meshId: string;
1339
+ tool: string;
1340
+ sessionId?: string | null;
1341
+ windowMs?: number;
1342
+ maxCalls?: number;
1343
+ }): { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null } {
1344
+ const { meshId, tool, sessionId = null } = opts;
1345
+ const windowMs = opts.windowMs ?? 10_000;
1346
+ const maxCalls = opts.maxCalls ?? 5;
1347
+ const now = Date.now();
1348
+ const windowStart = now - windowMs;
1349
+
1350
+ this.db.prepare(
1351
+ 'INSERT INTO mesh_tool_call_log (mesh_id, tool, session_id, called_at) VALUES (?, ?, ?, ?)'
1352
+ ).run(meshId, tool, sessionId, now);
1353
+
1354
+ const row = this.db.prepare(
1355
+ 'SELECT COUNT(*) as cnt FROM mesh_tool_call_log WHERE mesh_id = ? AND tool = ? AND called_at >= ?'
1356
+ ).get(meshId, tool, windowStart) as { cnt: number };
1357
+ const callsInWindow = row?.cnt ?? 0;
1358
+
1359
+ // Sweep old entries periodically to keep the table lean (every 200 calls across all tools).
1360
+ if (++this.toolCallLogCounter % 200 === 0) {
1361
+ this.db.prepare(
1362
+ 'DELETE FROM mesh_tool_call_log WHERE called_at < ?'
1363
+ ).run(now - Math.max(windowMs * 10, 60_000));
1364
+ }
1365
+
1366
+ if (callsInWindow > maxCalls) {
1367
+ const advisory = `Rate limit: ${tool} called ${callsInWindow} times in the last ${windowMs / 1000}s for mesh ${meshId}. `
1368
+ + `Wait for pendingCoordinatorEvents or an explicit user status request before calling again.`;
1369
+ return { rateLimitExceeded: true, callsInWindow, advisory };
1370
+ }
1371
+ return { rateLimitExceeded: false, callsInWindow, advisory: null };
1372
+ }
1373
+
1374
+ /**
1375
+ * Prune tool call log entries older than the given age in ms.
1376
+ * Exposed for testing.
1377
+ */
1378
+ pruneToolCallLog(olderThanMs: number): void {
1379
+ this.db.prepare('DELETE FROM mesh_tool_call_log WHERE called_at < ?').run(Date.now() - olderThanMs);
1380
+ }
1381
+
1382
+ // ── G2: Event Ledger ────────────────────────────────────────────────────
1383
+
1384
+ appendLedgerEntry(entry: {
1385
+ id: string;
1386
+ meshId: string;
1387
+ timestamp: string;
1388
+ kind: string;
1389
+ nodeId?: string | null;
1390
+ sessionId?: string | null;
1391
+ providerType?: string | null;
1392
+ payload?: unknown;
1393
+ }): void {
1394
+ this.db.prepare(
1395
+ `INSERT OR IGNORE INTO mesh_event_ledger
1396
+ (id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
1397
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
1398
+ ).run(
1399
+ entry.id,
1400
+ entry.meshId,
1401
+ entry.timestamp,
1402
+ entry.kind,
1403
+ entry.nodeId ?? null,
1404
+ entry.sessionId ?? null,
1405
+ entry.providerType ?? null,
1406
+ JSON.stringify(entry.payload ?? {}),
1407
+ );
1408
+ this.maybeCheckpointWal();
1409
+ }
1410
+
1411
+ readLedgerEntries(meshId: string, opts?: {
1412
+ tail?: number;
1413
+ since?: string;
1414
+ kind?: string;
1415
+ limit?: number;
1416
+ }): Array<{ id: string; meshId: string; timestamp: string; kind: string; nodeId: string | null; sessionId: string | null; providerType: string | null; payload: unknown }> {
1417
+ const limit = opts?.tail ?? opts?.limit ?? 200;
1418
+ let query: string;
1419
+ const params: unknown[] = [meshId];
1420
+ if (opts?.kind && opts?.since) {
1421
+ query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND kind = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?`;
1422
+ params.push(opts.kind, opts.since, limit);
1423
+ } else if (opts?.kind) {
1424
+ query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND kind = ? ORDER BY timestamp DESC LIMIT ?`;
1425
+ params.push(opts.kind, limit);
1426
+ } else if (opts?.since) {
1427
+ query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? AND timestamp >= ? ORDER BY timestamp DESC LIMIT ?`;
1428
+ params.push(opts.since, limit);
1429
+ } else {
1430
+ query = `SELECT * FROM mesh_event_ledger WHERE mesh_id = ? ORDER BY timestamp DESC LIMIT ?`;
1431
+ params.push(limit);
1432
+ }
1433
+ const rows = this.db.prepare(query).all(...params) as Array<Record<string, unknown>>;
1434
+ return rows.map(r => ({
1435
+ id: r.id as string,
1436
+ meshId: r.mesh_id as string,
1437
+ timestamp: r.timestamp as string,
1438
+ kind: r.kind as string,
1439
+ nodeId: r.node_id as string | null,
1440
+ sessionId: r.session_id as string | null,
1441
+ providerType: r.provider_type as string | null,
1442
+ payload: (() => { try { return JSON.parse(r.payload as string); } catch { return {}; } })(),
1443
+ }));
1444
+ }
1445
+
1446
+ /**
1447
+ * G2 read cutover: read ledger entries in append order (oldest first),
1448
+ * matching legacy JSONL file-order semantics. Ties on the same timestamp
1449
+ * are broken by rowid (insertion order), preserving the positional
1450
+ * guarantee that mesh-events relies on for same-millisecond entries.
1451
+ */
1452
+ readLedgerEntriesOrdered(meshId: string, opts?: {
1453
+ since?: string;
1454
+ kinds?: string[];
1455
+ tail?: number;
1456
+ }): Array<{ id: string; meshId: string; timestamp: string; kind: string; nodeId: string | null; sessionId: string | null; providerType: string | null; payload: unknown }> {
1457
+ const params: unknown[] = [meshId];
1458
+ let whereClause = 'mesh_id = ?';
1459
+ if (opts?.since) {
1460
+ whereClause += ' AND timestamp >= ?';
1461
+ params.push(opts.since);
1462
+ }
1463
+ const kinds = Array.isArray(opts?.kinds) ? opts.kinds.filter(k => typeof k === 'string' && k.trim()) : [];
1464
+ if (kinds.length > 0) {
1465
+ whereClause += ` AND kind IN (${kinds.map(() => '?').join(', ')})`;
1466
+ params.push(...kinds);
1467
+ }
1468
+ let query: string;
1469
+ if (opts?.tail && opts.tail > 0) {
1470
+ // Tail: newest N in append order — inner DESC limit, outer re-sort ASC.
1471
+ query = `SELECT * FROM (
1472
+ SELECT rowid AS rid, * FROM mesh_event_ledger WHERE ${whereClause}
1473
+ ORDER BY timestamp DESC, rowid DESC LIMIT ?
1474
+ ) ORDER BY timestamp ASC, rid ASC`;
1475
+ params.push(Math.floor(opts.tail));
1476
+ } else {
1477
+ query = `SELECT rowid AS rid, * FROM mesh_event_ledger WHERE ${whereClause} ORDER BY timestamp ASC, rowid ASC`;
1478
+ }
1479
+ const rows = this.db.prepare(query).all(...params) as Array<Record<string, unknown>>;
1480
+ return rows.map(r => ({
1481
+ id: r.id as string,
1482
+ meshId: r.mesh_id as string,
1483
+ timestamp: r.timestamp as string,
1484
+ kind: r.kind as string,
1485
+ nodeId: r.node_id as string | null,
1486
+ sessionId: r.session_id as string | null,
1487
+ providerType: r.provider_type as string | null,
1488
+ payload: (() => { try { return JSON.parse(r.payload as string); } catch { return {}; } })(),
1489
+ }));
1490
+ }
1491
+
1492
+ /** Remove all ledger entries for a mesh (mesh deletion / test cleanup). */
1493
+ clearLedgerForMesh(meshId: string): number {
1494
+ return this.db.prepare('DELETE FROM mesh_event_ledger WHERE mesh_id = ?').run(meshId).changes;
1495
+ }
1496
+
1497
+ /** G2: remove entries moved to the JSONL archive so the SQLite runtime set mirrors the active ledger. */
1498
+ deleteLedgerEntries(meshId: string, ids: string[]): number {
1499
+ if (!ids.length) return 0;
1500
+ let deleted = 0;
1501
+ const stmt = this.db.prepare('DELETE FROM mesh_event_ledger WHERE mesh_id = ? AND id = ?');
1502
+ this.db.transaction(() => {
1503
+ for (const id of ids) {
1504
+ deleted += stmt.run(meshId, id).changes;
1505
+ }
1506
+ })();
1507
+ return deleted;
1508
+ }
1509
+
1510
+ hasLedgerEntry(meshId: string, id: string): boolean {
1511
+ const row = this.db.prepare(
1512
+ 'SELECT 1 FROM mesh_event_ledger WHERE mesh_id = ? AND id = ? LIMIT 1'
1513
+ ).get(meshId, id);
1514
+ return row !== undefined;
1515
+ }
1516
+
1517
+ ledgerEntryCount(meshId: string): number {
1518
+ const row = this.db.prepare(
1519
+ 'SELECT COUNT(*) as cnt FROM mesh_event_ledger WHERE mesh_id = ?'
1520
+ ).get(meshId) as { cnt: number } | undefined;
1521
+ return row?.cnt ?? 0;
1522
+ }
1523
+
1524
+ importLedgerEntries(entries: Array<{
1525
+ id: string; meshId: string; timestamp: string; kind: string;
1526
+ nodeId?: string | null; sessionId?: string | null; providerType?: string | null; payload?: unknown;
1527
+ }>): number {
1528
+ let imported = 0;
1529
+ const stmt = this.db.prepare(
1530
+ `INSERT OR IGNORE INTO mesh_event_ledger
1531
+ (id, mesh_id, timestamp, kind, node_id, session_id, provider_type, payload)
1532
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
1533
+ );
1534
+ this.db.transaction(() => {
1535
+ for (const e of entries) {
1536
+ const result = stmt.run(
1537
+ e.id, e.meshId, e.timestamp, e.kind,
1538
+ e.nodeId ?? null, e.sessionId ?? null, e.providerType ?? null,
1539
+ JSON.stringify(e.payload ?? {}),
1540
+ );
1541
+ if (result.changes > 0) imported++;
1542
+ }
1543
+ })();
1544
+ return imported;
1545
+ }
1546
+
1547
+ /**
1548
+ * G4: Read a bounded, cursor-addressable ledger slice directly from the SQLite
1549
+ * mesh_event_ledger table. This is the P2P reconcile read path; JSONL files are
1550
+ * retained as export/import/debug/legacy artifacts only.
1551
+ *
1552
+ * The return shape is structurally compatible with MeshLedgerSlice so callers
1553
+ * in mesh-tools.ts can pass it directly to buildMeshLedgerReplicaEvidence.
1554
+ */
1555
+ readLedgerSlice(meshId: string, opts?: {
1556
+ afterId?: string;
1557
+ since?: string;
1558
+ kind?: string;
1559
+ limit?: number;
1560
+ }): {
1561
+ protocol: 'adhdev.mesh.ledger.slice.v1';
1562
+ meshId: string;
1563
+ entries: Array<{ id: string; meshId: string; timestamp: string; kind: string; nodeId: string | null; sessionId: string | null; providerType: string | null; payload: unknown }>;
1564
+ cursor: { afterId: string | null; nextAfterId: string | null; limit: number; hasMore: boolean };
1565
+ sourceOfTruth: { kind: 'local_sqlite'; table: 'mesh_event_ledger'; bounded: true; maxLimit: number };
1566
+ } {
1567
+ // Protocol maximum of 500, default 100 — mirrors mesh-ledger.ts constants.
1568
+ const MAX_LIMIT = 500;
1569
+ const DEFAULT_LIMIT = 100;
1570
+ const limit = (typeof opts?.limit === 'number' && Number.isFinite(opts.limit))
1571
+ ? Math.max(1, Math.min(MAX_LIMIT, Math.floor(opts.limit)))
1572
+ : DEFAULT_LIMIT;
1573
+
1574
+ const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
1575
+
1576
+ // Build query: fetch limit+1 rows so we can detect hasMore without a COUNT(*).
1577
+ const params: unknown[] = [meshId];
1578
+ let whereClause = 'mesh_id = ?';
1579
+
1580
+ if (opts?.kind) {
1581
+ whereClause += ' AND kind = ?';
1582
+ params.push(opts.kind);
1583
+ }
1584
+ if (opts?.since) {
1585
+ whereClause += ' AND timestamp >= ?';
1586
+ params.push(opts.since);
1587
+ }
1588
+ if (afterId) {
1589
+ // afterId: return entries with timestamp strictly after the referenced entry's timestamp,
1590
+ // or with the same timestamp but id > afterId (stable pagination).
1591
+ whereClause += ` AND (timestamp > (SELECT timestamp FROM mesh_event_ledger WHERE id = ? AND mesh_id = ?) OR (timestamp = (SELECT timestamp FROM mesh_event_ledger WHERE id = ? AND mesh_id = ?) AND id > ?))`;
1592
+ params.push(afterId, meshId, afterId, meshId, afterId);
1593
+ }
1594
+
1595
+ // Fetch limit+1 to detect hasMore
1596
+ const query = `SELECT * FROM mesh_event_ledger WHERE ${whereClause} ORDER BY timestamp ASC, id ASC LIMIT ?`;
1597
+ params.push(limit + 1);
1598
+
1599
+ const rows = this.db.prepare(query).all(...params) as Array<Record<string, unknown>>;
1600
+ const hasMore = rows.length > limit;
1601
+ const bounded = hasMore ? rows.slice(0, limit) : rows;
1602
+
1603
+ const entries = bounded.map(r => ({
1604
+ id: r.id as string,
1605
+ meshId: r.mesh_id as string,
1606
+ timestamp: r.timestamp as string,
1607
+ kind: r.kind as string,
1608
+ nodeId: r.node_id as string | null,
1609
+ sessionId: r.session_id as string | null,
1610
+ providerType: r.provider_type as string | null,
1611
+ payload: (() => { try { return JSON.parse(r.payload as string); } catch { return {}; } })(),
1612
+ }));
1613
+
1614
+ return {
1615
+ protocol: 'adhdev.mesh.ledger.slice.v1',
1616
+ meshId,
1617
+ entries,
1618
+ cursor: {
1619
+ afterId,
1620
+ nextAfterId: entries.length ? entries[entries.length - 1].id : afterId,
1621
+ limit,
1622
+ hasMore,
1623
+ },
1624
+ sourceOfTruth: {
1625
+ kind: 'local_sqlite',
1626
+ table: 'mesh_event_ledger',
1627
+ bounded: true,
1628
+ maxLimit: MAX_LIMIT,
1629
+ },
1630
+ };
1631
+ }
1632
+
1633
+ // ── G3: Pending Coordinator Events ──────────────────────────────────────
1634
+
1635
+ insertPendingEvent(event: {
1636
+ id: string;
1637
+ meshId: string;
1638
+ coordinatorDaemonId?: string | null;
1639
+ event: string;
1640
+ payload?: unknown;
1641
+ fingerprint?: string | null;
1642
+ queuedAt: number;
1643
+ }): boolean {
1644
+ const result = this.db.prepare(
1645
+ `INSERT OR IGNORE INTO mesh_pending_events
1646
+ (id, mesh_id, coordinator_daemon_id, event, payload, fingerprint, queued_at)
1647
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
1648
+ ).run(
1649
+ event.id,
1650
+ event.meshId,
1651
+ event.coordinatorDaemonId ?? null,
1652
+ event.event,
1653
+ JSON.stringify(event.payload ?? {}),
1654
+ event.fingerprint ?? null,
1655
+ event.queuedAt,
1656
+ );
1657
+ this.maybeCheckpointWal();
1658
+ return result.changes > 0;
1659
+ }
1660
+
1661
+ /**
1662
+ * Drain undrained pending events for a mesh, atomically marking them drained.
1663
+ * When `opts.onlyEvents` is supplied, ONLY rows whose `event` is in that set are
1664
+ * drained — the rest stay queued (drained=0) for a later drain. This is how the
1665
+ * reconcile loop force-drains terminal/force-inject events into a *generating*
1666
+ * coordinator while leaving non-force progress events for the coordinator's next
1667
+ * idle transition. Filtering happens inside the same transaction as the
1668
+ * drained=1 marking, so force-drain + a concurrent full drain can never both
1669
+ * consume the same row.
1670
+ */
1671
+ drainPendingEvents(
1672
+ meshId: string,
1673
+ coordinatorDaemonId?: string | null | ReadonlyArray<string>,
1674
+ opts?: { onlyEvents?: ReadonlySet<string> },
1675
+ ): Array<{ id: string; event: string; payload: unknown }> {
1676
+ return this.transaction(() => {
1677
+ const onlyEvents = opts?.onlyEvents;
1678
+ // An explicit-but-empty filter means "drain nothing" (no event name can match).
1679
+ if (onlyEvents && onlyEvents.size === 0) return [];
1680
+ const eventList = onlyEvents ? [...onlyEvents] : [];
1681
+ // A coordinator daemon can answer to more than one id form: its canonical
1682
+ // status id (e.g. `standalone_<machineId>` / `daemon_<machineId>`, which the
1683
+ // MCP layer stamps via ctx.localDaemonId) AND the bare machineId (stamped by
1684
+ // the local queue-assignment path). Accept ANY of them so a unicast event
1685
+ // stamped with either id is drained here. Unscoped (NULL) rows always match.
1686
+ const daemonIds = (Array.isArray(coordinatorDaemonId)
1687
+ ? coordinatorDaemonId
1688
+ : coordinatorDaemonId ? [coordinatorDaemonId] : [])
1689
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
1690
+ // Filter by event name IN-SQL when onlyEvents is set so the LIMIT applies to
1691
+ // matching rows — a long run of non-force events ahead in the queue must not
1692
+ // crowd a force event out of the 100-row window.
1693
+ const clauses = ['mesh_id = ?', 'drained = 0'];
1694
+ const params: unknown[] = [meshId];
1695
+ if (daemonIds.length > 0) {
1696
+ clauses.push(`(coordinator_daemon_id IS NULL OR coordinator_daemon_id IN (${daemonIds.map(() => '?').join(',')}))`);
1697
+ params.push(...daemonIds);
1698
+ }
1699
+ if (eventList.length > 0) {
1700
+ clauses.push(`event IN (${eventList.map(() => '?').join(',')})`);
1701
+ params.push(...eventList);
1702
+ }
1703
+ const rows = this.db.prepare(
1704
+ `SELECT id, event, payload FROM mesh_pending_events WHERE ${clauses.join(' AND ')} ORDER BY queued_at ASC LIMIT 100`
1705
+ ).all(...params) as Array<{ id: string; event: string; payload: string }>;
1706
+ if (rows.length === 0) return [];
1707
+ const ids = rows.map(r => r.id);
1708
+ const now = Date.now();
1709
+ this.db.prepare(
1710
+ `UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE id IN (${ids.map(() => '?').join(',')})`
1711
+ ).run(now, ...ids);
1712
+ return rows.map(r => ({
1713
+ id: r.id,
1714
+ event: r.event,
1715
+ payload: (() => { try { return JSON.parse(r.payload); } catch { return {}; } })(),
1716
+ }));
1717
+ });
1718
+ }
1719
+
1720
+ /** Non-destructive peek — returns undrained events without marking them drained. */
1721
+ peekPendingEvents(meshId: string, coordinatorDaemonId?: string | null | ReadonlyArray<string>): Array<{ id: string; event: string; payload: unknown }> {
1722
+ const daemonIds = (Array.isArray(coordinatorDaemonId)
1723
+ ? coordinatorDaemonId
1724
+ : coordinatorDaemonId ? [coordinatorDaemonId] : [])
1725
+ .filter((id): id is string => typeof id === 'string' && id.length > 0);
1726
+ const whereClause = daemonIds.length > 0
1727
+ ? `WHERE mesh_id = ? AND drained = 0 AND (coordinator_daemon_id IS NULL OR coordinator_daemon_id IN (${daemonIds.map(() => '?').join(',')}))`
1728
+ : `WHERE mesh_id = ? AND drained = 0`;
1729
+ const params: unknown[] = daemonIds.length > 0 ? [meshId, ...daemonIds] : [meshId];
1730
+ const rows = this.db.prepare(
1731
+ `SELECT id, event, payload FROM mesh_pending_events ${whereClause} ORDER BY queued_at ASC LIMIT 100`
1732
+ ).all(...params) as Array<{ id: string; event: string; payload: string }>;
1733
+ return rows.map(r => ({
1734
+ id: r.id,
1735
+ event: r.event,
1736
+ payload: (() => { try { return JSON.parse(r.payload); } catch { return {}; } })(),
1737
+ }));
1738
+ }
1739
+
1740
+ hasPendingEventFingerprint(meshId: string, fingerprint: string): boolean {
1741
+ const row = this.db.prepare(
1742
+ 'SELECT 1 FROM mesh_pending_events WHERE mesh_id = ? AND fingerprint = ? AND drained = 0 LIMIT 1'
1743
+ ).get(meshId, fingerprint);
1744
+ return row !== undefined;
1745
+ }
1746
+
1747
+ // ── M3: Mission Records ─────────────────────────────────────────────────
1748
+
1749
+ upsertMission(mission: {
1750
+ id: string;
1751
+ meshId: string;
1752
+ title: string;
1753
+ goal?: string;
1754
+ status?: string;
1755
+ source?: string;
1756
+ }): void {
1757
+ const now = new Date().toISOString();
1758
+ // `source` is a write-once provenance tag: on conflict we only overwrite it
1759
+ // with a non-null incoming value (COALESCE(excluded, existing)), so a later
1760
+ // status/goal upsert that omits source never clears a previously-stamped
1761
+ // 'magi'/'coordinator' tag.
1762
+ this.db.prepare(
1763
+ `INSERT INTO mesh_missions (id, mesh_id, title, goal, status, source, created_at, updated_at)
1764
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
1765
+ ON CONFLICT(id) DO UPDATE SET
1766
+ title = excluded.title,
1767
+ goal = excluded.goal,
1768
+ status = excluded.status,
1769
+ source = COALESCE(excluded.source, mesh_missions.source),
1770
+ updated_at = excluded.updated_at`
1771
+ ).run(
1772
+ mission.id,
1773
+ mission.meshId,
1774
+ mission.title,
1775
+ mission.goal ?? '',
1776
+ mission.status ?? 'active',
1777
+ mission.source ?? null,
1778
+ now,
1779
+ now,
1780
+ );
1781
+ this.maybeCheckpointWal();
1782
+ }
1783
+
1784
+ getMission(meshId: string, missionId: string): { id: string; meshId: string; title: string; goal: string; status: string; source?: string; createdAt: string; updatedAt: string } | null {
1785
+ const row = this.db.prepare(
1786
+ 'SELECT * FROM mesh_missions WHERE mesh_id = ? AND id = ?'
1787
+ ).get(meshId, missionId) as Record<string, string> | undefined;
1788
+ if (!row) return null;
1789
+ return { id: row.id, meshId: row.mesh_id, title: row.title, goal: row.goal, status: row.status, source: row.source ?? undefined, createdAt: row.created_at, updatedAt: row.updated_at };
1790
+ }
1791
+
1792
+ getMissions(meshId: string, statuses?: string[]): Array<{ id: string; meshId: string; title: string; goal: string; status: string; source?: string; createdAt: string; updatedAt: string }> {
1793
+ let rows: Array<Record<string, string>>;
1794
+ if (statuses?.length) {
1795
+ const placeholders = statuses.map(() => '?').join(', ');
1796
+ rows = this.db.prepare(
1797
+ `SELECT * FROM mesh_missions WHERE mesh_id = ? AND status IN (${placeholders}) ORDER BY updated_at DESC`
1798
+ ).all(meshId, ...statuses) as Array<Record<string, string>>;
1799
+ } else {
1800
+ rows = this.db.prepare(
1801
+ 'SELECT * FROM mesh_missions WHERE mesh_id = ? ORDER BY updated_at DESC'
1802
+ ).all(meshId) as Array<Record<string, string>>;
1803
+ }
1804
+ return rows.map(row => ({ id: row.id, meshId: row.mesh_id, title: row.title, goal: row.goal, status: row.status, source: row.source ?? undefined, createdAt: row.created_at, updatedAt: row.updated_at }));
1805
+ }
1806
+
1807
+ /** Remove all missions for a mesh — mesh deletion / test cleanup. */
1808
+ clearMissionsForMesh(meshId: string): number {
1809
+ return this.db.prepare('DELETE FROM mesh_missions WHERE mesh_id = ?').run(meshId).changes;
1810
+ }
1811
+
1812
+ /** Remove all pending-event rows (drained included) for a mesh — mesh deletion / test cleanup. */
1813
+ clearPendingEventsForMesh(meshId: string): number {
1814
+ return this.db.prepare('DELETE FROM mesh_pending_events WHERE mesh_id = ?').run(meshId).changes;
1815
+ }
1816
+
1817
+ pendingEventCount(meshId: string): number {
1818
+ const row = this.db.prepare(
1819
+ 'SELECT COUNT(*) as cnt FROM mesh_pending_events WHERE mesh_id = ? AND drained = 0'
1820
+ ).get(meshId) as { cnt: number } | undefined;
1821
+ return row?.cnt ?? 0;
1822
+ }
1823
+
1824
+ /**
1825
+ * Mark specific pending-event rows drained by id (ack). Used by the
1826
+ * unresolved-delegate durable-forward outbox: an event is peeked (not drained)
1827
+ * while its push to the coordinator is unconfirmed, then marked drained ONLY
1828
+ * after the push is acked. A failed push leaves the row undrained so the next
1829
+ * reconcile tick retries it. Returns the number of rows newly marked drained.
1830
+ */
1831
+ markPendingEventsDrainedById(ids: ReadonlyArray<string>): number {
1832
+ const idList = ids.filter((id): id is string => typeof id === 'string' && id.length > 0);
1833
+ if (idList.length === 0) return 0;
1834
+ const now = Date.now();
1835
+ return this.db.prepare(
1836
+ `UPDATE mesh_pending_events SET drained = 1, drained_at = ? WHERE drained = 0 AND id IN (${idList.map(() => '?').join(',')})`
1837
+ ).run(now, ...idList).changes;
1838
+ }
1839
+
1840
+ /**
1841
+ * Hard-delete pending-event rows by id (including the dedup fingerprint history).
1842
+ * Used to expire an unresolved-delegate outbox entry that has exhausted its retry
1843
+ * budget — fully removing it frees the fingerprint so a genuinely new completion
1844
+ * for the same task could be re-queued later. Returns the number of rows deleted.
1845
+ */
1846
+ deletePendingEventsById(ids: ReadonlyArray<string>): number {
1847
+ const idList = ids.filter((id): id is string => typeof id === 'string' && id.length > 0);
1848
+ if (idList.length === 0) return 0;
1849
+ return this.db.prepare(
1850
+ `DELETE FROM mesh_pending_events WHERE id IN (${idList.map(() => '?').join(',')})`
1851
+ ).run(...idList).changes;
1852
+ }
1853
+ }