@adhdev/daemon-core 0.9.82-rc.43 → 0.9.82-rc.430

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 +100 -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 +49391 -19228
  75. package/dist/index.js.map +1 -1
  76. package/dist/index.mjs +48574 -18570
  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 +9 -0
  102. package/dist/mesh/mesh-init.d.ts +86 -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 +290 -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 +221 -3
  129. package/dist/providers/contracts.d.ts +139 -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 +501 -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 +544 -26
  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 +710 -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 +1066 -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 +2711 -3254
  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 +483 -24
  260. package/src/config/config.ts +12 -0
  261. package/src/config/mesh-config.ts +495 -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 +194 -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 +381 -33
  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 +1888 -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 +73 -0
  307. package/src/mesh/mesh-init.ts +260 -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 +1918 -0
  314. package/src/mesh/mesh-reconcile-loop.ts +1780 -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 +1243 -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 +1933 -104
  335. package/src/providers/contracts.d.ts +55 -0
  336. package/src/providers/contracts.ts +150 -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 +339 -0
  346. package/src/providers/native-history/hermes-cli-transcript.ts +230 -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 +504 -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 +1128 -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 +740 -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,523 @@
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
+ * M1: why this task is held back (e.g. "dependency_failed:<taskId>").
507
+ * Only set by the system on dependency failure under the 'block' policy;
508
+ * waiting-on-dependency state is computed at view time, not stored.
509
+ */
510
+ blockedReason?: string;
22
511
  /** The node that actually claimed and is executing the task */
23
512
  assignedNodeId?: string;
24
513
  /** The session currently executing the task */
25
514
  assignedSessionId?: string;
515
+ /**
516
+ * Provider type of the session that claimed the task. Recorded so the queue
517
+ * can enforce per-(node, provider) maxParallel caps (RepoMeshNodePolicy
518
+ * providerRoles) by counting active assignments grouped by node + provider.
519
+ */
520
+ assignedProviderType?: string;
26
521
  /** Human/operator reason for terminal cancellation. */
27
522
  cancelReason?: string;
28
523
  cancelledAt?: string;
@@ -30,6 +525,16 @@ export interface MeshWorkQueueEntry {
30
525
  requeueReason?: string;
31
526
  requeuedAt?: string;
32
527
  requeueCount?: number;
528
+ /** Max automatic requeue attempts. When requeueCount reaches this, task is auto-failed. */
529
+ maxRetries?: number;
530
+ /**
531
+ * Bug B: number of times the reconcile assigned-stranded watchdog has reclaimed this
532
+ * row from 'assigned' back to 'pending' because its dispatch was never confirmed
533
+ * delivered. Separate from requeueCount (operator/execution retries) and bounded by
534
+ * MAX_STRANDED_RECLAIMS so a permanently-undeliverable target auto-fails rather than
535
+ * cycling reclaim→re-dispatch→strand forever.
536
+ */
537
+ strandedReclaimCount?: number;
33
538
  /** Last automatic queue session spin-up attempt, for mesh_view_queue/debug visibility. */
34
539
  autoLaunch?: {
35
540
  status: 'skipped' | 'started' | 'failed' | 'completed';
@@ -41,54 +546,211 @@ export interface MeshWorkQueueEntry {
41
546
  };
42
547
  /** ISO timestamp when the task was dispatched (assigned) to a node/session. Used for precise matching on completion. */
43
548
  dispatchTimestamp?: string;
549
+ /**
550
+ * (3) The ORIGINATING coordinator session that enqueued this task. Stamped onto the
551
+ * worker at dispatch (meshCoordinatorSessionId) so the task's completion routes back to
552
+ * the exact coordinator session — even when several coordinator sessions share one
553
+ * daemon. Rides in the queue payload JSON (no column migration); absent on legacy rows
554
+ * → daemon-level routing fallback (backward + version-skew safe).
555
+ */
556
+ sourceCoordinatorSessionId?: string;
44
557
  createdAt: string;
45
558
  updatedAt: string;
46
559
  }
47
560
 
48
- function getQueuePath(meshId: string): string {
49
- const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
50
- return join(getLedgerDir(), `${safe}.queue.json`);
561
+ export interface MeshQueueMutationOptions {
562
+ ownerRole?: RepoMeshDaemonRole;
563
+ }
564
+
565
+ export function normalizeMeshCapabilityTags(value: unknown): string[] {
566
+ if (!Array.isArray(value)) return [];
567
+ const seen = new Set<string>();
568
+ return value
569
+ .map(tag => typeof tag === 'string' ? tag.trim() : '')
570
+ .filter(Boolean)
571
+ .filter(tag => {
572
+ if (seen.has(tag)) return false;
573
+ seen.add(tag);
574
+ return true;
575
+ });
576
+ }
577
+
578
+ function firstProviderPriority(policy: unknown): string | undefined {
579
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
580
+ ? (policy as Record<string, unknown>).providerPriority
581
+ : undefined;
582
+ if (!Array.isArray(raw)) return undefined;
583
+ return raw.find(type => typeof type === 'string' && type.trim())?.trim();
51
584
  }
52
585
 
53
- function getLockPath(meshId: string): string {
54
- const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
55
- return join(getLedgerDir(), `${safe}.queue.lock`);
586
+ function readNodeOverride(node: { userOverrides?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
587
+ const overrides = node?.userOverrides;
588
+ if (!overrides || typeof overrides !== 'object' || Array.isArray(overrides)) return null;
589
+ const value = (overrides as Record<string, unknown>)[key];
590
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
56
591
  }
57
592
 
58
593
  /**
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).
594
+ * Live, self-reported platform/arch the owning daemon stamped onto the node from
595
+ * its own process.platform/process.arch via the git_status envelope. Kept on a
596
+ * field DISTINCT from userOverrides so capability-tag derivation can prefer an
597
+ * explicit operator override while still self-healing auto-detected nodes — and
598
+ * so the value reflects the node's real OS rather than the coordinator's.
62
599
  */
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
- }
600
+ function readNodeReporter(node: { reportedPlatform?: unknown; reportedArch?: unknown } | undefined, key: 'platform' | 'arch'): string | null {
601
+ const value = key === 'platform' ? node?.reportedPlatform : node?.reportedArch;
602
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
76
603
  }
77
604
 
78
- function readQueue(meshId: string): MeshWorkQueueEntry[] {
79
- const path = getQueuePath(meshId);
80
- if (!existsSync(path)) return [];
605
+ export function buildMeshNodeCapabilityTags(
606
+ node: { capabilities?: unknown; policy?: unknown; isLocalWorktree?: unknown; worktreeBranch?: unknown; userOverrides?: unknown; reportedPlatform?: unknown; reportedArch?: unknown } | undefined,
607
+ providerType?: string,
608
+ ): string[] {
609
+ const provider = typeof providerType === 'string' && providerType.trim()
610
+ ? providerType.trim()
611
+ : firstProviderPriority(node?.policy);
612
+ const worktreeBranch = typeof node?.worktreeBranch === 'string' && node.worktreeBranch.trim()
613
+ ? node.worktreeBranch.trim()
614
+ : null;
615
+ // Per-node platform/arch precedence (highest → lowest):
616
+ // 1. userOverrides.platform/arch — an EXPLICIT operator override always wins.
617
+ // 2. reportedPlatform/reportedArch — the live OS the owning daemon
618
+ // self-reported (its own process.platform/process.arch via the git_status
619
+ // envelope), persisted to the node record on each direct probe. This is
620
+ // why a Windows member advertises os=win32 even though the COORDINATOR
621
+ // computing these tags runs on darwin — without it the consumer reads the
622
+ // persistent node (operator userOverrides empty) and would fall straight
623
+ // through to the coordinator's own process.platform, mislabeling every
624
+ // node os=darwin. We prefer this LIVE value over any stale auto-stamp.
625
+ // 3. process.platform/process.arch — last-resort fallback, correct only for
626
+ // the local coordinator node / local worktree nodes that have not yet
627
+ // been probed (their workspace lives on THIS machine anyway).
628
+ // Vocabulary is raw process.platform/process.arch ("darwin"/"win32"/"linux",
629
+ // "arm64"/"x64") on both the advertiser and the required_tags matcher, which
630
+ // compares with plain string equality (nodeSatisfiesRequiredTags) — so this
631
+ // keeps the win32/darwin/linux vocabulary the matcher already expects.
632
+ const os = readNodeOverride(node, 'platform') ?? readNodeReporter(node, 'platform') ?? process.platform;
633
+ const arch = readNodeOverride(node, 'arch') ?? readNodeReporter(node, 'arch') ?? process.arch;
634
+ return normalizeMeshCapabilityTags([
635
+ ...(Array.isArray(node?.capabilities) ? node.capabilities : []),
636
+ `os=${os}`,
637
+ `arch=${arch}`,
638
+ ...(provider ? [`provider=${provider}`] : []),
639
+ // Worktree nodes automatically expose a "worktree=<branch>" tag so that
640
+ // mesh_enqueue_task with required_tags: ["worktree=<branch>"] routes
641
+ // only to the matching worktree node.
642
+ ...(node?.isLocalWorktree === true && worktreeBranch ? [`worktree=${worktreeBranch}`] : []),
643
+ // Convergence routing: advertise how this node can land its work onto base.
644
+ // - converge=refine: local worktree nodes (on ANY machine — refine_mesh_node
645
+ // now forwards to the owning daemon) can run the Refinery merge → push →
646
+ // cleanup against their own checkout, so they accept code_change tasks.
647
+ // - converge=fast_forward: non-worktree nodes (the machine itself) can only
648
+ // ff/push an already-converged branch; they are NOT a destination for
649
+ // code_change work (a worktree is created first, and that worktree node
650
+ // receives the task instead). Reuses the ordinary required-tags filter —
651
+ // the load-balancing scheduler auto-injects converge=refine for code_change
652
+ // so such work is hard-filtered onto refine-capable nodes.
653
+ ...(node?.isLocalWorktree === true ? ['converge=refine'] : ['converge=fast_forward']),
654
+ ]);
655
+ }
656
+
657
+ export function nodeSatisfiesRequiredTags(requiredTags: unknown, capabilityTags: unknown): boolean {
658
+ const required = normalizeMeshCapabilityTags(requiredTags);
659
+ if (required.length === 0) return true;
660
+ const available = new Set(normalizeMeshCapabilityTags(capabilityTags));
661
+ return required.every(tag => available.has(tag));
662
+ }
663
+
664
+ /**
665
+ * Convergence-aware required-tags resolution (load-balancing scheduler, opt-in).
666
+ *
667
+ * When the mesh enables policy.autoConvergeCodeChange, a `converge=refine` required
668
+ * tag is merged into a code_change task's required tags at enqueue time, so the
669
+ * scheduler hard-filters the task onto refine-capable worktree nodes only (on any
670
+ * machine — refine_mesh_node forwards to the owning daemon). Because the tag is
671
+ * persisted on the queue entry, BOTH the eligibility scan (maybeAutoLaunchOneQueueSession)
672
+ * and the claim transaction (claimNextQueueTask → nodeSatisfiesRequiredTags) enforce
673
+ * it consistently.
674
+ *
675
+ * Strict backward compatibility — the injection is skipped (returns the explicit tags
676
+ * unchanged) when ANY of:
677
+ * - the mesh does not opt in (autoConvergeCodeChange !== true), or
678
+ * - the task is not code_change (validation / live_debug_readonly / launch_app /
679
+ * convergence carry no merge cost and may run anywhere), or
680
+ * - the task is explicitly targeted (targetNodeId): the operator chose the node, so
681
+ * we do not second-guess it by filtering on convergence capability.
682
+ * Idempotent: normalizeMeshCapabilityTags dedupes, so re-injection is a no-op.
683
+ */
684
+ export function resolveConvergeRequiredTags(
685
+ meshId: string,
686
+ taskMode: MeshTaskMode | undefined,
687
+ explicitRequiredTags: string[],
688
+ opts?: { targetNodeId?: string },
689
+ ): string[] {
690
+ if (taskMode !== 'code_change') return explicitRequiredTags;
691
+ if (typeof opts?.targetNodeId === 'string' && opts.targetNodeId.trim()) return explicitRequiredTags;
692
+ let optedIn = false;
81
693
  try {
82
- const content = readFileSync(path, 'utf-8');
83
- return JSON.parse(content) as MeshWorkQueueEntry[];
694
+ optedIn = resolveAutoConvergeCodeChange(getMesh(meshId)?.policy as any);
84
695
  } catch {
85
- return [];
696
+ optedIn = false;
86
697
  }
698
+ if (!optedIn) return explicitRequiredTags;
699
+ return normalizeMeshCapabilityTags([...explicitRequiredTags, MESH_CONVERGE_REFINE_TAG]);
700
+ }
701
+
702
+ function withQueueLock<T>(_meshId: string, fn: () => T): T {
703
+ return MeshRuntimeStore.getInstance().transaction(fn);
704
+ }
705
+
706
+ function readQueue(meshId: string): MeshWorkQueueEntry[] {
707
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId);
87
708
  }
88
709
 
89
710
  function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
90
- const path = getQueuePath(meshId);
91
- writeFileSync(path, JSON.stringify(queue, null, 2), 'utf-8');
711
+ MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
712
+ }
713
+
714
+ function normalizeDependsOn(value: unknown): string[] {
715
+ if (!Array.isArray(value)) return [];
716
+ const seen = new Set<string>();
717
+ return value
718
+ .map(id => typeof id === 'string' ? id.trim() : '')
719
+ .filter(Boolean)
720
+ .filter(id => {
721
+ if (seen.has(id)) return false;
722
+ seen.add(id);
723
+ return true;
724
+ });
725
+ }
726
+
727
+ /**
728
+ * M1: detect dependency cycles before enqueue. Walks the dependency graph of
729
+ * existing queue entries plus the new task's edges. Fail-closed: a cycle
730
+ * rejects the enqueue entirely. Synchronous and bounded by queue size.
731
+ */
732
+ export function assertNoDependencyCycle(meshId: string, newTaskId: string, dependsOn: string[]): void {
733
+ if (dependsOn.length === 0) return;
734
+ if (dependsOn.includes(newTaskId)) {
735
+ throw new Error(`dependency_cycle_detected: task '${newTaskId}' cannot depend on itself`);
736
+ }
737
+ const adjacency = new Map<string, string[]>();
738
+ for (const entry of readQueue(meshId)) {
739
+ adjacency.set(entry.id, normalizeDependsOn(entry.dependsOn));
740
+ }
741
+ adjacency.set(newTaskId, dependsOn);
742
+ // DFS from the new task: if we can reach newTaskId again, the edges form a cycle.
743
+ const stack = [...dependsOn];
744
+ const visited = new Set<string>();
745
+ while (stack.length > 0) {
746
+ const current = stack.pop()!;
747
+ if (current === newTaskId) {
748
+ throw new Error(`dependency_cycle_detected: task '${newTaskId}' is part of a dependency cycle via '${dependsOn.join(', ')}'`);
749
+ }
750
+ if (visited.has(current)) continue;
751
+ visited.add(current);
752
+ stack.push(...(adjacency.get(current) ?? []));
753
+ }
92
754
  }
93
755
 
94
756
  /**
@@ -97,22 +759,158 @@ function writeQueue(meshId: string, queue: MeshWorkQueueEntry[]): void {
97
759
  export function enqueueTask(
98
760
  meshId: string,
99
761
  message: string,
100
- opts?: { targetNodeId?: string; targetSessionId?: string }
762
+ opts?: {
763
+ targetNodeId?: string;
764
+ targetSessionId?: string;
765
+ taskMode?: MeshTaskMode | string;
766
+ /** QUEUE-NODE-SERIALIZATION: explicit read-only axis (orthogonal to taskMode). */
767
+ readonly?: boolean;
768
+ requiredTags?: string[];
769
+ /** M1: tasks that must complete before this one is claimable. */
770
+ dependsOn?: string[];
771
+ /** M1/M3: mission this task belongs to. */
772
+ missionId?: string;
773
+ /** MAGI: consensus group id shared by every replica of a mesh_magi_review fan-out. */
774
+ consensusGroupId?: string;
775
+ /** Explicit task id for batch/template flows (M5). Random UUID when omitted. */
776
+ id?: string;
777
+ /** (3) Originating coordinator session id (for session-anchored completion routing). */
778
+ sourceCoordinatorSessionId?: string;
779
+ } & MeshQueueMutationOptions,
101
780
  ): MeshWorkQueueEntry {
781
+ requireMeshHostQueueOwner(opts);
782
+ const readonly = opts?.readonly === true;
783
+ const modeValidation = validateMeshTaskModeRequest(opts?.taskMode, message, readonly);
784
+ if (!modeValidation.valid) {
785
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
786
+ }
787
+ const id = typeof opts?.id === 'string' && opts.id.trim() ? opts.id.trim() : randomUUID();
788
+ const dependsOn = normalizeDependsOn(opts?.dependsOn);
102
789
  return withQueueLock(meshId, () => {
103
- const queue = readQueue(meshId);
790
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, id)) {
791
+ throw new Error(`duplicate_task_id: task '${id}' already exists in mesh '${meshId}'`);
792
+ }
793
+ assertNoDependencyCycle(meshId, id, dependsOn);
794
+ const callerTags = normalizeMeshCapabilityTags(opts?.requiredTags);
795
+ // Convergence routing (opt-in): auto-inject converge=refine for code_change
796
+ // tasks so they hard-filter onto refine-capable worktree nodes. No-op unless
797
+ // the mesh opts in; explicit target_node_id / required_tags are preserved.
798
+ // Routing is otherwise governed solely by the caller's required_tags (hard
799
+ // filter through nodeSatisfiesRequiredTags) — no role/taskMode auto-routing.
800
+ const resolvedRequiredTags = resolveConvergeRequiredTags(
801
+ meshId,
802
+ modeValidation.taskMode,
803
+ callerTags,
804
+ { targetNodeId: opts?.targetNodeId },
805
+ );
104
806
  const entry: MeshWorkQueueEntry = {
105
- id: randomUUID(),
807
+ id,
106
808
  meshId,
107
809
  message,
108
810
  status: 'pending',
811
+ taskMode: modeValidation.taskMode,
812
+ ...(readonly ? { readonly: true } : {}),
109
813
  targetNodeId: opts?.targetNodeId,
110
814
  targetSessionId: opts?.targetSessionId,
815
+ requiredTags: resolvedRequiredTags,
816
+ ...(dependsOn.length > 0 ? { dependsOn } : {}),
817
+ ...(typeof opts?.missionId === 'string' && opts.missionId.trim() ? { missionId: opts.missionId.trim() } : {}),
818
+ ...(typeof opts?.consensusGroupId === 'string' && opts.consensusGroupId.trim() ? { consensusGroupId: opts.consensusGroupId.trim() } : {}),
819
+ ...(typeof opts?.sourceCoordinatorSessionId === 'string' && opts.sourceCoordinatorSessionId.trim()
820
+ ? { sourceCoordinatorSessionId: opts.sourceCoordinatorSessionId.trim() }
821
+ : {}),
111
822
  createdAt: new Date().toISOString(),
112
823
  updatedAt: new Date().toISOString(),
113
824
  };
114
- queue.push(entry);
115
- writeQueue(meshId, queue);
825
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
826
+ return entry;
827
+ });
828
+ }
829
+
830
+ /**
831
+ * Record a direct-dispatch task (mesh_send_task) as an already-assigned queue
832
+ * entry so it is attributable to a mission.
833
+ *
834
+ * Direct dispatch normally bypasses the queue entirely — the task lives only in
835
+ * the ledger + mesh_direct_dispatches table, neither of which carries a
836
+ * missionId, so {@link summarizeMissionTasks}/{@link computeMeshTaskStats}
837
+ * (which both scan the queue for `task.missionId`) count it as 0. When a
838
+ * mission is attached, we materialise the same queue entry shape an enqueued
839
+ * task would have, but pre-assigned to the dispatched node/session and stamped
840
+ * with the dispatch timestamp. The terminal event path (updateSessionTaskStatus
841
+ * → findAssignedBySession) then flips it to completed/failed exactly like a
842
+ * pulled task, so mission total + completed aggregates work with no extra wiring.
843
+ *
844
+ * Intentionally separate from {@link enqueueTask}: enqueue creates `pending`
845
+ * work for the queue to assign, whereas this records work already dispatched
846
+ * out-of-band. They share the missionId stamping rule and mode validation.
847
+ */
848
+ export function recordDirectDispatchTask(
849
+ meshId: string,
850
+ message: string,
851
+ opts: {
852
+ id: string;
853
+ missionId: string;
854
+ assignedNodeId?: string;
855
+ assignedSessionId?: string;
856
+ taskMode?: MeshTaskMode | string;
857
+ /** QUEUE-NODE-SERIALIZATION: explicit read-only axis (orthogonal to taskMode). */
858
+ readonly?: boolean;
859
+ dispatchedAt?: string;
860
+ },
861
+ ): MeshWorkQueueEntry | null {
862
+ const missionId = typeof opts.missionId === 'string' ? opts.missionId.trim() : '';
863
+ if (!missionId) return null;
864
+ const taskId = typeof opts.id === 'string' ? opts.id.trim() : '';
865
+ if (!taskId) return null;
866
+ const readonly = opts.readonly === true;
867
+ const modeValidation = validateMeshTaskModeRequest(opts.taskMode, message, readonly);
868
+ if (!modeValidation.valid) {
869
+ throw new Error(`live_debug_readonly_guardrail_violation: forbidden operations (${modeValidation.violations.join(', ')})`);
870
+ }
871
+ const now = opts.dispatchedAt && opts.dispatchedAt.trim() ? opts.dispatchedAt : new Date().toISOString();
872
+ return withQueueLock(meshId, () => {
873
+ if (MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId)) {
874
+ // Already materialised (e.g. retry of the same dispatch) — leave it untouched.
875
+ return null;
876
+ }
877
+ const entry: MeshWorkQueueEntry = {
878
+ id: taskId,
879
+ meshId,
880
+ message,
881
+ status: 'assigned',
882
+ ...(modeValidation.taskMode ? { taskMode: modeValidation.taskMode } : {}),
883
+ ...(readonly ? { readonly: true } : {}),
884
+ missionId,
885
+ ...(opts.assignedNodeId ? { targetNodeId: opts.assignedNodeId, assignedNodeId: opts.assignedNodeId } : {}),
886
+ ...(opts.assignedSessionId ? { targetSessionId: opts.assignedSessionId, assignedSessionId: opts.assignedSessionId } : {}),
887
+ dispatchTimestamp: now,
888
+ createdAt: now,
889
+ updatedAt: now,
890
+ };
891
+ MeshRuntimeStore.getInstance().insertQueueEntry(entry);
892
+ // R2 / NOTIF-DROP: a mission-attributed DIRECT dispatch (mesh_send_task) has
893
+ // already been handed to the transport by the time we materialise this assigned
894
+ // row — unlike a queue claim, there is no later delivery-confirmation write for
895
+ // it. Without a confirmed delivery record keyed by this taskId, the assigned-
896
+ // stranded watchdog (recoverStrandedAssignedDispatches → taskHasConfirmedDelivery)
897
+ // sees the row as never-confirmed after ASSIGNED_STRANDED_DEADLINE_MS and reclaims
898
+ // a task the worker already COMPLETED, dropping its agent:generating_completed
899
+ // (live PROBE-B repro: "never confirmed delivered → pending"). Record a confirmed
900
+ // delivery here so taskHasConfirmedDelivery() is true and the watchdog leaves the
901
+ // row to PHASE 4 completion reconcile. This point is only reached after the direct
902
+ // dispatch's result.success, so 'delivered' is the accurate state.
903
+ try {
904
+ createSessionDelivery({
905
+ meshId,
906
+ ...(opts.assignedNodeId ? { nodeId: opts.assignedNodeId } : {}),
907
+ ...(opts.assignedSessionId ? { sessionId: opts.assignedSessionId } : {}),
908
+ taskId,
909
+ kind: 'task',
910
+ message,
911
+ status: 'delivered',
912
+ });
913
+ } catch { /* best-effort — the assigned row is already recorded */ }
116
914
  return entry;
117
915
  });
118
916
  }
@@ -121,43 +919,83 @@ export function enqueueTask(
121
919
  * Get all tasks in the queue, optionally filtered by status.
122
920
  */
123
921
  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;
922
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId, opts?.status?.length ? opts.status : undefined);
923
+ }
924
+
925
+ export function getMeshQueueRevision(meshId: string): string {
926
+ return MeshRuntimeStore.getInstance().getQueueRevision(meshId);
130
927
  }
131
928
 
132
929
  /**
133
930
  * Find the next pending task that this node is allowed to claim, and mark it as assigned.
931
+ *
932
+ * `opts.providerType` is stamped onto the claimed entry (assignedProviderType) so
933
+ * per-(node, provider) caps can be counted. `opts.providerMaxParallel`, when set,
934
+ * is the enforced per-(node, provider) cap from RepoMeshNodePolicy.providerRoles:
935
+ * a task is not assigned to this (node, provider) once it already has that many
936
+ * active assignments. This composes with the global/taskMode caps (stricter wins).
134
937
  */
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);
938
+ export function claimNextTask(
939
+ meshId: string,
940
+ nodeId: string,
941
+ sessionId: string,
942
+ capabilityTags?: string[],
943
+ opts?: { providerType?: string; providerMaxParallel?: number; nodeIsWorktree?: boolean },
944
+ ): MeshWorkQueueEntry | null {
945
+ return MeshRuntimeStore.getInstance().claimNextQueueTask(meshId, nodeId, sessionId, capabilityTags, opts);
946
+ }
947
+
948
+ // ─── M1: Dependency Failure Propagation ─────────
949
+
950
+ export type DependencyFailurePolicy = 'block' | 'cancel';
951
+
952
+ function resolveDependencyFailurePolicy(meshId: string): DependencyFailurePolicy {
953
+ try {
954
+ const policy = (getMesh(meshId)?.policy ?? {}) as Record<string, unknown>;
955
+ return policy.onDependencyFailure === 'cancel' ? 'cancel' : 'block';
956
+ } catch {
957
+ return 'block';
958
+ }
959
+ }
960
+
961
+ /**
962
+ * Apply the mesh's onDependencyFailure policy to pending dependents of a task
963
+ * that just reached a failed/cancelled terminal state.
964
+ *
965
+ * - 'block' (default): dependents stay pending with blockedReason
966
+ * "dependency_failed:<taskId>" so an operator can requeue/cancel them.
967
+ * - 'cancel': dependents are cancelled (cascading to their own dependents).
968
+ *
969
+ * Must be called inside the queue lock of the triggering transition.
970
+ */
971
+ function propagateDependencyFailure(meshId: string, failedTaskId: string): void {
972
+ const policy = resolveDependencyFailurePolicy(meshId);
973
+ const store = MeshRuntimeStore.getInstance();
974
+ const frontier = [failedTaskId];
975
+ const seen = new Set<string>(frontier);
976
+ while (frontier.length > 0) {
977
+ const currentId = frontier.pop()!;
978
+ const dependents = store.getQueueEntries(meshId, ['pending'])
979
+ .filter(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(currentId));
980
+ for (const dependent of dependents) {
981
+ if (seen.has(dependent.id)) continue;
982
+ seen.add(dependent.id);
983
+ if (policy === 'cancel') {
984
+ dependent.status = 'cancelled';
985
+ dependent.cancelledAt = new Date().toISOString();
986
+ dependent.cancelReason = `dependency_failed:${currentId}`;
987
+ store.updateQueueEntry(dependent);
988
+ frontier.push(dependent.id); // cascade to transitive dependents
989
+ } else {
990
+ dependent.blockedReason = `dependency_failed:${currentId}`;
991
+ store.updateQueueEntry(dependent);
992
+ }
148
993
  }
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
- });
994
+ }
159
995
  }
160
996
 
997
+ const DEPENDENCY_FAILURE_TERMINALS = new Set<MeshTaskStatus>(['failed', 'cancelled']);
998
+
161
999
  /**
162
1000
  * Update the status of a specific task.
163
1001
  * Used when a session completes, fails, or stalls.
@@ -166,15 +1004,19 @@ export function updateTaskStatus(
166
1004
  meshId: string,
167
1005
  taskId: string,
168
1006
  status: MeshTaskStatus,
1007
+ opts?: MeshQueueMutationOptions,
169
1008
  ): MeshWorkQueueEntry | null {
1009
+ requireMeshHostQueueOwner(opts);
170
1010
  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];
1011
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
1012
+ if (!entry) return null;
1013
+ entry.status = status;
1014
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1015
+ // Any transition OFF `assigned` ends the single-flight dispatch window (terminal
1016
+ // completion/failure, or the dispatch-failure requeue to `pending`).
1017
+ if (status !== 'assigned') endTaskDispatchInFlight(meshId, taskId);
1018
+ if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, taskId);
1019
+ return entry;
178
1020
  });
179
1021
  }
180
1022
 
@@ -184,14 +1026,12 @@ export function recordTaskAutoLaunch(
184
1026
  autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>,
185
1027
  ): MeshWorkQueueEntry | null {
186
1028
  return withQueueLock(meshId, () => {
187
- const queue = readQueue(meshId);
188
- const idx = queue.findIndex(q => q.id === taskId);
189
- if (idx === -1) return null;
1029
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
1030
+ if (!entry) return null;
190
1031
  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];
1032
+ entry.autoLaunch = { ...autoLaunch, updatedAt: now };
1033
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1034
+ return entry;
195
1035
  });
196
1036
  }
197
1037
 
@@ -201,19 +1041,20 @@ export function recordTaskAutoLaunch(
201
1041
  export function cancelTask(
202
1042
  meshId: string,
203
1043
  taskId: string,
204
- opts?: { reason?: string },
1044
+ opts?: { reason?: string } & MeshQueueMutationOptions,
205
1045
  ): MeshWorkQueueEntry | null {
1046
+ requireMeshHostQueueOwner(opts);
206
1047
  return withQueueLock(meshId, () => {
207
- const queue = readQueue(meshId);
208
- const idx = queue.findIndex(q => q.id === taskId);
209
- if (idx === -1) return null;
1048
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
1049
+ if (!entry) return null;
210
1050
  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];
1051
+ entry.status = 'cancelled';
1052
+ entry.cancelledAt = now;
1053
+ if (opts?.reason) entry.cancelReason = opts.reason;
1054
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1055
+ endTaskDispatchInFlight(meshId, taskId);
1056
+ propagateDependencyFailure(meshId, taskId);
1057
+ return entry;
217
1058
  });
218
1059
  }
219
1060
 
@@ -221,6 +1062,11 @@ export function cancelTask(
221
1062
  * Return a queue task to pending for retry. By default, dead session targeting
222
1063
  * and assigned ownership are cleared so stale assignments do not strand again.
223
1064
  */
1065
+ export type RequeueResult =
1066
+ | { status: 'requeued'; entry: MeshWorkQueueEntry }
1067
+ | { status: 'failed_max_retries'; entry: MeshWorkQueueEntry; maxRetries: number; requeueCount: number }
1068
+ | { status: 'not_found' };
1069
+
224
1070
  export function requeueTask(
225
1071
  meshId: string,
226
1072
  taskId: string,
@@ -230,15 +1076,51 @@ export function requeueTask(
230
1076
  targetSessionId?: string;
231
1077
  clearTargetNode?: boolean;
232
1078
  clearTargetSession?: boolean;
233
- },
1079
+ /**
1080
+ * Override the retry cap for this call. Use only for explicit operator actions.
1081
+ * If true, the task is requeued even when requeueCount >= maxRetries.
1082
+ */
1083
+ force?: boolean;
1084
+ /** Per-task retry cap override. Falls back to mesh policy maxTaskRetries (default 1). */
1085
+ maxRetries?: number;
1086
+ } & MeshQueueMutationOptions,
234
1087
  ): MeshWorkQueueEntry | null {
1088
+ requireMeshHostQueueOwner(opts);
235
1089
  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();
1090
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
1091
+ if (!entry) return null;
1092
+ // CANON-IDENTITY single-flight: refuse (no-op) to reopen a task whose dispatch
1093
+ // is still in-flight — the worker is actively generating on it. Requeueing it
1094
+ // here would flip the row back to `pending` and let a SECOND session claim the
1095
+ // SAME task (the live `ade8586d` requeue-while-generating double-dispatch). A
1096
+ // STALE assigned row (dead session, dispatch never confirmed) is NOT in-flight
1097
+ // — its mark was cleared on the dispatch failure — so it still requeues as
1098
+ // before. An explicit operator override (`force`) bypasses this guard.
1099
+ // MAGI-NOTE: the future consensus group fan-out (separate mission) intentionally
1100
+ // re-dispatches a group-tagged task into multiple sessions and must be exempted
1101
+ // from this single-flight guard; the exemption hook (group-id check) belongs here.
1102
+ if (!opts?.force && isTaskDispatchInFlight(meshId, taskId)) {
1103
+ 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.`);
1104
+ return entry;
1105
+ }
1106
+ // Proceeding to requeue (or force-override): the prior dispatch is being abandoned,
1107
+ // so end the single-flight window for this task id.
1108
+ endTaskDispatchInFlight(meshId, taskId);
1109
+ const currentCount = entry.requeueCount || 0;
1110
+ const maxRetries = opts?.maxRetries ?? entry.maxRetries ?? 1;
1111
+ if (!opts?.force && currentCount >= maxRetries) {
1112
+ // Auto-fail: cap exceeded without explicit force override.
1113
+ entry.status = 'failed';
1114
+ entry.cancelReason = `max_retries_exceeded: requeued ${currentCount} time(s), limit is ${maxRetries}`;
1115
+ entry.updatedAt = new Date().toISOString();
1116
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1117
+ propagateDependencyFailure(meshId, taskId);
1118
+ return entry;
1119
+ }
241
1120
  entry.status = 'pending';
1121
+ // Operator requeue clears a dependency-failure block — the operator is
1122
+ // explicitly overriding the held-back state.
1123
+ delete entry.blockedReason;
242
1124
  delete entry.assignedNodeId;
243
1125
  delete entry.assignedSessionId;
244
1126
  delete entry.cancelledAt;
@@ -247,11 +1129,92 @@ export function requeueTask(
247
1129
  if (typeof opts?.targetNodeId === 'string') entry.targetNodeId = opts.targetNodeId;
248
1130
  if (opts?.clearTargetSession !== false) delete entry.targetSessionId;
249
1131
  if (typeof opts?.targetSessionId === 'string') entry.targetSessionId = opts.targetSessionId;
250
- entry.updatedAt = now;
251
- entry.requeuedAt = now;
252
- entry.requeueCount = (entry.requeueCount || 0) + 1;
1132
+ entry.requeuedAt = new Date().toISOString();
1133
+ entry.requeueCount = currentCount + 1;
253
1134
  if (opts?.reason) entry.requeueReason = opts.reason;
254
- writeQueue(meshId, queue);
1135
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1136
+ return entry;
1137
+ });
1138
+ }
1139
+
1140
+ /**
1141
+ * Max times the assigned-stranded watchdog will reclaim a single task before giving
1142
+ * up and failing it. Bounds the reclaim→re-dispatch→strand cycle so a permanently
1143
+ * undeliverable target (e.g. a node whose transport is wedged) eventually fails and
1144
+ * unblocks its dependents instead of looping every reconcile tick.
1145
+ */
1146
+ const MAX_STRANDED_RECLAIMS = 3;
1147
+
1148
+ /**
1149
+ * Bug B: reclaim a task stuck in 'assigned' because its dispatch was never confirmed.
1150
+ *
1151
+ * claimNextTask atomically marks a row 'assigned' BEFORE the fire-and-forget dispatch
1152
+ * runs. If that dispatch neither rejects (→ no .catch requeue) nor is confirmed
1153
+ * delivered — a relay that hangs without acking, or a confirm timer lost across a
1154
+ * daemon restart — the row stays 'assigned' forever, contributing 0 pending so PHASE 3
1155
+ * reconcile never re-examines it. This returns such a row to 'pending' and clears its
1156
+ * dead assignment ownership (node / session / provider / dispatchTimestamp) — the same
1157
+ * ownership-clear requeueTask applies — so PHASE 3 can re-dispatch it onto a fresh idle
1158
+ * session.
1159
+ *
1160
+ * Guarded to 'assigned' rows only (a completion/cancel that already moved the row off
1161
+ * 'assigned' must never be resurrected) and bounded by MAX_STRANDED_RECLAIMS (beyond
1162
+ * which the task is failed so dependents unblock).
1163
+ */
1164
+ export function reclaimStrandedAssignedTask(
1165
+ meshId: string,
1166
+ taskId: string,
1167
+ opts?: { reason?: string; ageMs?: number } & MeshQueueMutationOptions,
1168
+ ): MeshWorkQueueEntry | null {
1169
+ requireMeshHostQueueOwner(opts);
1170
+ return withQueueLock(meshId, () => {
1171
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(meshId, taskId);
1172
+ if (!entry) return null;
1173
+ // Only a still-assigned row is stranded. If a completion/cancel already moved it
1174
+ // off 'assigned', there is nothing to reclaim — never resurrect a terminal row.
1175
+ if (entry.status !== 'assigned') return null;
1176
+ const now = new Date().toISOString();
1177
+ const reason = opts?.reason || 'assigned_stranded_dispatch_unconfirmed';
1178
+ const reclaims = (entry.strandedReclaimCount || 0) + 1;
1179
+ const prevNode = entry.assignedNodeId;
1180
+ const prevSession = entry.assignedSessionId;
1181
+ // Always clear the dead assignment ownership so a re-claim starts clean and the
1182
+ // assigned-counters (which filter status==='assigned') stop counting this row.
1183
+ delete entry.assignedNodeId;
1184
+ delete entry.assignedSessionId;
1185
+ delete entry.assignedProviderType;
1186
+ delete entry.dispatchTimestamp;
1187
+ entry.strandedReclaimCount = reclaims;
1188
+ entry.updatedAt = now;
1189
+ // The stranded assignment is being torn down (→ pending or failed); end its
1190
+ // single-flight window so a re-claim/requeue is not blocked.
1191
+ endTaskDispatchInFlight(meshId, taskId);
1192
+ if (reclaims > MAX_STRANDED_RECLAIMS) {
1193
+ // Repeatedly undeliverable — stop cycling and fail it so dependents unblock.
1194
+ entry.status = 'failed';
1195
+ entry.cancelReason = `stranded_dispatch_unrecovered: reclaimed ${reclaims - 1} time(s) without a confirmed dispatch`;
1196
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1197
+ propagateDependencyFailure(meshId, taskId);
1198
+ } else {
1199
+ entry.status = 'pending';
1200
+ entry.requeuedAt = now;
1201
+ entry.requeueReason = reason;
1202
+ MeshRuntimeStore.getInstance().updateQueueEntry(entry);
1203
+ }
1204
+ try {
1205
+ appendLedgerEntry(meshId, {
1206
+ kind: 'task_reclaimed' as MeshLedgerKind,
1207
+ nodeId: prevNode,
1208
+ sessionId: prevSession,
1209
+ payload: {
1210
+ taskId,
1211
+ reason,
1212
+ ...(typeof opts?.ageMs === 'number' ? { ageMs: opts.ageMs } : {}),
1213
+ reclaimCount: reclaims,
1214
+ outcome: entry.status,
1215
+ },
1216
+ });
1217
+ } catch { /* ledger write is best-effort */ }
255
1218
  return entry;
256
1219
  });
257
1220
  }
@@ -263,28 +1226,61 @@ export function updateSessionTaskStatus(
263
1226
  meshId: string,
264
1227
  sessionId: string,
265
1228
  status: MeshTaskStatus,
266
- opts?: { occurredAt?: string },
1229
+ opts?: { occurredAt?: string; taskId?: string },
267
1230
  ): MeshWorkQueueEntry | null {
268
1231
  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; }
1232
+ const store = MeshRuntimeStore.getInstance();
1233
+ const occurredAtIso = opts?.occurredAt ? new Date(opts.occurredAt).toISOString() : undefined;
1234
+ const entry = store.findAssignedBySession(meshId, sessionId, occurredAtIso, opts?.taskId);
1235
+ if (!entry) {
1236
+ // C2: the silent null here is exactly what stranded a finished task as
1237
+ // `assigned` for 19 minutes. If the session still has an assigned row we
1238
+ // failed to resolve, surface it loudly instead of dropping the completion.
1239
+ const assignedRows = store.getActiveAssignmentDetails(meshId)
1240
+ .filter(r => r.sessionId === sessionId);
1241
+ if (assignedRows.length > 0) {
1242
+ LOG.warn('MeshQueue', `No assigned queue row matched completion for mesh ${meshId} session ${sessionId} `
1243
+ + `(taskId=${opts?.taskId ?? 'none'}, occurredAt=${occurredAtIso ?? 'none'}); `
1244
+ + `${assignedRows.length} assigned row(s) exist: ${assignedRows.map(r => r.id).join(',')}`);
1245
+ }
1246
+ return null;
279
1247
  }
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];
1248
+ entry.status = status;
1249
+ store.updateQueueEntry(entry);
1250
+ // The worker reported a terminal/non-assigned outcome — the dispatch is over;
1251
+ // release the single-flight mark so the task id can be re-dispatched later.
1252
+ if (status !== 'assigned') endTaskDispatchInFlight(meshId, entry.id);
1253
+ if (DEPENDENCY_FAILURE_TERMINALS.has(status)) propagateDependencyFailure(meshId, entry.id);
1254
+ return entry;
285
1255
  });
286
1256
  }
287
1257
 
1258
+ /**
1259
+ * M1-3: true when at least one pending task is waiting on the given task.
1260
+ * Used by the completion event path to decide whether to wake the queue.
1261
+ */
1262
+ export function hasPendingDependents(meshId: string, taskId: string): boolean {
1263
+ return MeshRuntimeStore.getInstance().getQueueEntries(meshId, ['pending'])
1264
+ .some(entry => Array.isArray(entry.dependsOn) && entry.dependsOn.includes(taskId));
1265
+ }
1266
+
1267
+ /**
1268
+ * M1-4: view-time dependency state for a task — unmet dependency ids and
1269
+ * whether the task is currently claimable from a dependency standpoint.
1270
+ * Not stored (truth stays in task statuses).
1271
+ */
1272
+ export function describeTaskDependencyState(
1273
+ entry: Pick<MeshWorkQueueEntry, 'dependsOn' | 'blockedReason'>,
1274
+ statusById: Map<string, MeshTaskStatus | string>,
1275
+ ): { waitingOn: string[]; dependenciesSatisfied: boolean } {
1276
+ const deps = Array.isArray(entry.dependsOn) ? entry.dependsOn : [];
1277
+ const waitingOn = deps.filter(depId => statusById.get(depId) !== 'completed');
1278
+ return {
1279
+ waitingOn,
1280
+ dependenciesSatisfied: waitingOn.length === 0 && !entry.blockedReason,
1281
+ };
1282
+ }
1283
+
288
1284
  export interface MeshWorkQueueStats {
289
1285
  total: number;
290
1286
  active: number;
@@ -310,14 +1306,16 @@ export interface MeshWorkQueueStats {
310
1306
  * Return aggregate queue statistics for the given mesh.
311
1307
  */
312
1308
  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;
1309
+ const rows = MeshRuntimeStore.getInstance().getQueueStatsByStatus(meshId);
1310
+ const counts: Record<string, number> = {};
1311
+ for (const r of rows) counts[r.status] = r.count;
1312
+ const pending = counts['pending'] ?? 0;
1313
+ const assigned = counts['assigned'] ?? 0;
1314
+ const completed = counts['completed'] ?? 0;
1315
+ const failed = counts['failed'] ?? 0;
1316
+ const cancelled = counts['cancelled'] ?? 0;
319
1317
  return {
320
- total: queue.length,
1318
+ total: pending + assigned + completed + failed + cancelled,
321
1319
  active: pending + assigned,
322
1320
  historical: completed + failed + cancelled,
323
1321
  pending,
@@ -325,22 +1323,126 @@ export function getMeshQueueStats(meshId: string): MeshWorkQueueStats {
325
1323
  completed,
326
1324
  failed,
327
1325
  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
- })),
1326
+ activeCounts: { pending, assigned },
1327
+ historicalCounts: { completed, failed, cancelled },
1328
+ activeAssignments: MeshRuntimeStore.getInstance().getActiveAssignmentDetails(meshId),
345
1329
  };
346
1330
  }
1331
+
1332
+ export function __replaceMeshQueueForTests(meshId: string, queue: MeshWorkQueueEntry[]): void {
1333
+ MeshRuntimeStore.getInstance().transaction(() => {
1334
+ MeshRuntimeStore.getInstance().replaceQueue(meshId, queue);
1335
+ });
1336
+ }
1337
+
1338
+ export function __clearMeshQueueForTests(meshId: string): void {
1339
+ MeshRuntimeStore.getInstance().deleteQueue(meshId);
1340
+ }
1341
+
1342
+ export function __clearDirectDispatchesForTests(meshId: string): void {
1343
+ MeshRuntimeStore.getInstance().deleteDirectDispatches(meshId);
1344
+ }
1345
+
1346
+ export function __resetMeshRuntimeStoreForTests(): void {
1347
+ MeshRuntimeStore.resetForTests();
1348
+ }
1349
+
1350
+ // ── Direct Dispatch Tracking ─────────────────────────────────────────────────
1351
+ // Persists direct (non-queue) task dispatches so buildMeshActiveWork can read
1352
+ // active work from MeshRuntimeStore instead of scanning ledger JSONL entries.
1353
+
1354
+ export type DirectDispatchRecord = ReturnType<MeshRuntimeStore['getActiveDirectDispatches']>[number];
1355
+
1356
+ export function insertDirectDispatch(
1357
+ meshId: string,
1358
+ data: {
1359
+ taskId: string;
1360
+ nodeId?: string;
1361
+ sessionId?: string;
1362
+ providerType?: string;
1363
+ message: string;
1364
+ taskMode?: string;
1365
+ via: string;
1366
+ dispatchedToIdleSession?: boolean;
1367
+ dispatchedAt: string;
1368
+ },
1369
+ ): void {
1370
+ try {
1371
+ MeshRuntimeStore.getInstance().insertDirectDispatch({ ...data, meshId });
1372
+ } catch (e: any) {
1373
+ process.stderr.write(`[adhdev-mesh] insertDirectDispatch failed for task ${data.taskId}: ${e?.message || e}\n`);
1374
+ }
1375
+ }
1376
+
1377
+ export function getActiveDirectDispatches(meshId: string): DirectDispatchRecord[] {
1378
+ try {
1379
+ return MeshRuntimeStore.getInstance().getActiveDirectDispatches(meshId);
1380
+ } catch {
1381
+ return [];
1382
+ }
1383
+ }
1384
+
1385
+ export function updateDirectDispatchStatus(
1386
+ meshId: string,
1387
+ sessionId: string,
1388
+ status: 'acked' | 'completed' | 'failed' | 'stale',
1389
+ taskId?: string,
1390
+ ): void {
1391
+ try {
1392
+ // CANON-B: prefer the exact task_id row; fall back to the session_id match only when
1393
+ // the firing event carried no taskId (a legacy/relayed event). Warn on the fallback so
1394
+ // the residual PK-substitute path is observable when it strands a sibling dispatch.
1395
+ if (!taskId) {
1396
+ 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)`);
1397
+ }
1398
+ MeshRuntimeStore.getInstance().updateDirectDispatchStatus(meshId, sessionId, status, taskId);
1399
+ } catch { /* best-effort */ }
1400
+ }
1401
+
1402
+ export function cleanupTerminalDirectDispatches(olderThanMs = 7 * 24 * 60 * 60_000): void {
1403
+ try {
1404
+ MeshRuntimeStore.getInstance().cleanupTerminalDirectDispatches(olderThanMs);
1405
+ } catch { /* best-effort */ }
1406
+ }
1407
+
1408
+ export function markStaleDirectDispatches(meshId: string, olderThanMs = 60 * 60_000): void {
1409
+ try {
1410
+ MeshRuntimeStore.getInstance().markStaleDirectDispatches(meshId, olderThanMs);
1411
+ } catch { /* best-effort */ }
1412
+ }
1413
+
1414
+ /**
1415
+ * Delete specific direct dispatch rows by taskId. Returns the number of rows deleted.
1416
+ * Used by the staleDirect prune path to evict orphaned/terminal dispatch records from the
1417
+ * active staleDirect surface while leaving the append-only mesh ledger (audit history) intact.
1418
+ */
1419
+ export function deleteDirectDispatchesByTaskId(meshId: string, taskIds: string[]): number {
1420
+ try {
1421
+ return MeshRuntimeStore.getInstance().deleteDirectDispatchesByTaskId(meshId, taskIds);
1422
+ } catch {
1423
+ return 0;
1424
+ }
1425
+ }
1426
+
1427
+ export type MeshToolCallRateResult = { rateLimitExceeded: boolean; callsInWindow: number; advisory: string | null };
1428
+
1429
+ /**
1430
+ * Record a coordinator tool call and return a rate-limit advisory when the
1431
+ * call rate for that tool exceeds the allowed threshold.
1432
+ *
1433
+ * Defaults: 10-second sliding window, max 5 calls before advisory is raised.
1434
+ * Returns { rateLimitExceeded: false } on any store error so callers are not blocked.
1435
+ */
1436
+ export function recordMeshToolCall(opts: {
1437
+ meshId: string;
1438
+ tool: string;
1439
+ sessionId?: string | null;
1440
+ windowMs?: number;
1441
+ maxCalls?: number;
1442
+ }): MeshToolCallRateResult {
1443
+ try {
1444
+ return MeshRuntimeStore.getInstance().recordMeshToolCall(opts);
1445
+ } catch {
1446
+ return { rateLimitExceeded: false, callsInWindow: 0, advisory: null };
1447
+ }
1448
+ }