@adhdev/daemon-core 0.9.82-rc.40 → 0.9.82-rc.400

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