@adhdev/daemon-core 0.9.82-rc.41 → 0.9.82-rc.410

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