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

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