@adhdev/daemon-core 0.9.82-rc.38 → 0.9.82-rc.381

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 (414) 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 +55 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +121 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +63 -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 +14 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +7 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +15 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +60 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +2 -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 +116 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router.d.ts +227 -2
  56. package/dist/commands/upgrade-helper.d.ts +41 -1
  57. package/dist/config/chat-history.d.ts +9 -0
  58. package/dist/config/config.d.ts +5 -0
  59. package/dist/config/mesh-config.d.ts +77 -1
  60. package/dist/daemon/dev-server.d.ts +0 -2
  61. package/dist/detection/ide-detector.d.ts +13 -0
  62. package/dist/detection/win32-ide-version.d.ts +37 -0
  63. package/dist/git/change-impact-config.d.ts +159 -0
  64. package/dist/git/git-commands.d.ts +11 -1
  65. package/dist/git/git-diff.d.ts +6 -0
  66. package/dist/git/git-executor.d.ts +11 -0
  67. package/dist/git/git-status.d.ts +23 -0
  68. package/dist/git/git-types.d.ts +2 -50
  69. package/dist/git/index.d.ts +2 -0
  70. package/dist/index.d.ts +57 -13
  71. package/dist/index.js +47417 -19860
  72. package/dist/index.js.map +1 -1
  73. package/dist/index.mjs +45865 -18449
  74. package/dist/index.mjs.map +1 -1
  75. package/dist/installer.d.ts +1 -4
  76. package/dist/ipc/local-ipc-server.d.ts +91 -0
  77. package/dist/launch.d.ts +1 -1
  78. package/dist/logging/async-batch-writer.d.ts +10 -0
  79. package/dist/logging/log-redactor.d.ts +24 -0
  80. package/dist/logging/log-tail-reader.d.ts +81 -0
  81. package/dist/logging/logger.d.ts +1 -1
  82. package/dist/mesh/contracts.d.ts +164 -0
  83. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  84. package/dist/mesh/coordinator-registry.d.ts +59 -0
  85. package/dist/mesh/mesh-active-work.d.ts +174 -0
  86. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  87. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  88. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  89. package/dist/mesh/mesh-event-forwarding.d.ts +18 -0
  90. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  91. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  92. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  93. package/dist/mesh/mesh-events-stale.d.ts +52 -0
  94. package/dist/mesh/mesh-events-utils.d.ts +64 -0
  95. package/dist/mesh/mesh-events.d.ts +6 -49
  96. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  97. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  98. package/dist/mesh/mesh-init.d.ts +86 -0
  99. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  100. package/dist/mesh/mesh-ledger.d.ts +77 -1
  101. package/dist/mesh/mesh-missions.d.ts +164 -0
  102. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  103. package/dist/mesh/mesh-queue-assignment.d.ts +86 -0
  104. package/dist/mesh/mesh-reconcile-loop.d.ts +8 -0
  105. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  106. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  107. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  108. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  109. package/dist/mesh/mesh-routing.d.ts +70 -0
  110. package/dist/mesh/mesh-runtime-store.d.ts +439 -0
  111. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  112. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  113. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  114. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  115. package/dist/mesh/mesh-work-queue.d.ts +247 -5
  116. package/dist/mesh/preview-freshness.d.ts +18 -0
  117. package/dist/mesh/refine-config.d.ts +216 -0
  118. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  119. package/dist/providers/acp-provider-instance.d.ts +5 -0
  120. package/dist/providers/approval-utils.d.ts +20 -0
  121. package/dist/providers/chat-message-normalization.d.ts +13 -1
  122. package/dist/providers/cli-provider-instance.d.ts +111 -3
  123. package/dist/providers/contracts.d.ts +139 -6
  124. package/dist/providers/external-sources.d.ts +71 -0
  125. package/dist/providers/manual-attendance.d.ts +63 -0
  126. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  127. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  128. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  129. package/dist/providers/native-history/constants.d.ts +12 -0
  130. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  131. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  132. package/dist/providers/native-history/index.d.ts +13 -0
  133. package/dist/providers/provider-instance-manager.d.ts +14 -0
  134. package/dist/providers/provider-instance.d.ts +23 -1
  135. package/dist/providers/provider-loader.d.ts +26 -4
  136. package/dist/providers/provider-trust.d.ts +31 -0
  137. package/dist/providers/read-chat-contract.d.ts +29 -0
  138. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  139. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  140. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  141. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  142. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  143. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  144. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  145. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  146. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  147. package/dist/providers/sdk/v1/index.d.ts +30 -0
  148. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  149. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  150. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  151. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  152. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  153. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  154. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  155. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  156. package/dist/providers/spec/adapter.d.ts +91 -0
  157. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  158. package/dist/providers/spec/evaluator.d.ts +45 -0
  159. package/dist/providers/spec/fsm-driver.d.ts +397 -0
  160. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  161. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  162. package/dist/providers/spec/fsm-types.d.ts +174 -0
  163. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  164. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  165. package/dist/providers/spec/route.d.ts +4 -0
  166. package/dist/providers/spec/types.d.ts +222 -0
  167. package/dist/providers/status-monitor.d.ts +7 -7
  168. package/dist/providers/transcript-v2.d.ts +176 -0
  169. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  170. package/dist/providers/working-dir.d.ts +17 -0
  171. package/dist/repo-mesh-types.d.ts +376 -13
  172. package/dist/runtime-defaults.d.ts +2 -0
  173. package/dist/sessions/registry.d.ts +6 -0
  174. package/dist/shared-types-extra.d.ts +2 -4
  175. package/dist/shared-types.d.ts +59 -2
  176. package/dist/status/normalize.d.ts +1 -1
  177. package/dist/status/normalize.js +1 -0
  178. package/dist/status/normalize.js.map +1 -1
  179. package/dist/status/normalize.mjs +1 -0
  180. package/dist/status/normalize.mjs.map +1 -1
  181. package/dist/status/reporter.d.ts +2 -0
  182. package/dist/status/snapshot.d.ts +26 -0
  183. package/dist/system/hash.d.ts +8 -0
  184. package/dist/system/load-better-sqlite3.d.ts +21 -0
  185. package/dist/types.d.ts +5 -0
  186. package/package.json +7 -3
  187. package/src/agent-stream/poller.ts +2 -3
  188. package/src/agent-stream/provider-adapter.ts +1 -1
  189. package/src/boot/daemon-lifecycle.ts +63 -12
  190. package/src/boot/process-hardening.ts +89 -0
  191. package/src/build-info.ts +73 -0
  192. package/src/chat/source-machine.ts +534 -0
  193. package/src/chat/source-resolver.ts +0 -0
  194. package/src/chat/subscription-updates.ts +20 -1
  195. package/src/cli-adapter-types.d.ts +1 -0
  196. package/src/cli-adapter-types.ts +56 -2
  197. package/src/cli-adapters/cli-script-runner.ts +421 -0
  198. package/src/cli-adapters/cli-state-engine.ts +1221 -0
  199. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  200. package/src/cli-adapters/provider-cli-adapter.ts +836 -1141
  201. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  202. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  203. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  204. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  205. package/src/cli-adapters/provider-cli-shared.ts +110 -11
  206. package/src/cli-adapters/pty-transport.ts +2 -1
  207. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  208. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  209. package/src/cli-adapters/resolve-executable.ts +90 -0
  210. package/src/cli-adapters/session-host-transport.ts +2 -1
  211. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  212. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  213. package/src/cli-adapters/terminal-screen.ts +16 -81
  214. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  215. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  216. package/src/commands/chat-commands-read.ts +2327 -0
  217. package/src/commands/chat-commands-scope.ts +54 -0
  218. package/src/commands/chat-commands-shared.ts +114 -0
  219. package/src/commands/chat-commands-write.ts +880 -0
  220. package/src/commands/chat-commands.ts +19 -1841
  221. package/src/commands/cli-manager.ts +513 -26
  222. package/src/commands/handler.ts +841 -2
  223. package/src/commands/high-family/index.ts +28 -0
  224. package/src/commands/high-family/mesh-coordinator-launch.ts +657 -0
  225. package/src/commands/high-family/mesh-events.ts +47 -0
  226. package/src/commands/high-family/mesh-status.ts +642 -0
  227. package/src/commands/high-family/types.ts +76 -0
  228. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  229. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  230. package/src/commands/low-family/diagnostics.ts +57 -0
  231. package/src/commands/low-family/index.ts +37 -0
  232. package/src/commands/low-family/mesh-ledger.ts +62 -0
  233. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  234. package/src/commands/low-family/notification.ts +116 -0
  235. package/src/commands/low-family/refine-config.ts +106 -0
  236. package/src/commands/low-family/session-host.ts +274 -0
  237. package/src/commands/low-family/spec-providerdev.ts +217 -0
  238. package/src/commands/low-family/status-meta.ts +112 -0
  239. package/src/commands/low-family/types.ts +39 -0
  240. package/src/commands/med-family/cli-agent.ts +230 -0
  241. package/src/commands/med-family/fast-forward.ts +230 -0
  242. package/src/commands/med-family/ide.ts +163 -0
  243. package/src/commands/med-family/index.ts +37 -0
  244. package/src/commands/med-family/mesh-crud.ts +825 -0
  245. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  246. package/src/commands/med-family/mesh-queue.ts +131 -0
  247. package/src/commands/med-family/mesh-restart.ts +92 -0
  248. package/src/commands/med-family/types.ts +120 -0
  249. package/src/commands/mesh-coordinator.ts +334 -124
  250. package/src/commands/router.ts +2395 -3206
  251. package/src/commands/stream-commands.ts +8 -0
  252. package/src/commands/upgrade-helper.ts +310 -45
  253. package/src/config/chat-history.ts +483 -24
  254. package/src/config/config.ts +12 -0
  255. package/src/config/mesh-config.ts +353 -22
  256. package/src/config/recent-activity.ts +8 -2
  257. package/src/daemon/dev-auto-implement.ts +3 -2
  258. package/src/daemon/dev-cli-debug.ts +10 -1
  259. package/src/daemon/dev-server.ts +0 -541
  260. package/src/detection/cli-detector.ts +28 -9
  261. package/src/detection/ide-detector.ts +55 -16
  262. package/src/detection/win32-ide-version.ts +106 -0
  263. package/src/git/change-impact-config.ts +354 -0
  264. package/src/git/git-commands.ts +55 -14
  265. package/src/git/git-diff.ts +81 -11
  266. package/src/git/git-executor.ts +12 -0
  267. package/src/git/git-status.ts +574 -43
  268. package/src/git/git-types.ts +14 -62
  269. package/src/git/git-worktree.ts +8 -1
  270. package/src/git/index.ts +16 -0
  271. package/src/index.ts +171 -12
  272. package/src/installer.d.ts +1 -1
  273. package/src/installer.ts +8 -6
  274. package/src/ipc/local-ipc-server.ts +278 -0
  275. package/src/launch.d.ts +1 -1
  276. package/src/launch.ts +37 -28
  277. package/src/logging/async-batch-writer.ts +55 -0
  278. package/src/logging/command-log.ts +7 -5
  279. package/src/logging/log-redactor.ts +100 -0
  280. package/src/logging/log-tail-reader.ts +341 -0
  281. package/src/logging/logger.ts +14 -7
  282. package/src/mesh/contracts.ts +338 -0
  283. package/src/mesh/coordinator-prompt.ts +381 -33
  284. package/src/mesh/coordinator-registry.ts +121 -0
  285. package/src/mesh/mesh-active-work.ts +645 -0
  286. package/src/mesh/mesh-coordinator-config.ts +97 -0
  287. package/src/mesh/mesh-delivery-policy.ts +315 -0
  288. package/src/mesh/mesh-event-classify.ts +51 -0
  289. package/src/mesh/mesh-event-forwarding.ts +1575 -0
  290. package/src/mesh/mesh-event-trace.ts +67 -0
  291. package/src/mesh/mesh-events-coordinator.ts +30 -0
  292. package/src/mesh/mesh-events-pending.ts +590 -0
  293. package/src/mesh/mesh-events-stale.ts +363 -0
  294. package/src/mesh/mesh-events-utils.ts +425 -0
  295. package/src/mesh/mesh-events.ts +30 -1035
  296. package/src/mesh/mesh-fast-forward.ts +839 -0
  297. package/src/mesh/mesh-host-ownership.ts +73 -0
  298. package/src/mesh/mesh-init.ts +260 -0
  299. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  300. package/src/mesh/mesh-ledger.ts +596 -102
  301. package/src/mesh/mesh-missions.ts +322 -0
  302. package/src/mesh/mesh-node-identity.ts +1887 -0
  303. package/src/mesh/mesh-queue-assignment.ts +1491 -0
  304. package/src/mesh/mesh-reconcile-loop.ts +1332 -0
  305. package/src/mesh/mesh-refine-batch.ts +197 -0
  306. package/src/mesh/mesh-refine-gates.ts +1652 -0
  307. package/src/mesh/mesh-refine-status.ts +231 -0
  308. package/src/mesh/mesh-review-inbox.ts +307 -0
  309. package/src/mesh/mesh-routing.ts +291 -0
  310. package/src/mesh/mesh-runtime-store.ts +1708 -0
  311. package/src/mesh/mesh-scheduling-runtime.ts +199 -0
  312. package/src/mesh/mesh-task-stats.ts +161 -0
  313. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  314. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  315. package/src/mesh/mesh-work-queue.ts +997 -141
  316. package/src/mesh/preview-freshness.ts +118 -0
  317. package/src/mesh/refine-config.ts +423 -0
  318. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  319. package/src/providers/acp-provider-instance.ts +43 -10
  320. package/src/providers/approval-utils.d.ts +5 -0
  321. package/src/providers/approval-utils.ts +57 -5
  322. package/src/providers/chat-message-normalization.ts +46 -6
  323. package/src/providers/cli-provider-instance.ts +1416 -101
  324. package/src/providers/contracts.d.ts +55 -0
  325. package/src/providers/contracts.ts +150 -6
  326. package/src/providers/extension-provider-instance.ts +12 -7
  327. package/src/providers/external-sources.ts +218 -0
  328. package/src/providers/ide-provider-instance.ts +35 -12
  329. package/src/providers/manual-attendance.ts +85 -0
  330. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  331. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  332. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  333. package/src/providers/native-history/constants.ts +19 -0
  334. package/src/providers/native-history/dispatcher.ts +339 -0
  335. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  336. package/src/providers/native-history/index.ts +30 -0
  337. package/src/providers/provider-instance-manager.ts +30 -0
  338. package/src/providers/provider-instance.ts +19 -1
  339. package/src/providers/provider-loader.ts +668 -50
  340. package/src/providers/provider-schema.ts +87 -14
  341. package/src/providers/provider-trust.ts +114 -0
  342. package/src/providers/read-chat-contract.ts +76 -16
  343. package/src/providers/sdk/README.md +49 -0
  344. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  345. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  346. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  347. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  348. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  349. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  350. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  351. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  352. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  353. package/src/providers/sdk/v1/index.ts +152 -0
  354. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  355. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  356. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  357. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  358. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  359. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  360. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  361. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  362. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  363. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  364. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  365. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  366. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  367. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  368. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  369. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  370. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  374. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  375. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  376. package/src/providers/sdk/v1/validators/index.ts +19 -0
  377. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  378. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  379. package/src/providers/spec/adapter.ts +235 -0
  380. package/src/providers/spec/cli-adapter.ts +1051 -0
  381. package/src/providers/spec/evaluator.ts +407 -0
  382. package/src/providers/spec/fsm-driver.ts +1292 -0
  383. package/src/providers/spec/fsm-evaluator.ts +272 -0
  384. package/src/providers/spec/fsm-loader.ts +120 -0
  385. package/src/providers/spec/fsm-types.ts +273 -0
  386. package/src/providers/spec/native-history-executor.ts +1128 -0
  387. package/src/providers/spec/pre-launch-trust.ts +104 -0
  388. package/src/providers/spec/route.ts +51 -0
  389. package/src/providers/spec/types.ts +262 -0
  390. package/src/providers/status-monitor.d.ts +7 -7
  391. package/src/providers/status-monitor.ts +37 -22
  392. package/src/providers/transcript-v2.ts +567 -0
  393. package/src/providers/types/interactive-prompt.ts +536 -0
  394. package/src/providers/version-archive.ts +64 -24
  395. package/src/providers/working-dir.ts +23 -0
  396. package/src/repo-mesh-types.ts +542 -14
  397. package/src/runtime-defaults.ts +39 -0
  398. package/src/sessions/registry.ts +6 -0
  399. package/src/shared-types-extra.ts +2 -4
  400. package/src/shared-types.d.ts +8 -0
  401. package/src/shared-types.ts +64 -1
  402. package/src/status/builders.ts +26 -6
  403. package/src/status/normalize.ts +2 -0
  404. package/src/status/reporter.ts +19 -1
  405. package/src/status/snapshot.ts +95 -26
  406. package/src/system/hash.ts +23 -0
  407. package/src/system/host-memory.ts +29 -12
  408. package/src/system/load-better-sqlite3.ts +68 -0
  409. package/src/types.ts +5 -0
  410. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  411. package/dist/mesh/mesh-sync.d.ts +0 -53
  412. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  413. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  414. package/src/mesh/mesh-sync.ts +0 -111
@@ -1,28 +1,337 @@
1
- import { existsSync, writeFileSync, readFileSync, openSync, closeSync, unlinkSync } from 'fs';
2
- import { join } from 'path';
3
1
  import { randomUUID } from 'crypto';
4
- import { getLedgerDir } from './mesh-ledger.js';
2
+ import { requireMeshHostQueueOwner } from './mesh-host-ownership.js';
3
+ import type { RepoMeshDaemonRole } from '../repo-mesh-types.js';
4
+ import { MESH_CONVERGE_REFINE_TAG, resolveAutoConvergeCodeChange } from '../repo-mesh-types.js';
5
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
6
+ import { getMesh } from '../config/mesh-config.js';
7
+ import { LOG } from '../logging/logger.js';
8
+ import { appendLedgerEntry } from './mesh-ledger.js';
9
+ import type { MeshLedgerKind } from './mesh-ledger.js';
5
10
 
6
11
  export type MeshTaskStatus = 'pending' | 'assigned' | 'completed' | 'failed' | 'cancelled';
7
12
  export type MeshActiveTaskStatus = Extract<MeshTaskStatus, 'pending' | 'assigned'>;
8
13
  export type MeshHistoricalTaskStatus = Extract<MeshTaskStatus, 'completed' | 'failed' | 'cancelled'>;
14
+ export type MeshTaskMode = 'code_change' | 'validation' | 'live_debug_readonly' | 'launch_app' | 'convergence';
9
15
 
10
16
  export const ACTIVE_MESH_QUEUE_STATUSES: MeshActiveTaskStatus[] = ['pending', 'assigned'];
11
17
  export const HISTORICAL_MESH_QUEUE_STATUSES: MeshHistoricalTaskStatus[] = ['completed', 'failed', 'cancelled'];
18
+ export const MESH_TASK_MODES: MeshTaskMode[] = ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'];
19
+
20
+ export interface MeshTaskModeValidationResult {
21
+ valid: boolean;
22
+ taskMode?: MeshTaskMode;
23
+ violations: string[];
24
+ allowedOperations?: string[];
25
+ }
26
+
27
+ const LIVE_DEBUG_READONLY_FORBIDDEN: Array<{ label: string; pattern: RegExp }> = [
28
+ { label: 'source_edit', pattern: /\b(edit|modify|patch|apply\s+patch|write\s+(?:to\s+)?(?:file|source)|overwrite|delete\s+file|remove\s+file|create\s+file|touch\s+file)\b/i },
29
+ { label: 'checkpoint', pattern: /\b(checkpoint|mesh_checkpoint)\b/i },
30
+ { label: 'deploy_or_version_bump', pattern: /\b(deploy|wrangler\s+deploy|version[-\s]?bump|npm\s+version|release|npm\s+publish|yarn\s+publish|pnpm\s+publish)\b/i },
31
+ { label: 'destructive_shell', pattern: /\b(rm\s+-rf|mv\s+\S+\s+\S+|truncate\s|tee\s+\S+|sed\s+-i|shred\b)\b/i },
32
+ { label: 'package_install', pattern: /\b(npm\s+(?:install|i|add|link|uninstall|remove)|yarn\s+(?:add|remove|link)|pnpm\s+(?:add|remove|link)|pip\s+install|brew\s+install|apt\s+install|cargo\s+install)\b/i },
33
+ { label: 'container_mutation', pattern: /\b(docker\s+(?:build|run|exec|push|tag|rmi|rm|create|start|stop|kill)|kubectl\s+(?:apply|delete|patch|replace|create|scale))\b/i },
34
+ ];
35
+
36
+ /**
37
+ * Negation cues that, when they appear shortly before a mutation keyword inside
38
+ * the same clause, mean the keyword is being *forbidden* or described rather
39
+ * than invoked (e.g. "do not git reset", "절대 push 하지 마세요"). Matched
40
+ * case-insensitively. The Korean cues intentionally include sub-string forms
41
+ * ("않", "금지", "말 것") so conjugated variants are caught.
42
+ */
43
+ const NEGATION_CUES: string[] = [
44
+ "don't", 'do not', 'never', 'avoid', 'without', 'no longer', 'not', 'forbidden',
45
+ '하지 마', '하지 마세요', '말 것', '금지', '없음', '않',
46
+ ];
47
+
48
+ /** How many whitespace-delimited tokens before a keyword we scan for negation. */
49
+ const NEGATION_WINDOW_TOKENS = 6;
50
+
51
+ /**
52
+ * Returns true if a negation cue appears within {@link NEGATION_WINDOW_TOKENS}
53
+ * tokens before `matchIndex`, staying inside the same clause — we stop at
54
+ * sentence/line/clause boundaries (newline, `.`/`!`/`?`, `;`) so a negation in a
55
+ * previous sentence does not suppress a real command in the next one.
56
+ */
57
+ function hasNegationBefore(text: string, matchIndex: number): boolean {
58
+ const before = text.slice(0, matchIndex);
59
+ // Restrict to the current clause: cut at the last clause/sentence/line break.
60
+ const clauseStart = Math.max(
61
+ before.lastIndexOf('\n'),
62
+ before.lastIndexOf('. '),
63
+ before.lastIndexOf('! '),
64
+ before.lastIndexOf('? '),
65
+ before.lastIndexOf(';'),
66
+ );
67
+ const clause = before.slice(clauseStart + 1);
68
+ const lower = clause.toLowerCase();
69
+ // Whitespace tokens immediately preceding the keyword, within the window.
70
+ const tokens = clause.split(/\s+/).filter(Boolean);
71
+ const windowTokens = tokens.slice(Math.max(0, tokens.length - NEGATION_WINDOW_TOKENS));
72
+ const windowText = windowTokens.join(' ').toLowerCase();
73
+ for (const cue of NEGATION_CUES) {
74
+ const c = cue.toLowerCase();
75
+ // ASCII cues are word-ish phrases — match in the bounded window only.
76
+ // CJK cues have no spaces, so the window-join can miss them; for those
77
+ // fall back to scanning the whole clause (still clause-bounded).
78
+ if (/[^\x00-\x7f]/.test(c)) {
79
+ if (lower.includes(c)) return true;
80
+ } else if (windowText.includes(c)) {
81
+ return true;
82
+ }
83
+ }
84
+ return false;
85
+ }
86
+
87
+ /**
88
+ * Korean (and other) negation often trails the verb it negates ("git reset 하지
89
+ * 마세요" = "do not git reset"). Returns true if a CJK negation cue appears
90
+ * shortly after `matchEnd`, within the same clause. Scoped to CJK cues only —
91
+ * trailing ASCII words rarely negate a preceding command and would over-match.
92
+ */
93
+ function hasTrailingNegation(text: string, matchEnd: number): boolean {
94
+ const after = text.slice(matchEnd);
95
+ // Clause-bound the lookahead: stop at the next clause/line break.
96
+ const clauseEnd = (() => {
97
+ const stops = [after.indexOf('\n'), after.indexOf('. '), after.indexOf('; ')]
98
+ .filter(i => i >= 0);
99
+ return stops.length ? Math.min(...stops) : after.length;
100
+ })();
101
+ const clause = after.slice(0, clauseEnd).toLowerCase();
102
+ for (const cue of NEGATION_CUES) {
103
+ const c = cue.toLowerCase();
104
+ if (/[^\x00-\x7f]/.test(c) && clause.includes(c)) return true;
105
+ }
106
+ return false;
107
+ }
108
+
109
+ /**
110
+ * Returns true when the keyword at [matchStart, matchEnd) looks like an actual
111
+ * command invocation rather than a plain-prose mention. Command context is:
112
+ * - inside a fenced code block (``` ... ```) or inline backticks (`...`)
113
+ * - on a shell-prompt line (starts with `$ ` or `> `)
114
+ * - at a command-call position: line start (leading whitespace allowed) or
115
+ * right after a shell connective (`&&`, `||`, `|`, `;`) or an imperative
116
+ * connective ("then"/"run"/"," ) that introduces a command.
117
+ * Plain mid-sentence prose mentions (no backticks, no command position) are not
118
+ * command context and are excluded from violations.
119
+ */
120
+ function isMutationKeywordInCommandContext(text: string, matchStart: number, matchEnd: number): boolean {
121
+ if (isInsideBackticksOrFence(text, matchStart, matchEnd)) return true;
122
+
123
+ // The line containing the match, and the portion of it before the keyword.
124
+ const lineStart = text.lastIndexOf('\n', matchStart - 1) + 1;
125
+ const linePrefix = text.slice(lineStart, matchStart);
126
+
127
+ // Shell-prompt line: "$ ..." or "> ..." (leading whitespace allowed).
128
+ if (/^\s*[$>]\s/.test(text.slice(lineStart))) return true;
129
+
130
+ // Line start (only whitespace before the keyword on this line).
131
+ if (/^\s*$/.test(linePrefix)) return true;
132
+
133
+ // After a shell connective or imperative connective introducing a command.
134
+ // We look at what immediately precedes the keyword on the same line.
135
+ if (/(?:&&|\|\||\||;)\s*$/.test(linePrefix)) return true;
136
+ if (/(?:^|[\s,])(?:then|run|first)\s+$/i.test(linePrefix)) return true;
137
+ if (/,\s*$/.test(linePrefix)) return true;
138
+
139
+ return false;
140
+ }
141
+
142
+ /**
143
+ * True if [matchStart, matchEnd) lies inside an inline-backtick span or a fenced
144
+ * code block. Fenced blocks (```...```) take precedence; otherwise we count
145
+ * inline backticks before the match — an odd count means we are inside a span.
146
+ */
147
+ function isInsideBackticksOrFence(text: string, matchStart: number, matchEnd: number): boolean {
148
+ // Fenced code blocks: count ``` fences before the match.
149
+ const fenceRe = /```/g;
150
+ let fenceCount = 0;
151
+ let m: RegExpExecArray | null;
152
+ while ((m = fenceRe.exec(text)) !== null) {
153
+ if (m.index >= matchStart) break;
154
+ fenceCount++;
155
+ }
156
+ if (fenceCount % 2 === 1) return true;
157
+
158
+ // Inline backticks: count single backticks before the match start, ignoring
159
+ // those that are part of a ``` fence (handled above). An odd count → inside.
160
+ let inlineCount = 0;
161
+ for (let i = 0; i < matchStart; i++) {
162
+ if (text[i] === '`') {
163
+ // Skip triple-fence backticks.
164
+ if (text[i + 1] === '`' && text[i + 2] === '`') {
165
+ i += 2;
166
+ continue;
167
+ }
168
+ inlineCount++;
169
+ }
170
+ }
171
+ return inlineCount % 2 === 1;
172
+ }
173
+
174
+ /**
175
+ * Decides whether a forbidden keyword match at [matchStart, matchEnd) should
176
+ * count as a real violation. A match counts only when it is in command context
177
+ * and not negated. Negation always wins (even inside a code block), per the
178
+ * conservative rule: code-block + negation → exclude; other code-block → keep.
179
+ */
180
+ function isRealMutationMatch(text: string, matchStart: number, matchEnd: number): boolean {
181
+ if (hasNegationBefore(text, matchStart)) return false;
182
+ if (hasTrailingNegation(text, matchEnd)) return false;
183
+ return isMutationKeywordInCommandContext(text, matchStart, matchEnd);
184
+ }
185
+
186
+ /**
187
+ * Runs a global regex over `text` and returns true if any match is a real
188
+ * mutation (command context, not negated).
189
+ */
190
+ function patternHasRealMutation(pattern: RegExp, text: string): boolean {
191
+ const re = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');
192
+ let match: RegExpExecArray | null;
193
+ while ((match = re.exec(text)) !== null) {
194
+ if (isRealMutationMatch(text, match.index, match.index + match[0].length)) return true;
195
+ if (match.index === re.lastIndex) re.lastIndex++; // avoid zero-width loop
196
+ }
197
+ return false;
198
+ }
199
+
200
+ /**
201
+ * Git subcommands that mutate the working tree, index, refs, or remote.
202
+ * `stash` and `checkout` are intentionally absent here: they have read-only
203
+ * variants (`git stash list`/`show`, `git checkout-index`) and are classified
204
+ * token-by-token in {@link detectGitMutation} rather than by bare keyword.
205
+ */
206
+ const GIT_MUTATION_SUBCOMMANDS = new Set([
207
+ 'add', 'commit', 'push', 'reset', 'rebase', 'clean', 'switch', 'merge',
208
+ 'tag', 'restore', 'rm', 'mv', 'cherry-pick', 'revert', 'pull', 'fetch',
209
+ 'am', 'apply', 'gc', 'prune',
210
+ ]);
211
+
212
+ /**
213
+ * Read-only `git stash` variants. Any other `git stash <x>` (pop/apply/drop/
214
+ * push/save/clear, or bare `git stash` which defaults to push) is a mutation.
215
+ */
216
+ const GIT_STASH_READONLY_SUBCOMMANDS = new Set(['list', 'show']);
217
+
218
+ /**
219
+ * Detects a true git mutation in free-text task message, token-aware so that
220
+ * read-only diagnostics (`git stash list`, `git stash show --stat`,
221
+ * `git checkout-index`, `git status`, `git diff`, `git log`, ...) are allowed.
222
+ * Returns true only when a genuine mutating git invocation is present.
223
+ */
224
+ function detectGitMutation(message: string): boolean {
225
+ const re = /\bgit\s+([a-z][a-z0-9-]*)/gi;
226
+ let match: RegExpExecArray | null;
227
+ while ((match = re.exec(message)) !== null) {
228
+ const sub = match[1].toLowerCase();
229
+ // Only treat a mutating `git <sub>` as a real violation when it appears
230
+ // as an actual command (code/command context) and is not negated. Plain
231
+ // prose mentions ("don't git reset", "we won't push") are ignored.
232
+ const isReal = () => isRealMutationMatch(message, match!.index, match!.index + match![0].length);
233
+ if (GIT_MUTATION_SUBCOMMANDS.has(sub)) {
234
+ if (isReal()) return true;
235
+ continue;
236
+ }
237
+ if (sub === 'stash') {
238
+ // Token following `git stash`; read-only only for list/show.
239
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
240
+ const next = after ? after[1].toLowerCase() : '';
241
+ if (!GIT_STASH_READONLY_SUBCOMMANDS.has(next) && isReal()) return true; // bare stash = push, or pop/apply/drop/...
242
+ } else if (sub === 'checkout') {
243
+ // `git checkout <ref/path>` mutates; `git checkout-index` is matched
244
+ // as its own token by the regex (sub === 'checkout-index') and is read-only.
245
+ if (isReal()) return true;
246
+ } else if (sub === 'submodule') {
247
+ // `git submodule update` mutates; `git submodule status` is read-only.
248
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
249
+ const next = after ? after[1].toLowerCase() : '';
250
+ if ((next === 'update' || next === 'add' || next === 'sync' || next === 'deinit') && isReal()) return true;
251
+ } else if (sub === 'worktree') {
252
+ const after = message.slice(re.lastIndex).match(/^\s+([a-z][a-z0-9-]*)/i);
253
+ const next = after ? after[1].toLowerCase() : '';
254
+ if ((next === 'add' || next === 'remove' || next === 'move' || next === 'prune') && isReal()) return true;
255
+ }
256
+ // checkout-index, stash-with-no-next-already-handled, status/diff/log/show/
257
+ // rev-parse/branch/submodule status fall through as read-only.
258
+ }
259
+ return false;
260
+ }
261
+
262
+ export function normalizeMeshTaskMode(value: unknown): MeshTaskMode | undefined {
263
+ if (typeof value !== 'string') return undefined;
264
+ const normalized = value.trim() as MeshTaskMode;
265
+ return (MESH_TASK_MODES as string[]).includes(normalized) ? normalized : undefined;
266
+ }
267
+
268
+ export function validateMeshTaskModeRequest(mode: unknown, message: string): MeshTaskModeValidationResult {
269
+ const taskMode = normalizeMeshTaskMode(mode);
270
+ if (!taskMode) {
271
+ return { valid: true, violations: [] };
272
+ }
273
+ if (taskMode !== 'live_debug_readonly') {
274
+ return { valid: true, taskMode, violations: [] };
275
+ }
276
+ const text = message || '';
277
+ // Only flag keywords that look like real commands (code/command context) and
278
+ // are not negated — descriptive/prohibitive prose ("don't run `npm publish`",
279
+ // "read-only, no deploy") must not trip the guardrail.
280
+ const violations = LIVE_DEBUG_READONLY_FORBIDDEN
281
+ .filter(rule => patternHasRealMutation(rule.pattern, text))
282
+ .map(rule => rule.label);
283
+ if (detectGitMutation(text)) {
284
+ violations.push('git_mutation');
285
+ }
286
+ return {
287
+ valid: violations.length === 0,
288
+ taskMode,
289
+ violations,
290
+ allowedOperations: [
291
+ 'process/log/window/port/session inspection',
292
+ 'read-only filesystem listing/reading',
293
+ 'status probes and keep-running handle reporting',
294
+ 'diagnostic summaries without source edits, commits, checkpoints, pushes, deploys, resets, rebases, or destructive cleanups',
295
+ ],
296
+ };
297
+ }
12
298
 
13
299
  export interface MeshWorkQueueEntry {
14
300
  id: string;
15
301
  meshId: string;
16
302
  message: string;
17
303
  status: MeshTaskStatus;
304
+ taskMode?: MeshTaskMode;
18
305
  /** If specified, only this node can claim the task (used by legacy mesh_send_task) */
19
306
  targetNodeId?: string;
20
307
  /** If specified, only this runtime session can claim the task */
21
308
  targetSessionId?: string;
309
+ /** If specified, a node must expose all tags before it can claim the task. */
310
+ requiredTags?: string[];
311
+ /**
312
+ * M1: ids of tasks that must reach 'completed' before this task is claimable.
313
+ * Forward references (ids not yet enqueued) are allowed for batch flows and
314
+ * simply keep the task waiting until the referenced task exists and completes.
315
+ */
316
+ dependsOn?: string[];
317
+ /** M1/M3: mission this task belongs to (joins mesh_missions). */
318
+ missionId?: string;
319
+ /**
320
+ * M1: why this task is held back (e.g. "dependency_failed:<taskId>").
321
+ * Only set by the system on dependency failure under the 'block' policy;
322
+ * waiting-on-dependency state is computed at view time, not stored.
323
+ */
324
+ blockedReason?: string;
22
325
  /** The node that actually claimed and is executing the task */
23
326
  assignedNodeId?: string;
24
327
  /** The session currently executing the task */
25
328
  assignedSessionId?: string;
329
+ /**
330
+ * Provider type of the session that claimed the task. Recorded so the queue
331
+ * can enforce per-(node, provider) maxParallel caps (RepoMeshNodePolicy
332
+ * providerRoles) by counting active assignments grouped by node + provider.
333
+ */
334
+ assignedProviderType?: string;
26
335
  /** Human/operator reason for terminal cancellation. */
27
336
  cancelReason?: string;
28
337
  cancelledAt?: string;
@@ -30,6 +339,16 @@ export interface MeshWorkQueueEntry {
30
339
  requeueReason?: string;
31
340
  requeuedAt?: string;
32
341
  requeueCount?: number;
342
+ /** Max automatic requeue attempts. When requeueCount reaches this, task is auto-failed. */
343
+ maxRetries?: number;
344
+ /**
345
+ * Bug B: number of times the reconcile assigned-stranded watchdog has reclaimed this
346
+ * row from 'assigned' back to 'pending' because its dispatch was never confirmed
347
+ * delivered. Separate from requeueCount (operator/execution retries) and bounded by
348
+ * MAX_STRANDED_RECLAIMS so a permanently-undeliverable target auto-fails rather than
349
+ * cycling reclaim→re-dispatch→strand forever.
350
+ */
351
+ strandedReclaimCount?: number;
33
352
  /** Last automatic queue session spin-up attempt, for mesh_view_queue/debug visibility. */
34
353
  autoLaunch?: {
35
354
  status: 'skipped' | 'started' | 'failed' | 'completed';
@@ -41,54 +360,211 @@ export interface MeshWorkQueueEntry {
41
360
  };
42
361
  /** ISO timestamp when the task was dispatched (assigned) to a node/session. Used for precise matching on completion. */
43
362
  dispatchTimestamp?: string;
363
+ /**
364
+ * (3) The ORIGINATING coordinator session that enqueued this task. Stamped onto the
365
+ * worker at dispatch (meshCoordinatorSessionId) so the task's completion routes back to
366
+ * the exact coordinator session — even when several coordinator sessions share one
367
+ * daemon. Rides in the queue payload JSON (no column migration); absent on legacy rows
368
+ * → daemon-level routing fallback (backward + version-skew safe).
369
+ */
370
+ sourceCoordinatorSessionId?: string;
44
371
  createdAt: string;
45
372
  updatedAt: string;
46
373
  }
47
374
 
48
- function getQueuePath(meshId: string): string {
49
- const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
50
- return join(getLedgerDir(), `${safe}.queue.json`);
375
+ export interface MeshQueueMutationOptions {
376
+ ownerRole?: RepoMeshDaemonRole;
51
377
  }
52
378
 
53
- function getLockPath(meshId: string): string {
54
- const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
55
- return join(getLedgerDir(), `${safe}.queue.lock`);
379
+ export function normalizeMeshCapabilityTags(value: unknown): string[] {
380
+ if (!Array.isArray(value)) return [];
381
+ const seen = new Set<string>();
382
+ return value
383
+ .map(tag => typeof tag === 'string' ? tag.trim() : '')
384
+ .filter(Boolean)
385
+ .filter(tag => {
386
+ if (seen.has(tag)) return false;
387
+ seen.add(tag);
388
+ return true;
389
+ });
390
+ }
391
+
392
+ function firstProviderPriority(policy: unknown): string | undefined {
393
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
394
+ ? (policy as Record<string, unknown>).providerPriority
395
+ : undefined;
396
+ if (!Array.isArray(raw)) return undefined;
397
+ return raw.find(type => typeof type === 'string' && type.trim())?.trim();
398
+ }
399
+
400
+ function readNodeOverride(node: { userOverrides?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
401
+ const overrides = node?.userOverrides;
402
+ if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) return null;
403
+ const value = (overrides as Record<string, unknown>)[key];
404
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
56
405
  }
57
406
 
58
407
  /**
59
- * Simple advisory file lock using O_EXCL (atomic create) for queue mutations.
60
- * Retries up to 10 times at 30 ms intervals; proceeds without lock on timeout
61
- * to prevent deadlock (best-effort far better than no locking at all).
408
+ * Live, self-reported platform/arch the owning daemon stamped onto the node from
409
+ * its own process.platform/process.arch via the git_status envelope. Kept on a
410
+ * field DISTINCT from userOverrides so capability-tag derivation can prefer an
411
+ * explicit operator override while still self-healing auto-detected nodes — and
412
+ * so the value reflects the node's real OS rather than the coordinator's.
62
413
  */
63
- function withQueueLock<T>(meshId: string, fn: () => T): T {
64
- const lockPath = getLockPath(meshId);
65
- let fd = -1;
66
- for (let i = 0; i < 10; i++) {
67
- try { fd = openSync(lockPath, 'wx'); break; } catch {
68
- const deadline = Date.now() + 30;
69
- while (Date.now() < deadline) { /* spin */ }
70
- }
71
- }
72
- try { return fn(); } finally {
73
- if (fd !== -1) try { closeSync(fd); } catch { /* noop */ }
74
- try { unlinkSync(lockPath); } catch { /* already removed */ }
75
- }
414
+ function readNodeReporter(node: { reportedPlatform?: unknown; reportedArch?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
415
+ const value = key === 'platform' ? node?.reportedPlatform : node?.reportedArch;
416
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
76
417
  }
77
418
 
78
- function readQueue(meshId: string): MeshWorkQueueEntry[] {
79
- const path = getQueuePath(meshId);
80
- if (!existsSync(path)) return [];
419
+ export function buildMeshNodeCapabilityTags(
420
+ node: { capabilities?: unknown; policy?: unknown; isLocalWorktree?: unknown; worktreeBranch?: unknown; userOverrides?: unknown; reportedPlatform?: unknown; reportedArch?: unknown } | undefined,
421
+ providerType?: string,
422
+ ): string[] {
423
+ const provider = typeof providerType === 'string' && providerType.trim()
424
+ ? providerType.trim()
425
+ : firstProviderPriority(node?.policy);
426
+ const worktreeBranch = typeof node?.worktreeBranch === 'string' && node.worktreeBranch.trim()
427
+ ? node.worktreeBranch.trim()
428
+ : null;
429
+ // Per-node platform/arch precedence (highest → lowest):
430
+ // 1. userOverrides.platform/arch — an EXPLICIT operator override always wins.
431
+ // 2. reportedPlatform/reportedArch — the live OS the owning daemon
432
+ // self-reported (its own process.platform/process.arch via the git_status
433
+ // envelope), persisted to the node record on each direct probe. This is
434
+ // why a Windows member advertises os=win32 even though the COORDINATOR
435
+ // computing these tags runs on darwin — without it the consumer reads the
436
+ // persistent node (operator userOverrides empty) and would fall straight
437
+ // through to the coordinator's own process.platform, mislabeling every
438
+ // node os=darwin. We prefer this LIVE value over any stale auto-stamp.
439
+ // 3. process.platform/process.arch — last-resort fallback, correct only for
440
+ // the local coordinator node / local worktree nodes that have not yet
441
+ // been probed (their workspace lives on THIS machine anyway).
442
+ // Vocabulary is raw process.platform/process.arch ("darwin"/"win32"/"linux",
443
+ // "arm64"/"x64") on both the advertiser and the required_tags matcher, which
444
+ // compares with plain string equality (nodeSatisfiesRequiredTags) — so this
445
+ // keeps the win32/darwin/linux vocabulary the matcher already expects.
446
+ const os = readNodeOverride(node, 'platform') ?? readNodeReporter(node, 'platform') ?? process.platform;
447
+ const arch = readNodeOverride(node, 'arch') ?? readNodeReporter(node, 'arch') ?? process.arch;
448
+ return normalizeMeshCapabilityTags([
449
+ ...(Array.isArray(node?.capabilities) ? node.capabilities : []),
450
+ `os=${os}`,
451
+ `arch=${arch}`,
452
+ ...(provider ? [`provider=${provider}`] : []),
453
+ // Worktree nodes automatically expose a "worktree=<branch>" tag so that
454
+ // mesh_enqueue_task with required_tags: ["worktree=<branch>"] routes
455
+ // only to the matching worktree node.
456
+ ...(node?.isLocalWorktree === true && worktreeBranch ? [`worktree=${worktreeBranch}`] : []),
457
+ // Convergence routing: advertise how this node can land its work onto base.
458
+ // - converge=refine: local worktree nodes (on ANY machine — refine_mesh_node
459
+ // now forwards to the owning daemon) can run the Refinery merge → push →
460
+ // cleanup against their own checkout, so they accept code_change tasks.
461
+ // - converge=fast_forward: non-worktree nodes (the machine itself) can only
462
+ // ff/push an already-converged branch; they are NOT a destination for
463
+ // code_change work (a worktree is created first, and that worktree node
464
+ // receives the task instead). Reuses the ordinary required-tags filter —
465
+ // the load-balancing scheduler auto-injects converge=refine for code_change
466
+ // so such work is hard-filtered onto refine-capable nodes.
467
+ ...(node?.isLocalWorktree === true ? ['converge=refine'] : ['converge=fast_forward']),
468
+ ]);
469
+ }
470
+
471
+ export function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean {
472
+ const required = normalizeMeshCapabilityTags(requiredTags);
473
+ if (required.length === 0) return true;
474
+ const available = new Set(normalizeMeshCapabilityTags(capabilityTags));
475
+ return required.every(tag => available.has(tag));
476
+ }
477
+
478
+ /**
479
+ * Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
480
+ *
481
+ * When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
482
+ * tag is merged into a code_change task's required tags at enqueue time, so the
483
+ * scheduler hard-filters the task onto refine-capable worktree nodes only (on any
484
+ * machine — refine_mesh_node forwards to the owning daemon). Because the tag is
485
+ * persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
486
+ * and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
487
+ * it consistently.
488
+ *
489
+ * Strict backward compatibility — the injection is skipped (returns the explicit tags
490
+ * unchanged) when ANY of:
491
+ * - the mesh does not opt in (autoConvergeCodeChange !== true), or
492
+ * - the task is not code_change (validation / live_debug_readonly / launch_app /
493
+ * convergence carry no merge cost and may run anywhere), or
494
+ * - the task is explicitly targeted (targetNodeId): the operator chose the node, so
495
+ * we do not second-guess it by filtering on convergence capability.
496
+ * Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
497
+ */
498
+ export function resolveConvergeRequiredTags(
499
+ meshId: string,
500
+ taskMode: MeshTaskMode | undefined,
501
+ explicitRequiredTags: string[],
502
+ opts?: { targetNodeId?: string },
503
+ ): string[] {
504
+ if (taskMode !== 'code_change') return explicitRequiredTags;
505
+ if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
506
+ let optedIn = false;
81
507
  try {
82
- const content = readFileSync(path, 'utf-8');
83
- return JSON.parse(content) as MeshWorkQueueEntry[];
508
+ optedIn = resolveAutoConvergeCodeChange(getMesh(meshId)?.policy as any);
84
509
  } catch {
85
- return [];
510
+ optedIn = false;
86
511
  }
512
+ if (!optedIn) return explicitRequiredTags;
513
+ return normalizeMeshCapabilityTags([...explicitRequiredTags, MESH_CONVERGE_REFINE_TAG]);
514
+ }
515
+
516
+ function withQueueLock<T>(_meshId: string, fn: () => T): T {
517
+ return MeshRuntimeStore.getInstance().transaction(fn);
518
+ }
519
+
520
+ function readQueue(meshId: string): MeshWorkQueueEntry[] {
521
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId);
87
522
  }
88
523
 
89
524
  function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
90
- const path = getQueuePath(meshId);
91
- writeFileSync(path, JSON.stringify(queue, null, 2), 'utf-8');
525
+ MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
526
+ }
527
+
528
+ function normalizeDependsOn(value: unknown): string[] {
529
+ if (!Array.isArray(value)) return [];
530
+ const seen = new Set<string>();
531
+ return value
532
+ .map(id => typeof id === 'string' ? id.trim() : '')
533
+ .filter(Boolean)
534
+ .filter(id => {
535
+ if (seen.has(id)) return false;
536
+ seen.add(id);
537
+ return true;
538
+ });
539
+ }
540
+
541
+ /**
542
+ * M1: detect dependency cycles before enqueue. Walks the dependency graph of
543
+ * existing queue entries plus the new task's edges. Fail-closed: a cycle
544
+ * rejects the enqueue entirely. Synchronous and bounded by queue size.
545
+ */
546
+ export function assertNoDependencyCycle(meshId: string, newTaskId: string, dependsOn: string[]): void {
547
+ if (dependsOn.length === 0) return;
548
+ if (dependsOn.includes(newTaskId)) {
549
+ throw new Error(`dependency_cycle_detected: task '${newTaskId}' cannot depend on itself`);
550
+ }
551
+ const adjacency = new Map<string, string[]>();
552
+ for (const entry of readQueue(meshId)) {
553
+ adjacency.set(entry.id, normalizeDependsOn(entry.dependsOn));
554
+ }
555
+ adjacency.set(newTaskId, dependsOn);
556
+ // DFS from the new task: if we can reach newTaskId again, the edges form a cycle.
557
+ const stack = [...dependsOn];
558
+ const visited = new Set<string>();
559
+ while (stack.length > 0) {
560
+ const current = stack.pop()!;
561
+ if (current === newTaskId) {
562
+ throw new Error(`dependency_cycle_detected: task '${newTaskId}' is part of a dependency cycle via '${dependsOn.join(', ')}'`);
563
+ }
564
+ if (visited.has(current)) continue;
565
+ visited.add(current);
566
+ stack.push(...(adjacency.get(current) ?? []));
567
+ }
92
568
  }
93
569
 
94
570
  /**
@@ -97,22 +573,125 @@ function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
97
573
  export function enqueueTask(
98
574
  meshId: string,
99
575
  message: string,
100
- opts?: { targetNodeId?: string; targetSessionId?: string }
576
+ opts?: {
577
+ targetNodeId?: string;
578
+ targetSessionId?: string;
579
+ taskMode?: MeshTaskMode | string;
580
+ requiredTags?: string[];
581
+ /** M1: tasks that must complete before this one is claimable. */
582
+ dependsOn?: string[];
583
+ /** M1/M3: mission this task belongs to. */
584
+ missionId?: string;
585
+ /** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
586
+ id?: string;
587
+ /** (3) Originating coordinator session id (for session-anchored completion routing). */
588
+ sourceCoordinatorSessionId?: string;
589
+ } & MeshQueueMutationOptions,
101
590
  ): MeshWorkQueueEntry {
591
+ requireMeshHostQueueOwner(opts);
592
+ const modeValidation = validateMeshTaskModeRequest(opts?.taskMode, message);
593
+ if (!modeValidation.valid) {
594
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
595
+ }
596
+ const id = typeof opts?.id === 'string' && opts.id.trim() ? opts.id.trim() : randomUUID();
597
+ const dependsOn = normalizeDependsOn(opts?.dependsOn);
102
598
  return withQueueLock(meshId, () => {
103
- const queue = readQueue(meshId);
599
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, id)) {
600
+ throw new Error(`duplicate_task_id: task '${id}' already exists in mesh '${meshId}'`);
601
+ }
602
+ assertNoDependencyCycle(meshId, id, dependsOn);
603
+ const callerTags = normalizeMeshCapabilityTags(opts?.requiredTags);
604
+ // Convergence routing (opt-in): auto-inject converge=refine for code_change
605
+ // tasks so they hard-filter onto refine-capable worktree nodes. No-op unless
606
+ // the mesh opts in; explicit target_node_id / required_tags are preserved.
607
+ // Routing is otherwise governed solely by the caller's required_tags (hard
608
+ // filter through nodeSatisfiesRequiredTags) — no role/taskMode auto-routing.
609
+ const resolvedRequiredTags = resolveConvergeRequiredTags(
610
+ meshId,
611
+ modeValidation.taskMode,
612
+ callerTags,
613
+ { targetNodeId: opts?.targetNodeId },
614
+ );
104
615
  const entry: MeshWorkQueueEntry = {
105
- id: randomUUID(),
616
+ id,
106
617
  meshId,
107
618
  message,
108
619
  status: 'pending',
620
+ taskMode: modeValidation.taskMode,
109
621
  targetNodeId: opts?.targetNodeId,
110
622
  targetSessionId: opts?.targetSessionId,
623
+ requiredTags: resolvedRequiredTags,
624
+ ...(dependsOn.length > 0 ? { dependsOn } : {}),
625
+ ...(typeof opts?.missionId === 'string' && opts.missionId.trim() ? { missionId: opts.missionId.trim() } : {}),
626
+ ...(typeof opts?.sourceCoordinatorSessionId === 'string' && opts.sourceCoordinatorSessionId.trim()
627
+ ? { sourceCoordinatorSessionId: opts.sourceCoordinatorSessionId.trim() }
628
+ : {}),
111
629
  createdAt: new Date().toISOString(),
112
630
  updatedAt: new Date().toISOString(),
113
631
  };
114
- queue.push(entry);
115
- writeQueue(meshId, queue);
632
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
633
+ return entry;
634
+ });
635
+ }
636
+
637
+ /**
638
+ * Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
639
+ * entry so it is attributable to a mission.
640
+ *
641
+ * Direct dispatch normally bypasses the queue entirely — the task lives only in
642
+ * the ledger + mesh_direct_dispatches table, neither of which carries a
643
+ * missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
644
+ * (which both scan the queue for `task.missionId`) count it as 0. When a
645
+ * mission is attached, we materialise the same queue entry shape an enqueued
646
+ * task would have, but pre-assigned to the dispatched node/session and stamped
647
+ * with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
648
+ * → findAssignedBySession) then flips it to completed/failed exactly like a
649
+ * pulled task, so mission total + completed aggregates work with no extra wiring.
650
+ *
651
+ * Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
652
+ * work for the queue to assign, whereas this records work already dispatched
653
+ * out-of-band. They share the missionId stamping rule and mode validation.
654
+ */
655
+ export function recordDirectDispatchTask(
656
+ meshId: string,
657
+ message: string,
658
+ opts: {
659
+ id: string;
660
+ missionId: string;
661
+ assignedNodeId?: string;
662
+ assignedSessionId?: string;
663
+ taskMode?: MeshTaskMode | string;
664
+ dispatchedAt?: string;
665
+ },
666
+ ): MeshWorkQueueEntry | null {
667
+ const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
668
+ if (!missionId) return null;
669
+ const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
670
+ if (!taskId) return null;
671
+ const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message);
672
+ if (!modeValidation.valid) {
673
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
674
+ }
675
+ const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
676
+ return withQueueLock(meshId, () => {
677
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
678
+ // Already materialised (e.g. retry of the same dispatch) — leave it untouched.
679
+ return null;
680
+ }
681
+ const entry: MeshWorkQueueEntry = {
682
+ id: taskId,
683
+ meshId,
684
+ message,
685
+ status: 'assigned',
686
+ ...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
687
+ missionId,
688
+ ...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
689
+ ...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
690
+ dispatchTimestamp: now,
691
+ createdAt: now,
692
+ updatedAt: now,
693
+ };
694
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
116
695
  return entry;
117
696
  });
118
697
  }
@@ -121,43 +700,83 @@ export function enqueueTask(
121
700
  * Get all tasks in the queue, optionally filtered by status.
122
701
  */
123
702
  export function getQueue(meshId: string, opts?: { status?: MeshTaskStatus[] }): MeshWorkQueueEntry[] {
124
- let queue = readQueue(meshId);
125
- if (opts?.status?.length) {
126
- const statuses = new Set(opts.status);
127
- queue = queue.filter(q => statuses.has(q.status));
128
- }
129
- return queue;
703
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId, opts?.status?.length ? opts.status : undefined);
704
+ }
705
+
706
+ export function getMeshQueueRevision(meshId: string): string {
707
+ return MeshRuntimeStore.getInstance().getQueueRevision(meshId);
130
708
  }
131
709
 
132
710
  /**
133
711
  * Find the next pending task that this node is allowed to claim, and mark it as assigned.
712
+ *
713
+ * `opts.providerType` is stamped onto the claimed entry (assignedProviderType) so
714
+ * per-(node, provider) caps can be counted. `opts.providerMaxParallel`, when set,
715
+ * is the enforced per-(node, provider) cap from RepoMeshNodePolicy.providerRoles:
716
+ * a task is not assigned to this (node, provider) once it already has that many
717
+ * active assignments. This composes with the global/taskMode caps (stricter wins).
134
718
  */
135
- export function claimNextTask(meshId: string, nodeId: string, sessionId: string): MeshWorkQueueEntry | null {
136
- return withQueueLock(meshId, () => {
137
- const queue = readQueue(meshId);
138
- const hasActiveAssignment = queue.some(q => q.status === 'assigned' && (
139
- q.assignedSessionId === sessionId || q.assignedNodeId === nodeId
140
- ));
141
- if (hasActiveAssignment) return null;
142
- let targetIdx = queue.findIndex(q => q.status === 'pending' && q.targetSessionId === sessionId);
143
- if (targetIdx === -1) {
144
- targetIdx = queue.findIndex(q => q.status === 'pending' && q.targetNodeId === nodeId && !q.targetSessionId);
145
- }
146
- if (targetIdx === -1) {
147
- targetIdx = queue.findIndex(q => q.status === 'pending' && !q.targetNodeId && !q.targetSessionId);
719
+ export function claimNextTask(
720
+ meshId: string,
721
+ nodeId: string,
722
+ sessionId: string,
723
+ capabilityTags?: string[],
724
+ opts?: { providerType?: string; providerMaxParallel?: number; nodeIsWorktree?: boolean },
725
+ ): MeshWorkQueueEntry | null {
726
+ return MeshRuntimeStore.getInstance().claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags, opts);
727
+ }
728
+
729
+ // ─── M1: Dependency Failure Propagation ─────────
730
+
731
+ export type DependencyFailurePolicy = 'block' | 'cancel';
732
+
733
+ function resolveDependencyFailurePolicy(meshId: string): DependencyFailurePolicy {
734
+ try {
735
+ const policy = (getMesh(meshId)?.policy ?? {}) as Record<string, unknown>;
736
+ return policy.onDependencyFailure === 'cancel' ? 'cancel' : 'block';
737
+ } catch {
738
+ return 'block';
739
+ }
740
+ }
741
+
742
+ /**
743
+ * Apply the mesh's onDependencyFailure policy to pending dependents of a task
744
+ * that just reached a failed/cancelled terminal state.
745
+ *
746
+ * - 'block' (default): dependents stay pending with blockedReason
747
+ * "dependency_failed:<taskId>" so an operator can requeue/cancel them.
748
+ * - 'cancel': dependents are cancelled (cascading to their own dependents).
749
+ *
750
+ * Must be called inside the queue lock of the triggering transition.
751
+ */
752
+ function propagateDependencyFailure(meshId: string, failedTaskId: string): void {
753
+ const policy = resolveDependencyFailurePolicy(meshId);
754
+ const store = MeshRuntimeStore.getInstance();
755
+ const frontier = [failedTaskId];
756
+ const seen = new Set<string>(frontier);
757
+ while (frontier.length > 0) {
758
+ const currentId = frontier.pop()!;
759
+ const dependents = store.getQueueEntries(meshId, ['pending'])
760
+ .filter(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(currentId));
761
+ for (const dependent of dependents) {
762
+ if (seen.has(dependent.id)) continue;
763
+ seen.add(dependent.id);
764
+ if (policy === 'cancel') {
765
+ dependent.status = 'cancelled';
766
+ dependent.cancelledAt = new Date().toISOString();
767
+ dependent.cancelReason = `dependency_failed:${currentId}`;
768
+ store.updateQueueEntry(dependent);
769
+ frontier.push(dependent.id); // cascade to transitive dependents
770
+ } else {
771
+ dependent.blockedReason = `dependency_failed:${currentId}`;
772
+ store.updateQueueEntry(dependent);
773
+ }
148
774
  }
149
- if (targetIdx === -1) return null;
150
- const entry = queue[targetIdx];
151
- entry.status = 'assigned';
152
- entry.assignedNodeId = nodeId;
153
- entry.assignedSessionId = sessionId;
154
- entry.dispatchTimestamp = new Date().toISOString();
155
- entry.updatedAt = new Date().toISOString();
156
- writeQueue(meshId, queue);
157
- return entry;
158
- });
775
+ }
159
776
  }
160
777
 
778
+ const DEPENDENCY_FAILURE_TERMINALS = new Set<MeshTaskStatus>(['failed', 'cancelled']);
779
+
161
780
  /**
162
781
  * Update the status of a specific task.
163
782
  * Used when a session completes, fails, or stalls.
@@ -166,15 +785,16 @@ export function updateTaskStatus(
166
785
  meshId: string,
167
786
  taskId: string,
168
787
  status: MeshTaskStatus,
788
+ opts?: MeshQueueMutationOptions,
169
789
  ): MeshWorkQueueEntry | null {
790
+ requireMeshHostQueueOwner(opts);
170
791
  return withQueueLock(meshId, () => {
171
- const queue = readQueue(meshId);
172
- const idx = queue.findIndex(q => q.id === taskId);
173
- if (idx === -1) return null;
174
- queue[idx].status = status;
175
- queue[idx].updatedAt = new Date().toISOString();
176
- writeQueue(meshId, queue);
177
- return queue[idx];
792
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
793
+ if (!entry) return null;
794
+ entry.status = status;
795
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
796
+ if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
797
+ return entry;
178
798
  });
179
799
  }
180
800
 
@@ -184,14 +804,12 @@ export function recordTaskAutoLaunch(
184
804
  autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>,
185
805
  ): MeshWorkQueueEntry | null {
186
806
  return withQueueLock(meshId, () => {
187
- const queue = readQueue(meshId);
188
- const idx = queue.findIndex(q => q.id === taskId);
189
- if (idx === -1) return null;
807
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
808
+ if (!entry) return null;
190
809
  const now = new Date().toISOString();
191
- queue[idx].autoLaunch = { ...autoLaunch, updatedAt: now };
192
- queue[idx].updatedAt = now;
193
- writeQueue(meshId, queue);
194
- return queue[idx];
810
+ entry.autoLaunch = { ...autoLaunch, updatedAt: now };
811
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
812
+ return entry;
195
813
  });
196
814
  }
197
815
 
@@ -201,19 +819,19 @@ export function recordTaskAutoLaunch(
201
819
  export function cancelTask(
202
820
  meshId: string,
203
821
  taskId: string,
204
- opts?: { reason?: string },
822
+ opts?: { reason?: string } & MeshQueueMutationOptions,
205
823
  ): MeshWorkQueueEntry | null {
824
+ requireMeshHostQueueOwner(opts);
206
825
  return withQueueLock(meshId, () => {
207
- const queue = readQueue(meshId);
208
- const idx = queue.findIndex(q => q.id === taskId);
209
- if (idx === -1) return null;
826
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
827
+ if (!entry) return null;
210
828
  const now = new Date().toISOString();
211
- queue[idx].status = 'cancelled';
212
- queue[idx].updatedAt = now;
213
- queue[idx].cancelledAt = now;
214
- if (opts?.reason) queue[idx].cancelReason = opts.reason;
215
- writeQueue(meshId, queue);
216
- return queue[idx];
829
+ entry.status = 'cancelled';
830
+ entry.cancelledAt = now;
831
+ if (opts?.reason) entry.cancelReason = opts.reason;
832
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
833
+ propagateDependencyFailure(meshId, taskId);
834
+ return entry;
217
835
  });
218
836
  }
219
837
 
@@ -221,6 +839,11 @@ export function cancelTask(
221
839
  * Return a queue task to pending for retry. By default, dead session targeting
222
840
  * and assigned ownership are cleared so stale assignments do not strand again.
223
841
  */
842
+ export type RequeueResult =
843
+ | { status: 'requeued'; entry: MeshWorkQueueEntry }
844
+ | { status: 'failed_max_retries'; entry: MeshWorkQueueEntry; maxRetries: number; requeueCount: number }
845
+ | { status: 'not_found' };
846
+
224
847
  export function requeueTask(
225
848
  meshId: string,
226
849
  taskId: string,
@@ -230,15 +853,34 @@ export function requeueTask(
230
853
  targetSessionId?: string;
231
854
  clearTargetNode?: boolean;
232
855
  clearTargetSession?: boolean;
233
- },
856
+ /**
857
+ * Override the retry cap for this call. Use only for explicit operator actions.
858
+ * If true, the task is requeued even when requeueCount >= maxRetries.
859
+ */
860
+ force?: boolean;
861
+ /** Per-task retry cap override. Falls back to mesh policy maxTaskRetries (default 1). */
862
+ maxRetries?: number;
863
+ } & MeshQueueMutationOptions,
234
864
  ): MeshWorkQueueEntry | null {
865
+ requireMeshHostQueueOwner(opts);
235
866
  return withQueueLock(meshId, () => {
236
- const queue = readQueue(meshId);
237
- const idx = queue.findIndex(q => q.id === taskId);
238
- if (idx === -1) return null;
239
- const entry = queue[idx];
240
- const now = new Date().toISOString();
867
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
868
+ if (!entry) return null;
869
+ const currentCount = entry.requeueCount || 0;
870
+ const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
871
+ if (!opts?.force && currentCount >= maxRetries) {
872
+ // Auto-fail: cap exceeded without explicit force override.
873
+ entry.status = 'failed';
874
+ entry.cancelReason = `max_retries_exceeded: requeued ${currentCount} time(s), limit is ${maxRetries}`;
875
+ entry.updatedAt = new Date().toISOString();
876
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
877
+ propagateDependencyFailure(meshId, taskId);
878
+ return entry;
879
+ }
241
880
  entry.status = 'pending';
881
+ // Operator requeue clears a dependency-failure block — the operator is
882
+ // explicitly overriding the held-back state.
883
+ delete entry.blockedReason;
242
884
  delete entry.assignedNodeId;
243
885
  delete entry.assignedSessionId;
244
886
  delete entry.cancelledAt;
@@ -247,11 +889,89 @@ export function requeueTask(
247
889
  if (typeof opts?.targetNodeId === 'string') entry.targetNodeId = opts.targetNodeId;
248
890
  if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
249
891
  if (typeof opts?.targetSessionId === 'string') entry.targetSessionId = opts.targetSessionId;
250
- entry.updatedAt = now;
251
- entry.requeuedAt = now;
252
- entry.requeueCount = (entry.requeueCount || 0) + 1;
892
+ entry.requeuedAt = new Date().toISOString();
893
+ entry.requeueCount = currentCount + 1;
253
894
  if (opts?.reason) entry.requeueReason = opts.reason;
254
- writeQueue(meshId, queue);
895
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
896
+ return entry;
897
+ });
898
+ }
899
+
900
+ /**
901
+ * Max times the assigned-stranded watchdog will reclaim a single task before giving
902
+ * up and failing it. Bounds the reclaim→re-dispatch→strand cycle so a permanently
903
+ * undeliverable target (e.g. a node whose transport is wedged) eventually fails and
904
+ * unblocks its dependents instead of looping every reconcile tick.
905
+ */
906
+ const MAX_STRANDED_RECLAIMS = 3;
907
+
908
+ /**
909
+ * Bug B: reclaim a task stuck in 'assigned' because its dispatch was never confirmed.
910
+ *
911
+ * claimNextTask atomically marks a row 'assigned' BEFORE the fire-and-forget dispatch
912
+ * runs. If that dispatch neither rejects (→ no .catch requeue) nor is confirmed
913
+ * delivered — a relay that hangs without acking, or a confirm timer lost across a
914
+ * daemon restart — the row stays 'assigned' forever, contributing 0 pending so PHASE 3
915
+ * reconcile never re-examines it. This returns such a row to 'pending' and clears its
916
+ * dead assignment ownership (node / session / provider / dispatchTimestamp) — the same
917
+ * ownership-clear requeueTask applies — so PHASE 3 can re-dispatch it onto a fresh idle
918
+ * session.
919
+ *
920
+ * Guarded to 'assigned' rows only (a completion/cancel that already moved the row off
921
+ * 'assigned' must never be resurrected) and bounded by MAX_STRANDED_RECLAIMS (beyond
922
+ * which the task is failed so dependents unblock).
923
+ */
924
+ export function reclaimStrandedAssignedTask(
925
+ meshId: string,
926
+ taskId: string,
927
+ opts?: { reason?: string; ageMs?: number } & MeshQueueMutationOptions,
928
+ ): MeshWorkQueueEntry | null {
929
+ requireMeshHostQueueOwner(opts);
930
+ return withQueueLock(meshId, () => {
931
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
932
+ if (!entry) return null;
933
+ // Only a still-assigned row is stranded. If a completion/cancel already moved it
934
+ // off 'assigned', there is nothing to reclaim — never resurrect a terminal row.
935
+ if (entry.status !== 'assigned') return null;
936
+ const now = new Date().toISOString();
937
+ const reason = opts?.reason || 'assigned_stranded_dispatch_unconfirmed';
938
+ const reclaims = (entry.strandedReclaimCount || 0) + 1;
939
+ const prevNode = entry.assignedNodeId;
940
+ const prevSession = entry.assignedSessionId;
941
+ // Always clear the dead assignment ownership so a re-claim starts clean and the
942
+ // assigned-counters (which filter status==='assigned') stop counting this row.
943
+ delete entry.assignedNodeId;
944
+ delete entry.assignedSessionId;
945
+ delete entry.assignedProviderType;
946
+ delete entry.dispatchTimestamp;
947
+ entry.strandedReclaimCount = reclaims;
948
+ entry.updatedAt = now;
949
+ if (reclaims > MAX_STRANDED_RECLAIMS) {
950
+ // Repeatedly undeliverable — stop cycling and fail it so dependents unblock.
951
+ entry.status = 'failed';
952
+ entry.cancelReason = `stranded_dispatch_unrecovered: reclaimed ${reclaims - 1} time(s) without a confirmed dispatch`;
953
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
954
+ propagateDependencyFailure(meshId, taskId);
955
+ } else {
956
+ entry.status = 'pending';
957
+ entry.requeuedAt = now;
958
+ entry.requeueReason = reason;
959
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
960
+ }
961
+ try {
962
+ appendLedgerEntry(meshId, {
963
+ kind: 'task_reclaimed' as MeshLedgerKind,
964
+ nodeId: prevNode,
965
+ sessionId: prevSession,
966
+ payload: {
967
+ taskId,
968
+ reason,
969
+ ...(typeof opts?.ageMs === 'number' ? { ageMs: opts.ageMs } : {}),
970
+ reclaimCount: reclaims,
971
+ outcome: entry.status,
972
+ },
973
+ });
974
+ } catch { /* ledger write is best-effort */ }
255
975
  return entry;
256
976
  });
257
977
  }
@@ -263,28 +983,58 @@ export function updateSessionTaskStatus(
263
983
  meshId: string,
264
984
  sessionId: string,
265
985
  status: MeshTaskStatus,
266
- opts?: { occurredAt?: string },
986
+ opts?: { occurredAt?: string; taskId?: string },
267
987
  ): MeshWorkQueueEntry | null {
268
988
  return withQueueLock(meshId, () => {
269
- const queue = readQueue(meshId);
270
- const occurredAtTime = opts?.occurredAt ? new Date(opts.occurredAt).getTime() : Number.NaN;
271
- const hasOccurredAt = Number.isFinite(occurredAtTime);
272
- let bestIdx = -1;
273
- let bestTime = 0;
274
- for (let i = queue.length - 1; i >= 0; i--) {
275
- if (queue[i].assignedSessionId !== sessionId || queue[i].status !== 'assigned') continue;
276
- const time = new Date(queue[i].dispatchTimestamp || queue[i].updatedAt).getTime();
277
- if (hasOccurredAt && Number.isFinite(time) && time > occurredAtTime) continue;
278
- if (time > bestTime) { bestTime = time; bestIdx = i; }
989
+ const store = MeshRuntimeStore.getInstance();
990
+ const occurredAtIso = opts?.occurredAt ? new Date(opts.occurredAt).toISOString() : undefined;
991
+ const entry = store.findAssignedBySession(meshId, sessionId, occurredAtIso, opts?.taskId);
992
+ if (!entry) {
993
+ // C2: the silent null here is exactly what stranded a finished task as
994
+ // `assigned` for 19 minutes. If the session still has an assigned row we
995
+ // failed to resolve, surface it loudly instead of dropping the completion.
996
+ const assignedRows = store.getActiveAssignmentDetails(meshId)
997
+ .filter(r => r.sessionId === sessionId);
998
+ if (assignedRows.length > 0) {
999
+ LOG.warn('MeshQueue', `No assigned queue row matched completion for mesh ${meshId} session ${sessionId} `
1000
+ + `(taskId=${opts?.taskId ?? 'none'}, occurredAt=${occurredAtIso ?? 'none'}); `
1001
+ + `${assignedRows.length} assigned row(s) exist: ${assignedRows.map(r => r.id).join(',')}`);
1002
+ }
1003
+ return null;
279
1004
  }
280
- if (bestIdx === -1) return null;
281
- queue[bestIdx].status = status;
282
- queue[bestIdx].updatedAt = new Date().toISOString();
283
- writeQueue(meshId, queue);
284
- return queue[bestIdx];
1005
+ entry.status = status;
1006
+ store.updateQueueEntry(entry);
1007
+ if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
1008
+ return entry;
285
1009
  });
286
1010
  }
287
1011
 
1012
+ /**
1013
+ * M1-3: true when at least one pending task is waiting on the given task.
1014
+ * Used by the completion event path to decide whether to wake the queue.
1015
+ */
1016
+ export function hasPendingDependents(meshId: string, taskId: string): boolean {
1017
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId, ['pending'])
1018
+ .some(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(taskId));
1019
+ }
1020
+
1021
+ /**
1022
+ * M1-4: view-time dependency state for a task — unmet dependency ids and
1023
+ * whether the task is currently claimable from a dependency standpoint.
1024
+ * Not stored (truth stays in task statuses).
1025
+ */
1026
+ export function describeTaskDependencyState(
1027
+ entry: Pick<MeshWorkQueueEntry, 'dependsOn' | 'blockedReason'>,
1028
+ statusById: Map<string, MeshTaskStatus | string>,
1029
+ ): { waitingOn: string[]; dependenciesSatisfied: boolean } {
1030
+ const deps = Array.isArray(entry.dependsOn) ? entry.dependsOn : [];
1031
+ const waitingOn = deps.filter(depId => statusById.get(depId) !== 'completed');
1032
+ return {
1033
+ waitingOn,
1034
+ dependenciesSatisfied: waitingOn.length === 0 && !entry.blockedReason,
1035
+ };
1036
+ }
1037
+
288
1038
  export interface MeshWorkQueueStats {
289
1039
  total: number;
290
1040
  active: number;
@@ -310,14 +1060,16 @@ export interface MeshWorkQueueStats {
310
1060
  * Return aggregate queue statistics for the given mesh.
311
1061
  */
312
1062
  export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
313
- const queue = readQueue(meshId);
314
- const pending = queue.filter(q => q.status === 'pending').length;
315
- const assigned = queue.filter(q => q.status === 'assigned').length;
316
- const completed = queue.filter(q => q.status === 'completed').length;
317
- const failed = queue.filter(q => q.status === 'failed').length;
318
- const cancelled = queue.filter(q => q.status === 'cancelled').length;
1063
+ const rows = MeshRuntimeStore.getInstance().getQueueStatsByStatus(meshId);
1064
+ const counts: Record<string, number> = {};
1065
+ for (const r of rows) counts[r.status] = r.count;
1066
+ const pending = counts['pending'] ?? 0;
1067
+ const assigned = counts['assigned'] ?? 0;
1068
+ const completed = counts['completed'] ?? 0;
1069
+ const failed = counts['failed'] ?? 0;
1070
+ const cancelled = counts['cancelled'] ?? 0;
319
1071
  return {
320
- total: queue.length,
1072
+ total: pending + assigned + completed + failed + cancelled,
321
1073
  active: pending + assigned,
322
1074
  historical: completed + failed + cancelled,
323
1075
  pending,
@@ -325,22 +1077,126 @@ export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
325
1077
  completed,
326
1078
  failed,
327
1079
  cancelled,
328
- activeCounts: {
329
- pending,
330
- assigned,
331
- },
332
- historicalCounts: {
333
- completed,
334
- failed,
335
- cancelled,
336
- },
337
- activeAssignments: queue
338
- .filter(q => q.status === 'assigned')
339
- .map(q => ({
340
- id: q.id,
341
- nodeId: q.assignedNodeId,
342
- sessionId: q.assignedSessionId,
343
- message: q.message,
344
- })),
1080
+ activeCounts: { pending, assigned },
1081
+ historicalCounts: { completed, failed, cancelled },
1082
+ activeAssignments: MeshRuntimeStore.getInstance().getActiveAssignmentDetails(meshId),
345
1083
  };
346
1084
  }
1085
+
1086
+ export function __replaceMeshQueueForTests(meshId: string, queue: MeshWorkQueueEntry[]): void {
1087
+ MeshRuntimeStore.getInstance().transaction(() => {
1088
+ MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
1089
+ });
1090
+ }
1091
+
1092
+ export function __clearMeshQueueForTests(meshId: string): void {
1093
+ MeshRuntimeStore.getInstance().deleteQueue(meshId);
1094
+ }
1095
+
1096
+ export function __clearDirectDispatchesForTests(meshId: string): void {
1097
+ MeshRuntimeStore.getInstance().deleteDirectDispatches(meshId);
1098
+ }
1099
+
1100
+ export function __resetMeshRuntimeStoreForTests(): void {
1101
+ MeshRuntimeStore.resetForTests();
1102
+ }
1103
+
1104
+ // ── Direct Dispatch Tracking ─────────────────────────────────────────────────
1105
+ // Persists direct (non-queue) task dispatches so buildMeshActiveWork can read
1106
+ // active work from MeshRuntimeStore instead of scanning ledger JSONL entries.
1107
+
1108
+ export type DirectDispatchRecord = ReturnType<MeshRuntimeStore['getActiveDirectDispatches']>[number];
1109
+
1110
+ export function insertDirectDispatch(
1111
+ meshId: string,
1112
+ data: {
1113
+ taskId: string;
1114
+ nodeId?: string;
1115
+ sessionId?: string;
1116
+ providerType?: string;
1117
+ message: string;
1118
+ taskMode?: string;
1119
+ via: string;
1120
+ dispatchedToIdleSession?: boolean;
1121
+ dispatchedAt: string;
1122
+ },
1123
+ ): void {
1124
+ try {
1125
+ MeshRuntimeStore.getInstance().insertDirectDispatch({ ...data, meshId });
1126
+ } catch (e: any) {
1127
+ process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${data.taskId}: ${e?.message || e}\n`);
1128
+ }
1129
+ }
1130
+
1131
+ export function getActiveDirectDispatches(meshId: string): DirectDispatchRecord[] {
1132
+ try {
1133
+ return MeshRuntimeStore.getInstance().getActiveDirectDispatches(meshId);
1134
+ } catch {
1135
+ return [];
1136
+ }
1137
+ }
1138
+
1139
+ export function updateDirectDispatchStatus(
1140
+ meshId: string,
1141
+ sessionId: string,
1142
+ status: 'acked' | 'completed' | 'failed' | 'stale',
1143
+ taskId?: string,
1144
+ ): void {
1145
+ try {
1146
+ // CANON-B: prefer the exact task_id row; fall back to the session_id match only when
1147
+ // the firing event carried no taskId (a legacy/relayed event). Warn on the fallback so
1148
+ // the residual PK-substitute path is observable when it strands a sibling dispatch.
1149
+ if (!taskId) {
1150
+ LOG.warn('MeshQueue', `updateDirectDispatchStatus(${status}) for mesh ${meshId} session ${sessionId} has no taskId — falling back to session_id match (may flip a sibling dispatch row)`);
1151
+ }
1152
+ MeshRuntimeStore.getInstance().updateDirectDispatchStatus(meshId, sessionId, status, taskId);
1153
+ } catch { /* best-effort */ }
1154
+ }
1155
+
1156
+ export function cleanupTerminalDirectDispatches(olderThanMs = 7 * 24 * 60 * 60_000): void {
1157
+ try {
1158
+ MeshRuntimeStore.getInstance().cleanupTerminalDirectDispatches(olderThanMs);
1159
+ } catch { /* best-effort */ }
1160
+ }
1161
+
1162
+ export function markStaleDirectDispatches(meshId: string, olderThanMs = 60 * 60_000): void {
1163
+ try {
1164
+ MeshRuntimeStore.getInstance().markStaleDirectDispatches(meshId, olderThanMs);
1165
+ } catch { /* best-effort */ }
1166
+ }
1167
+
1168
+ /**
1169
+ * Delete specific direct dispatch rows by taskId. Returns the number of rows deleted.
1170
+ * Used by the staleDirect prune path to evict orphaned/terminal dispatch records from the
1171
+ * active staleDirect surface while leaving the append-only mesh ledger (audit history) intact.
1172
+ */
1173
+ export function deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
1174
+ try {
1175
+ return MeshRuntimeStore.getInstance().deleteDirectDispatchesByTaskId(meshId, taskIds);
1176
+ } catch {
1177
+ return 0;
1178
+ }
1179
+ }
1180
+
1181
+ export type MeshToolCallRateResult = { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null };
1182
+
1183
+ /**
1184
+ * Record a coordinator tool call and return a rate-limit advisory when the
1185
+ * call rate for that tool exceeds the allowed threshold.
1186
+ *
1187
+ * Defaults: 10-second sliding window, max 5 calls before advisory is raised.
1188
+ * Returns { rateLimitExceeded: false } on any store error so callers are not blocked.
1189
+ */
1190
+ export function recordMeshToolCall(opts: {
1191
+ meshId: string;
1192
+ tool: string;
1193
+ sessionId?: string | null;
1194
+ windowMs?: number;
1195
+ maxCalls?: number;
1196
+ }): MeshToolCallRateResult {
1197
+ try {
1198
+ return MeshRuntimeStore.getInstance().recordMeshToolCall(opts);
1199
+ } catch {
1200
+ return { rateLimitExceeded: false, callsInWindow: 0, advisory: null };
1201
+ }
1202
+ }