@adhdev/daemon-core 0.9.82-rc.48 → 0.9.82-rc.481

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