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

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
@@ -0,0 +1,1738 @@
1
+ import { existsSync } from 'fs';
2
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
3
+ import { MESH_CONNECT_TIMEOUT_MS } from '../runtime-defaults.js';
4
+ import { loadConfig } from '../config/config.js';
5
+ import { getMesh } from '../config/mesh-config.js';
6
+ import { detectCLI } from '../detection/cli-detector.js';
7
+ import { LOG } from '../logging/logger.js';
8
+ import { appendLedgerEntry } from './mesh-ledger.js';
9
+ import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, getActiveDirectDispatches, isTaskReadonly } from './mesh-work-queue.js';
10
+ import type { MeshWorkQueueEntry } from './mesh-work-queue.js';
11
+ import { fastForwardMeshNode } from './mesh-fast-forward.js';
12
+ import { createSessionDelivery, updateSessionDeliveryStatus } from './mesh-delivery-policy.js';
13
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
14
+ import { traceMeshEventDrop } from './mesh-event-trace.js';
15
+ import { awaitWithWarmupDeadline, resolveWarmupDeadlineOpts } from './mesh-warmup-deadline.js';
16
+ import { resolveDelegatedWorkerAutoApprove, resolveProviderMaxParallel, resolveNodeSchedulingPriority, normalizeMeshSchedulingStrategy, resolveMaxParallelTasks, resolveMaxReadonlyParallelTasks, distributionToStrategy } from '../repo-mesh-types.js';
17
+ import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
18
+ import { loadMeshJsonConfig, type MeshJsonSchedulingConfig } from '../config/mesh-json-config.js';
19
+ import { normalizeMeshNodeId, meshNodeIdMatches, daemonIdsEquivalent, normalizeMeshWorkspaceForCompare, meshWorkspacesEquivalent, type MeshNodeIdentified } from '@adhdev/mesh-shared';
20
+ import { findTerminalLedgerEvidenceForTask, hasUnterminalDirectDispatchLedgerEntry } from './mesh-events-stale.js';
21
+ import { readNonEmptyString } from './mesh-events-utils.js';
22
+ import { queuePendingMeshCoordinatorEvent } from './mesh-events-pending.js';
23
+ import { isWorktreeBootstrapStaleRunning } from './worktree-bootstrap-config.js';
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Idle auto fast-forward throttle state
27
+ // ---------------------------------------------------------------------------
28
+ const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
29
+ const idleAutoFastForwardLastAttempt = new Map<string, number>();
30
+
31
+ export function __resetIdleAutoFastForwardForTests(): void {
32
+ idleAutoFastForwardLastAttempt.clear();
33
+ }
34
+
35
+ export function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
36
+ const localMesh = getMesh(meshId);
37
+ const cachedMesh = components.router?.getCachedInlineMesh(meshId);
38
+ if (!localMesh) return cachedMesh;
39
+ if (!cachedMesh) return localMesh;
40
+ return mergeInlineCacheOnlyNodes(localMesh, cachedMesh);
41
+ }
42
+
43
+ /**
44
+ * Claim-time membership view unification (CLAIMSTALL fix).
45
+ *
46
+ * The coordinator's claim path — triggerMeshQueue → autoLaunch candidate filter
47
+ * and the local/remote idle-session drain — reads mesh membership through
48
+ * getMeshWithCache, which historically returned the local-config mesh verbatim
49
+ * whenever one existed. A freshly cloned worktree node is registered ONLY into the
50
+ * router's inline mesh cache: clone_mesh_node's `meshRecord.inline` branch calls
51
+ * updateInlineMeshNode, NOT addNode, so the worktree node never reaches local
52
+ * config (meshes.json). The config-first view therefore omits the worktree node,
53
+ * while send_task — which resolves membership through getMeshForCommand(preferInline)
54
+ * over the same inline cache — sees it. That view asymmetry is the stall: a queue
55
+ * task pinned to the worktree node reports `target_node_id_unmatched` (autoLaunch
56
+ * candidate filter / targetPinUnmatched check) and the node's idle session is
57
+ * dropped from the drain pool (mesh.nodes.find miss), so claim never fires and the
58
+ * task is stranded pending — even though nodeId matching itself is correct.
59
+ *
60
+ * Fix: union the local-config nodes with any inline-cache-ONLY nodes, so the claim
61
+ * view matches the command (send_task) view. Base (non-worktree) nodes present in
62
+ * local config stay config-authoritative — their entry is taken verbatim from
63
+ * localMesh, so base node claim/matching is byte-for-byte unchanged. Only nodes
64
+ * that exist solely in the inline cache (the cloned worktree nodes) are appended.
65
+ * Identity comparison uses the shared 3-form normalizer (id / nodeId / node_id),
66
+ * identical to every other claim-path consumer — the matching logic is untouched,
67
+ * only which nodes are visible.
68
+ */
69
+ function mergeInlineCacheOnlyNodes(localMesh: any, cachedMesh: any): any {
70
+ const localNodes = Array.isArray(localMesh?.nodes) ? localMesh.nodes : [];
71
+ const cachedNodes = Array.isArray(cachedMesh?.nodes) ? cachedMesh.nodes : [];
72
+ if (!cachedNodes.length) return localMesh;
73
+ const cacheOnly = cachedNodes.filter((cachedNode: any) => {
74
+ const cachedId = readMeshNodeId(cachedNode);
75
+ // Unidentifiable cache entries can never be a claim/route target — skip them
76
+ // rather than appending junk that no consumer can address.
77
+ if (!cachedId) return false;
78
+ return !localNodes.some((localNode: any) => meshNodeIdMatches(localNode, cachedId));
79
+ });
80
+ if (!cacheOnly.length) return localMesh;
81
+ return { ...localMesh, nodes: [...localNodes, ...cacheOnly] };
82
+ }
83
+
84
+ // ---------------------------------------------------------------------------
85
+ // Queue assignment
86
+ // ---------------------------------------------------------------------------
87
+
88
+ // Per-dispatch confirmation timeout (Bug B). A dispatch promise that never settles —
89
+ // a saturated remote P2P relay that hangs, or a transport that resolves only after
90
+ // the worker acks — would otherwise leave the just-claimed queue row 'assigned' with
91
+ // its delivery stuck 'delivering' forever: the .catch that requeues never fires, and
92
+ // PHASE 3 reconcile skips the row (it counts 0 pending). Racing the dispatch against
93
+ // this timeout guarantees a hung dispatch deterministically returns the task to
94
+ // 'pending' for re-dispatch. Generous so a merely-slow-but-live dispatch (a cold
95
+ // remote relay) is never reclaimed early; the reconcile assigned-stranded watchdog is
96
+ // the durable cross-restart backstop for a timer lost to a daemon restart.
97
+ const DISPATCH_CONFIRM_TIMEOUT_MS = 120_000;
98
+
99
+ // Cold-open connect budget for the warmup-aware REMOTE task dispatch deadline. A
100
+ // remote `agent_command` to a peer whose mesh DataChannel is not open yet first has
101
+ // to drive the cross-machine (often TURN-relayed) handshake; charging that warmup
102
+ // against the response budget is the same cold-open false-timeout the git_status
103
+ // probe path already guards against. This budget bounds ONLY the "channel not open
104
+ // yet" phase; once the channel is warm the DISPATCH_CONFIRM_TIMEOUT_MS response
105
+ // budget governs (identical to the legacy flat guard for an already-open peer, so
106
+ // no latency is added to a normal dispatch). Matches the daemon-cloud
107
+ // DaemonMeshManager CONNECT_TIMEOUT_MS (45s) so the caller-side deadline tracks the
108
+ // transport's own cold-open window rather than guessing.
109
+ //
110
+ // Sourced from the unified, env-overridable MESH_CONNECT_TIMEOUT_MS (runtime-defaults)
111
+ // — the SAME budget the router's direct-peer git_status probe uses. Previously this
112
+ // was a hard-coded 45_000 while the probe path was env-overridable, so setting the
113
+ // env tuned the probe but silently left this dispatch path at 45s (a silent
114
+ // asymmetry). They now move together.
115
+ const DISPATCH_CONNECT_TIMEOUT_MS = MESH_CONNECT_TIMEOUT_MS;
116
+
117
+ // Fail-loud (throttled) trace for a remote dispatch that ran with NO live mesh
118
+ // connection getter wired — the same degraded-warmup misconfiguration the git probe
119
+ // path warns about. Warn once per peer; resolveWarmupDeadlineOpts then falls back to
120
+ // the conservative combined budget instead of silently assuming "always warm".
121
+ const dispatchWarmupGetterMissingWarned = new Set<string>();
122
+ function warnDispatchWarmupGetterMissingOnce(daemonId: string): void {
123
+ if (dispatchWarmupGetterMissingWarned.has(daemonId)) return;
124
+ dispatchWarmupGetterMissingWarned.add(daemonId);
125
+ LOG.warn('MeshQueue', `Mesh peer connection getter unavailable for ${String(daemonId).slice(0, 12)}; remote task-dispatch warmup deadline degraded to the combined connect+response window. Avoids a cold-open false-timeout but loses warm/cold precision — wire getMeshPeerConnectionStatus on this daemon.`);
126
+ }
127
+
128
+ interface DeliverTaskContext {
129
+ meshId: string;
130
+ nodeId: string;
131
+ sessionId: string;
132
+ providerType: string;
133
+ task: MeshWorkQueueEntry;
134
+ transport: 'remote' | 'local';
135
+ sourceCoordinatorSessionId?: string;
136
+ sourceCoordinatorDaemonId?: string;
137
+ }
138
+
139
+ // Readiness barrier for the LOCAL auto-launch path. A just-spawned CLI session is
140
+ // not interactive until its PTY prints the input prompt (the adapter flips
141
+ // isReady() / settles to idle ~2-6s later). Poll the local adapter until it reports
142
+ // ready (or idle), bounded by a generous timeout so a slow/contended boot still
143
+ // lands, and a hard cap so a session that never becomes interactive doesn't block the
144
+ // reconcile loop forever (the adapter's queue-until-ready path is the backstop then).
145
+ const LOCAL_LAUNCH_READY_TIMEOUT_MS = 15_000;
146
+ const LOCAL_LAUNCH_READY_POLL_MS = 100;
147
+
148
+ async function waitForLocalSessionReady(components: DaemonComponents, sessionId: string): Promise<void> {
149
+ const adapter = components.cliManager?.adapters?.get(sessionId) as
150
+ | { isReady?: () => boolean; currentStatus?: string }
151
+ | undefined;
152
+ // No locally-resolvable adapter (e.g. a remote/forwarded session that somehow
153
+ // reached this branch) → nothing to wait on; let dispatch proceed.
154
+ if (!adapter || typeof adapter.isReady !== 'function') return;
155
+ const deadline = Date.now() + LOCAL_LAUNCH_READY_TIMEOUT_MS;
156
+ while (Date.now() < deadline) {
157
+ if (adapter.isReady() || adapter.currentStatus === 'idle') return;
158
+ await new Promise<void>(resolve => setTimeout(resolve, LOCAL_LAUNCH_READY_POLL_MS));
159
+ }
160
+ LOG.warn('MeshQueue', `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
161
+ }
162
+
163
+ // CONS scope 3: the SINGLE source of truth for dispatching a claimed task to its
164
+ // session. The remote (P2P dispatchMeshCommand) and local (cliManager.handleCliCommand)
165
+ // branches differ ONLY in the transport call — the delivery record, the delivered/failed
166
+ // transitions, the pending-requeue-on-failure, the dispatch_failed ledger entry, AND the
167
+ // Bug B hang timeout are identical and live here once so a future change to the dispatch
168
+ // lifecycle cannot drift between the two paths. The caller passes a `dispatchThunk` that
169
+ // performs only the transport-specific send and returns its promise.
170
+ //
171
+ // Cold-open warmup (remote only): the REMOTE transport speaks over a P2P
172
+ // DataChannel that may still be opening when the first task is dispatched to a peer.
173
+ // When `warmup` is supplied the dispatch is awaited under the warmup-aware deadline
174
+ // (mesh-warmup-deadline) — the cold-open handshake is charged to the connect budget
175
+ // and only the warm round trip to the DISPATCH_CONFIRM_TIMEOUT_MS response budget —
176
+ // so the very first dispatch to a not-yet-open peer is no longer false-timed at the
177
+ // combined window. An already-open peer behaves identically to the legacy flat guard
178
+ // (response budget governs from t0), so a normal dispatch sees no added latency. The
179
+ // LOCAL transport (in-process cliManager) has no channel to warm up and keeps the
180
+ // flat Bug B hang guard.
181
+ function deliverTaskToSession(
182
+ dispatchThunk: () => Promise<unknown>,
183
+ ctx: DeliverTaskContext,
184
+ warmup?: { daemonId: string; getConnection?: (daemonId: string) => Record<string, unknown> | null },
185
+ ): void {
186
+ const delivery = createSessionDelivery({
187
+ meshId: ctx.meshId,
188
+ nodeId: ctx.nodeId,
189
+ sessionId: ctx.sessionId,
190
+ providerType: ctx.providerType,
191
+ taskId: ctx.task.id,
192
+ kind: 'task',
193
+ message: ctx.task.message,
194
+ status: 'delivering',
195
+ ...(ctx.sourceCoordinatorSessionId ? { sourceCoordinatorSessionId: ctx.sourceCoordinatorSessionId } : {}),
196
+ ...(ctx.sourceCoordinatorDaemonId ? { sourceCoordinatorDaemonId: ctx.sourceCoordinatorDaemonId } : {}),
197
+ });
198
+
199
+ // Invoke the transport synchronously (preserves the prior fire-and-forget timing,
200
+ // and lets a synchronous throw fall into the same failure path as a rejection).
201
+ let dispatchPromise: Promise<unknown>;
202
+ try {
203
+ dispatchPromise = Promise.resolve(dispatchThunk());
204
+ } catch (e) {
205
+ dispatchPromise = Promise.reject(e);
206
+ }
207
+
208
+ let timer: ReturnType<typeof setTimeout> | undefined;
209
+ let guarded: Promise<unknown>;
210
+ if (warmup) {
211
+ // Remote P2P: cold-open-aware deadline. awaitWithWarmupDeadline owns its own
212
+ // timers (so `timer` stays undefined and the clearTimeout below is a no-op),
213
+ // and rejects with Error('timeout') when either budget lapses — the same
214
+ // retryable failure shape the catch below already handles (requeue + ledger).
215
+ guarded = awaitWithWarmupDeadline(dispatchPromise, resolveWarmupDeadlineOpts({
216
+ getConnection: warmup.getConnection,
217
+ daemonId: warmup.daemonId,
218
+ connectTimeoutMs: DISPATCH_CONNECT_TIMEOUT_MS,
219
+ responseTimeoutMs: DISPATCH_CONFIRM_TIMEOUT_MS,
220
+ onMissingGetter: warnDispatchWarmupGetterMissingOnce,
221
+ }));
222
+ } else {
223
+ guarded = Promise.race([
224
+ dispatchPromise,
225
+ new Promise<never>((_, reject) => {
226
+ timer = setTimeout(
227
+ () => reject(new Error(`dispatch_confirm_timeout after ${DISPATCH_CONFIRM_TIMEOUT_MS}ms`)),
228
+ DISPATCH_CONFIRM_TIMEOUT_MS,
229
+ );
230
+ // Never keep the process alive solely for this confirm-timeout timer.
231
+ if (typeof (timer as { unref?: () => void })?.unref === 'function') (timer as { unref: () => void }).unref();
232
+ }),
233
+ ]);
234
+ }
235
+
236
+ guarded.then(() => {
237
+ if (timer) clearTimeout(timer);
238
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
239
+ }).catch((e: any) => {
240
+ if (timer) clearTimeout(timer);
241
+ // A dispatch failure (transport reject OR hang timeout) is most often transient —
242
+ // a busy/refusing adapter, or a relay that never acked — not a permanent task
243
+ // failure. Marking the task terminal here would permanently kill tasks a later
244
+ // tick delivers fine. Return it to 'pending' and record a retryable dispatch_failed
245
+ // ledger entry so the reconcile loop re-dispatches it. Identical for both transports.
246
+ LOG.error('MeshQueue', `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
247
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
248
+ updateTaskStatus(ctx.meshId, ctx.task.id, 'pending');
249
+ try {
250
+ appendLedgerEntry(ctx.meshId, {
251
+ kind: 'dispatch_failed' as any,
252
+ nodeId: ctx.nodeId,
253
+ sessionId: ctx.sessionId,
254
+ payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable: true, transport: ctx.transport },
255
+ });
256
+ } catch { /* ledger write is best-effort */ }
257
+ });
258
+ }
259
+
260
+ // WTCLAIM: workspace normalization for base-vs-worktree comparison now lives in
261
+ // @adhdev/mesh-shared (normalizeMeshWorkspaceForCompare) so the enqueue→claim path,
262
+ // the mesh_status per-node session filter, and the read_chat node scope guard all
263
+ // share one comparison rule instead of drifting module-private copies.
264
+
265
+ export function tryAssignQueueTask(
266
+ components: DaemonComponents,
267
+ meshId: string,
268
+ nodeId: string,
269
+ sessionId: string,
270
+ providerType: string
271
+ ): boolean {
272
+ const mesh = getMeshWithCache(components, meshId);
273
+ // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
274
+ // `n.id` — a stamp-form nodeId vs the mesh node's config-form id must still
275
+ // resolve, mirroring the remote idle-session path below (:1341).
276
+ const node = mesh?.nodes.find((n: any) => meshNodeIdMatches(n, nodeId));
277
+
278
+ // WORKTREE-CLAIM-GATE-BYPASS: the SINGLE claim-time gate for the worktree-bootstrap defer.
279
+ // tryAssignQueueTask is the one funnel every claim path flows through — the event-driven
280
+ // agent:ready drain, the triggerMeshQueue idle-session drain (local + remote), the
281
+ // auto-launch claim, and the PHASE 3 reconcile re-drain all call it. The agent:ready handler
282
+ // (mesh-event-forwarding) deferred its OWN claim while a worktree node's bootstrap was still
283
+ // 'running', but it ALSO called setRemoteIdleSession first — registering the session as a
284
+ // claim candidate. A concurrent triggerMeshQueue drain then pulled that candidate and claimed
285
+ // through tryAssignQueueTask within ~0.16s, BYPASSING the event-handler-local defer: the task
286
+ // dispatched into a half-built worktree (native addons not yet installed → child daemon dies
287
+ // → empty session, totalMessages=0). The transport ack returns ok:true, so neither the
288
+ // assigned-stranded watchdog nor the pending-only PHASE 3 reconcile ever re-fires it → the
289
+ // session is stranded empty forever.
290
+ //
291
+ // Lowering the gate HERE makes the defer a property of the claim itself, not of one caller:
292
+ // a worktree node whose bootstrap is still 'running' can never be claimed from any path. The
293
+ // task stays pending (we return false WITHOUT touching its status — no fail/cancel), so the
294
+ // bootstrap_complete refire (triggerMeshQueue re-fired on worktree_bootstrap_complete) re-runs
295
+ // this claim and passes once status is no longer 'running'. The registered remote-idle session
296
+ // persists for REMOTE_IDLE_SESSION_TTL_MS (5min > observed ~2m8s bootstrap), so the refire
297
+ // still finds a live candidate to re-claim. Identity uses meshNodeIdMatches (the same shared
298
+ // 3-form normalizer the defer guard uses), never a raw === — canon-identity regression guard.
299
+ // Conservative: any non-'running' status (idle/complete/failed/absent/unknown) does NOT gate,
300
+ // so a base node and a fully-bootstrapped worktree keep prior behavior exactly.
301
+ if ((node as { worktreeBootstrap?: { status?: string } } | undefined)?.worktreeBootstrap?.status === 'running') {
302
+ // Fix (3) safety net: a 'running' bootstrap that is far older than any real bootstrap AND
303
+ // whose worktree is git-clean is almost certainly one whose terminal-state stamp never
304
+ // reached this daemon — downgrade it so a dispatch is allowed instead of stranded forever.
305
+ // The conservative threshold + git-clean co-requirement prevents downgrading a genuinely
306
+ // in-progress bootstrap (which would re-introduce the half-built-worktree dispatch).
307
+ if (isWorktreeBootstrapStaleRunning(node)) {
308
+ LOG.warn('MeshQueue', `Worktree node ${nodeId} (${sessionId}) bootstrap stuck 'running' beyond the stale backstop and its worktree is git-clean — treating bootstrap as silently complete and allowing the claim (the terminal-state stamp likely never reached this daemon's mesh view)`);
309
+ } else {
310
+ LOG.info('MeshQueue', `Gating queue claim for worktree node ${nodeId} (${sessionId}): worktree bootstrap still running — task left pending; claim re-fires once bootstrap reaches a terminal state (guards against dispatching into a half-built worktree → empty session)`);
311
+ return false;
312
+ }
313
+ }
314
+
315
+ // WTCLAIM (fix-B extended to the enqueue→claim path): a base-targeted task must never be
316
+ // claimed by — and dispatched into — a co-located worktree-clone session, nor vice versa.
317
+ // The drain candidate's nodeId is derived from settings.meshNodeId || settings.nodeId
318
+ // (triggerMeshQueue), so a worktree session whose meshNodeId is empty/stale falls back to
319
+ // settings.nodeId = the BASE node id and impersonates the base node here. fix-B's worker-side
320
+ // workspace scope only ran for sessionless dispatch (meshScopeNodeId && !targetSessionId); the
321
+ // claim path ALWAYS carries a targetSessionId, so it never engaged. Apply the same scope here:
322
+ // for a LOCAL claiming session (adapter resolvable on this daemon), require its actual
323
+ // workingDir to match the target node's declared workspace. On a confirmed mismatch, refuse the
324
+ // claim so the task returns to pending for the correctly-scoped session/node to pull. Scoped to
325
+ // local sessions where the workspace is verifiable — a remote session lives on another daemon
326
+ // whose paths we cannot compare here (and remote candidates are already nodeId-matched from
327
+ // getRemoteIdleSessions). Conservative by design: when either workspace is unknown we do NOT
328
+ // skip, so a node with no declared workspace keeps its prior behavior and no legitimate claim
329
+ // is starved.
330
+ // WTDISPATCH (residual of WTCLAIM): the cross-node claim guard must reach EVERY claiming
331
+ // session this daemon can observe — not only those whose adapter happens to be in
332
+ // cliManager.adapters. An auto-launched worker session can carry its node binding on the
333
+ // CLI-instance settings while its session-host record shows no_node_binding, and the
334
+ // event-driven / remote-idle drain (agent:ready → setRemoteIdleSession → tryAssignQueueTask)
335
+ // can pass a nodeId that does NOT belong to the claiming session — a sibling worktree node
336
+ // on the SAME daemon. The adapter-only WTCLAIM check (rc.361/4c5b30b1) never engaged for a
337
+ // session observed solely via instanceManager, so session A could pull node B's task and
338
+ // node A's task was left with no session to claim it (no task_dispatched — it never dispatches).
339
+ //
340
+ // Resolve the claiming session's REAL identity from the adapter workingDir, then fall back to
341
+ // the live CLI instance's workspace + its stamped meshNodeId, and refuse a claim that
342
+ // contradicts EITHER (fail-closed). Reuses the shared meshWorkspacesEquivalent / meshNodeIdMatches
343
+ // comparators — no new comparison logic. Conservative: when neither the workspace NOR the stamp
344
+ // is resolvable we do NOT refuse, so a node with no declared workspace keeps prior behavior and
345
+ // a genuinely remote (cross-daemon) candidate stays nodeId-matched from getRemoteIdleSessions.
346
+ const localClaimAdapter = components.cliManager?.adapters?.get(sessionId) as { workingDir?: string } | undefined;
347
+ let claimInstanceWorkspace = '';
348
+ let claimStampedNodeId = '';
349
+ try {
350
+ const claimState = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
351
+ claimInstanceWorkspace = readNonEmptyString(claimState?.workspace);
352
+ const claimSettings = (claimState?.settings as Record<string, unknown>) || {};
353
+ claimStampedNodeId = readNonEmptyString(claimSettings.meshNodeId);
354
+ } catch { /* best-effort — fall through to the conservative (no refuse) path */ }
355
+
356
+ const nodeWorkspaceRaw = readNonEmptyString(node?.workspace);
357
+ const sessionWorkspaceRaw = readNonEmptyString(localClaimAdapter?.workingDir) || claimInstanceWorkspace;
358
+
359
+ if (claimStampedNodeId && nodeId) {
360
+ // The session carries its OWN meshNodeId stamp — its authoritative node identity, set when
361
+ // the coordinator launched/dispatched it (mesh-routing trusts this stamp FIRST). When it
362
+ // matches the claim target the session genuinely belongs to this node, so the stamp settles
363
+ // it and the workspace heuristic is skipped (a base/worktree pair can legitimately share a
364
+ // workspace). When it does NOT match, the claim is a cross-node leak — refuse, fail-closed.
365
+ if (!meshNodeIdMatches({ id: claimStampedNodeId } as MeshNodeIdentified, nodeId)) {
366
+ LOG.info('MeshQueue', `WTDISPATCH: refusing claim for node ${nodeId} (${sessionId}) — session is bound to node "${claimStampedNodeId}" (cross-node claim blocked)`);
367
+ return false;
368
+ }
369
+ } else if (sessionWorkspaceRaw && nodeWorkspaceRaw && !meshWorkspacesEquivalent(sessionWorkspaceRaw, nodeWorkspaceRaw)) {
370
+ // No stamp (the no_node_binding worker) — fall back to the workspace to tell two co-located
371
+ // sibling worktree sessions apart. WTCLAIM, now reaching instanceManager-observable sessions
372
+ // too. Conservative: unknown workspace on either side → do NOT refuse (no legitimate claim
373
+ // starved; a genuinely remote cross-daemon candidate stays nodeId-matched as before).
374
+ LOG.info('MeshQueue', `WTCLAIM: refusing claim for node ${nodeId} (${sessionId}) — session workspace "${normalizeMeshWorkspaceForCompare(sessionWorkspaceRaw)}" ≠ node workspace "${normalizeMeshWorkspaceForCompare(nodeWorkspaceRaw)}" (cross-workspace dispatch blocked)`);
375
+ return false;
376
+ }
377
+
378
+ const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
379
+ // Per-(node, provider) maxParallel cap (RepoMeshNodePolicy.providerRoles) layers
380
+ // on top of the global/taskMode caps — stricter wins. Resolved here where the
381
+ // claiming session's providerType + node policy are both known, then enforced
382
+ // inside the atomic claim transaction so concurrent claims can't overshoot it.
383
+ const providerMaxParallel = resolveProviderMaxParallel(node?.policy, providerType);
384
+ // WTDISPATCH-FANOUT: tell the atomic claim whether the claiming node is a worktree
385
+ // clone so a `convergence` task (base-only: merge → push → cleanup) is refused for
386
+ // worktree sessions. Without it, every sibling worktree session on this daemon could
387
+ // claim the same convergence intent and race push/production-deploy (the 4-way fan-out).
388
+ const nodeIsWorktree = node?.isLocalWorktree === true;
389
+ const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
390
+ providerType,
391
+ ...(providerMaxParallel !== undefined ? { providerMaxParallel } : {}),
392
+ nodeIsWorktree,
393
+ });
394
+ if (!task) {
395
+ return false;
396
+ }
397
+
398
+ const terminal = findTerminalLedgerEvidenceForTask({
399
+ meshId,
400
+ taskId: task.id,
401
+ });
402
+ if (terminal) {
403
+ const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
404
+ updateTaskStatus(meshId, task.id, status);
405
+ LOG.info('MeshQueue', `Skipped dispatch for terminal task ${task.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
406
+ traceMeshEventDrop('dispatch_terminal_ledger', {
407
+ taskId: task.id,
408
+ sessionId,
409
+ nodeId,
410
+ meshId,
411
+ event: 'agent_command',
412
+ }, terminal.kind);
413
+ return false;
414
+ }
415
+
416
+ LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
417
+
418
+ if (node?.daemonId && components.dispatchMeshCommand) {
419
+ const isLocalNode = components.cliManager.adapters.has(sessionId);
420
+ if (!isLocalNode) {
421
+ const localDaemonIdForDispatch = readNonEmptyString(loadConfig().machineId) || undefined;
422
+ // (3) Originating coordinator session that enqueued this task — route its
423
+ // completion back to that exact session (multi-coordinator). Carried over P2P
424
+ // to the remote worker, which echoes it on its completion event.
425
+ const sourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId) || undefined;
426
+ const dispatchMeshCommand = components.dispatchMeshCommand;
427
+ const remoteDaemonId = node.daemonId;
428
+ // CONS3: only the transport call differs — everything else (delivery record,
429
+ // status transitions, requeue-on-failure, ledger, Bug B hang timeout) is in
430
+ // the shared deliverTaskToSession helper.
431
+ deliverTaskToSession(
432
+ () => dispatchMeshCommand(remoteDaemonId, 'agent_command', {
433
+ targetSessionId: sessionId,
434
+ cliType: providerType,
435
+ action: 'send_chat',
436
+ message: task.message,
437
+ meshContext: {
438
+ meshId,
439
+ nodeId,
440
+ taskId: task.id,
441
+ ...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
442
+ ...(sourceCoordinatorSessionId ? { coordinatorSessionId: sourceCoordinatorSessionId } : {}),
443
+ },
444
+ }),
445
+ {
446
+ meshId,
447
+ nodeId,
448
+ sessionId,
449
+ providerType,
450
+ task,
451
+ transport: 'remote',
452
+ ...(sourceCoordinatorSessionId ? { sourceCoordinatorSessionId } : {}),
453
+ ...(localDaemonIdForDispatch ? { sourceCoordinatorDaemonId: localDaemonIdForDispatch } : {}),
454
+ },
455
+ // Warmup-aware deadline: this dispatch can be the FIRST command to a
456
+ // peer whose mesh DataChannel is still opening — charge the cold-open
457
+ // handshake to the connect budget, not the response budget.
458
+ { daemonId: remoteDaemonId, getConnection: components.getMeshPeerConnectionStatus },
459
+ );
460
+ return true;
461
+ }
462
+ }
463
+
464
+ // Stamp mesh context onto the session so completion events route correctly
465
+ // via setupMeshEventForwarding. Without this, manually-opened idle sessions
466
+ // (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
467
+ // agent:generating_completed is silently dropped as isMeshDelegate=false.
468
+ try {
469
+ const inst = components.instanceManager.getInstance(sessionId);
470
+ if (inst && typeof inst.updateSettings === 'function') {
471
+ // Adopting a (possibly manually-opened) local session as a worker: apply the
472
+ // delegated-worker auto-approve policy here too, so a session that was launched
473
+ // without autoApprove still auto-approves once the coordinator dispatches a task
474
+ // to it (the "approval notification fires only for certain delegated sessions"
475
+ // case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
476
+ //
477
+ // This local-dispatch branch also runs on the coordinator daemon for a co-located
478
+ // session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
479
+ // the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
480
+ // the anchor the forwarder keys on), matching what mesh_launch_session stamps.
481
+ const localDaemonId = readNonEmptyString(loadConfig().machineId);
482
+ const localSourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId);
483
+ inst.updateSettings({
484
+ meshNodeFor: meshId,
485
+ meshNodeId: nodeId,
486
+ launchedByCoordinator: true,
487
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
488
+ ...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
489
+ // (3) Stamp the originating coordinator session for session-anchored routing
490
+ // of this co-located worker's completion. Absent → daemon-level fallback.
491
+ ...(localSourceCoordinatorSessionId ? { meshCoordinatorSessionId: localSourceCoordinatorSessionId } : {}),
492
+ });
493
+ }
494
+ } catch { /* best-effort — dispatch still proceeds */ }
495
+
496
+ // CONS3: same shared dispatch lifecycle as the remote branch — only the transport
497
+ // (cliManager.handleCliCommand) differs.
498
+ // ARCH-REFACTOR R1: carry meshContext (incl. taskId) on the LOCAL dispatch too, so
499
+ // handleCliCommand's send_chat path binds this task to its turn (per-turn identity).
500
+ // Previously only the remote branch shipped meshContext.taskId; the local path relied
501
+ // on the last-write-wins session scalar, which races a follow-up task and made the
502
+ // completion echo the wrong taskId (the standalone NOTIF-MISDELIVER repro).
503
+ deliverTaskToSession(
504
+ () => components.cliManager.handleCliCommand('agent_command', {
505
+ targetSessionId: sessionId,
506
+ cliType: providerType,
507
+ action: 'send_chat',
508
+ message: task.message,
509
+ meshContext: {
510
+ meshId,
511
+ nodeId,
512
+ taskId: task.id,
513
+ ...(readNonEmptyString(loadConfig().machineId) ? { coordinatorDaemonId: readNonEmptyString(loadConfig().machineId) } : {}),
514
+ ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { coordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
515
+ },
516
+ }),
517
+ {
518
+ meshId,
519
+ nodeId,
520
+ sessionId,
521
+ providerType,
522
+ task,
523
+ transport: 'local',
524
+ ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
525
+ ...(readNonEmptyString(loadConfig().machineId) ? { sourceCoordinatorDaemonId: readNonEmptyString(loadConfig().machineId) } : {}),
526
+ },
527
+ );
528
+
529
+ return true;
530
+ }
531
+
532
+ const autoLaunchInProgress = new Set<string>();
533
+ const autoLaunchCooldownUntil = new Map<string, number>();
534
+ const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
535
+ // A remote auto-launch (launch_cli forward) is fire-and-async: the worker session
536
+ // spawns, reaches idle, emits agent:ready, that ready is queued on the worker, pulled
537
+ // by this coordinator (reconcile PHASE 1), and only THEN claims the task. That round
538
+ // trip routinely exceeds the 5s per-(mesh,node) cooldown, so cooldown alone lets the
539
+ // reconcile loop fire a SECOND launch for the same still-pending task before the first
540
+ // session's claim lands — every tick spawns yet another orphan session (observed live:
541
+ // 26 sessions for one task). This is a per-TASK await-claim window: once a task has a
542
+ // successfully-launched session whose claim we are still waiting on, do not launch it
543
+ // again until the window lapses. It is generous (a slow remote spawn can take tens of
544
+ // seconds) but bounded so a launch that silently never reaches idle is eventually retried.
545
+ const AUTO_LAUNCH_AWAIT_CLAIM_MS = 90_000;
546
+
547
+ // De-dup for repeated `skipped` ledger noise: the reconcile loop re-runs the queue
548
+ // trigger every 4s, so a task that can't be claimed (e.g. a remote node with no
549
+ // transport, or a node under cooldown) would otherwise append an identical
550
+ // session_auto_launch{phase:'skipped'} entry on every tick — flooding the ledger.
551
+ // We suppress a `skipped` ledger append when the immediately-prior recorded event
552
+ // for that task was the SAME (phase, reason). Any non-skip phase (started/failed/
553
+ // completed) or a changed reason resets the de-dup so real transitions still record.
554
+ const lastAutoLaunchLedgerKey = new Map<string, string>();
555
+ const AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2000;
556
+
557
+ // Fix (1): actionable dispatch-skip notification.
558
+ //
559
+ // User-core gap: when a queued task cannot be dispatched the coordinator (Claude Code via
560
+ // MCP) had no proactive signal — the skip was only recorded to task.autoLaunch + the ledger,
561
+ // both of which the coordinator must poll to discover. For a skip that will NOT self-resolve
562
+ // (a routing miss, no capable node, a convergence task pinned to a worktree, an unusable
563
+ // provider, an unreachable remote, or a dirty workspace) the coordinator could sit waiting
564
+ // for a dispatch that can never happen. We now actively surface those — and ONLY those — as a
565
+ // pending coordinator event carrying a "why + how to act" message, routed to the originating
566
+ // coordinator (sourceCoordinator*). Transient/back-pressure skips (cooldown, in-progress,
567
+ // awaiting-claim, parallel/session caps, node not yet launch-ready, an active assignment) are
568
+ // deliberately excluded: they clear on their own and would only spam the coordinator every 4s.
569
+ const ACTIONABLE_SKIP_REASON_PREFIXES = [
570
+ 'target_node_id_unmatched',
571
+ 'no_node_satisfies_required_tags',
572
+ 'mesh_convergence_target_is_worktree',
573
+ 'remote_auto_launch_unsupported',
574
+ 'remote_auto_launch_no_coordinator_daemon_id',
575
+ 'missing_provider_priority',
576
+ 'provider_loader_unavailable',
577
+ 'provider_priority_unusable',
578
+ 'provider_unusable',
579
+ 'dirty_workspace',
580
+ ];
581
+
582
+ // De-dup actionable-skip coordinator notifications: emit once per (mesh, task) until the
583
+ // reason CHANGES, so the 4s reconcile loop re-marking the same skip does not re-notify. A
584
+ // non-skip transition (or a genuine reason change) re-arms it. In-memory only — a daemon
585
+ // restart re-notifies once, which is the correct behaviour after a restart.
586
+ const lastActionableSkipNotified = new Map<string, string>();
587
+
588
+ function isActionableSkipReason(reason?: string): boolean {
589
+ if (!reason) return false;
590
+ return ACTIONABLE_SKIP_REASON_PREFIXES.some(prefix => reason === prefix || reason.startsWith(prefix));
591
+ }
592
+
593
+ function actionableSkipGuidance(reason: string): { summary: string; nextAction: string } {
594
+ if (reason === 'target_node_id_unmatched') return {
595
+ summary: 'it is pinned to a target node id that matches no node in the mesh (the node may have been removed, or its id form does not resolve)',
596
+ nextAction: 'Verify the target node still exists with mesh_status, then re-enqueue without the node pin or with a valid node id (or re-clone the node).',
597
+ };
598
+ if (reason === 'no_node_satisfies_required_tags') return {
599
+ summary: "no node in the mesh can satisfy the task's required capability tags",
600
+ nextAction: "Relax the task's requiredTags, or add/launch a node whose provider produces the required capabilities.",
601
+ };
602
+ if (reason === 'mesh_convergence_target_is_worktree') return {
603
+ summary: 'it is a convergence task (base-only: merge → push → cleanup) but every candidate node is a worktree clone',
604
+ nextAction: 'Dispatch the convergence task to the base node, or run the deterministic fast-forward path (mesh_fast_forward_node / mesh_refine_node) instead.',
605
+ };
606
+ if (reason.startsWith('remote_auto_launch')) return {
607
+ summary: 'the target node is on a remote daemon this coordinator cannot auto-launch a session on (no dispatch transport, or no coordinator daemon id to stamp)',
608
+ nextAction: 'Launch a session on that node yourself with mesh_launch_session, or ensure the remote daemon is connected over P2P.',
609
+ };
610
+ if (reason.startsWith('provider') || reason === 'missing_provider_priority') return {
611
+ summary: 'the node has no usable provider for this task (provider priority missing/unusable, or the provider loader is unavailable)',
612
+ nextAction: "Check the node's providerPriority policy and that the required CLI/ACP provider is installed and enabled on that machine.",
613
+ };
614
+ if (reason === 'dirty_workspace') return {
615
+ summary: "the node's workspace is dirty, so auto-launch is blocked to avoid clobbering uncommitted changes",
616
+ nextAction: "Clean or commit the node's working tree (or fast-forward it); the task will then auto-assign.",
617
+ };
618
+ return {
619
+ summary: `it cannot be dispatched (${reason})`,
620
+ nextAction: 'Inspect the node/mesh state with mesh_status and resolve the blocker, or re-enqueue the task.',
621
+ };
622
+ }
623
+
624
+ /** Surface a non-self-resolving dispatch skip to the originating coordinator as a pending
625
+ * event (so it is delivered actively, not only on poll). De-duped per (mesh, task, reason). */
626
+ function notifyCoordinatorOfActionableSkip(meshId: string, taskId: string, reason: string | undefined, nodeId?: string): void {
627
+ if (!isActionableSkipReason(reason)) return;
628
+ const dedupKey = `${meshId}:${taskId}`;
629
+ if (lastActionableSkipNotified.get(dedupKey) === reason) return;
630
+ lastActionableSkipNotified.set(dedupKey, reason!);
631
+ if (lastActionableSkipNotified.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
632
+ const oldest = lastActionableSkipNotified.keys().next().value;
633
+ if (oldest !== undefined) lastActionableSkipNotified.delete(oldest);
634
+ }
635
+ let task: MeshWorkQueueEntry | undefined;
636
+ try { task = getQueue(meshId).find(t => t.id === taskId); } catch { /* best-effort */ }
637
+ // The queue is owned by this coordinator daemon, so scope the event to this daemon's id;
638
+ // the originating coordinator SESSION (if known) further narrows delivery on this daemon.
639
+ const targetCoordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
640
+ const targetCoordinatorSessionId = readNonEmptyString(task?.sourceCoordinatorSessionId);
641
+ const nodeLabel = readNonEmptyString(nodeId) || readNonEmptyString(task?.targetNodeId);
642
+ const { summary, nextAction } = actionableSkipGuidance(reason!);
643
+ const coordinatorMessage = `[System] A queued mesh task${nodeLabel ? ` for node ${nodeLabel}` : ''} is not being dispatched because ${summary}. ${nextAction} This is an actionable blocker — it will NOT clear on its own; the task stays pending until you resolve it.`;
644
+ try {
645
+ queuePendingMeshCoordinatorEvent({
646
+ event: 'mesh:dispatch_blocked',
647
+ meshId,
648
+ nodeLabel: nodeLabel || meshId,
649
+ ...(nodeLabel ? { nodeId: nodeLabel } : {}),
650
+ metadataEvent: {
651
+ source: 'mesh_queue_dispatch_skip',
652
+ taskId,
653
+ reason,
654
+ ...(nodeLabel ? { nodeId: nodeLabel } : {}),
655
+ coordinatorMessage,
656
+ },
657
+ coordinatorMessage,
658
+ queuedAt: Date.now(),
659
+ ...(targetCoordinatorDaemonId ? { targetCoordinatorDaemonId } : {}),
660
+ ...(targetCoordinatorSessionId ? { targetCoordinatorSessionId } : {}),
661
+ });
662
+ } catch (e: any) {
663
+ LOG.warn('MeshQueue', `Failed to surface actionable dispatch-skip (${reason}) for task ${taskId}: ${e?.message || e}`);
664
+ }
665
+ }
666
+
667
+ function sweepExpiredCooldowns(): void {
668
+ const now = Date.now();
669
+ for (const [key, until] of autoLaunchCooldownUntil) {
670
+ if (now >= until) autoLaunchCooldownUntil.delete(key);
671
+ }
672
+ }
673
+
674
+ function normalizeProviderPriority(policy: unknown): string[] {
675
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
676
+ ? (policy as Record<string, unknown>).providerPriority
677
+ : undefined;
678
+ if (!Array.isArray(raw)) return [];
679
+ const seen = new Set<string>();
680
+ return raw
681
+ .map(type => typeof type === 'string' ? type.trim() : '')
682
+ .filter(Boolean)
683
+ .filter(type => {
684
+ if (seen.has(type)) return false;
685
+ seen.add(type);
686
+ return true;
687
+ });
688
+ }
689
+
690
+ function isTerminalSessionStatus(status: string): boolean {
691
+ return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
692
+ }
693
+
694
+ function isIdleSessionState(state: any): boolean {
695
+ const status = readNonEmptyString(state?.status).toLowerCase();
696
+ if (isTerminalSessionStatus(status)) return false;
697
+ return status === 'idle' || state?.activeChat?.status === 'waiting_input';
698
+ }
699
+
700
+ function isDirtyNode(node: any): boolean {
701
+ return node?.health === 'dirty' || node?.git?.dirty === true;
702
+ }
703
+
704
+ function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
705
+ const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
706
+ ? mesh.policy.autoFastForward as Record<string, unknown>
707
+ : {};
708
+ const maxBehind = Number(record.maxBehind);
709
+ return {
710
+ enabled: record.enabled !== false,
711
+ ...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
712
+ requireCleanSubmodules: record.requireCleanSubmodules !== false,
713
+ };
714
+ }
715
+
716
+ function sessionStateLooksActive(state: any): boolean {
717
+ const status = readNonEmptyString(state?.status).toLowerCase();
718
+ const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
719
+ // 'long_generating' is retained as a legacy alias for the renamed 'no_progress' busy status.
720
+ const active = new Set(['generating', 'streaming', 'no_progress', 'long_generating', 'working', 'starting', 'waiting_approval']);
721
+ return active.has(status) || active.has(chatStatus);
722
+ }
723
+
724
+ function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
725
+ if (nodeHasActiveAssignment(meshId, nodeId)) return true;
726
+ return components.instanceManager.getByCategory('cli').some((inst: any) => {
727
+ const state = inst.getState();
728
+ const settings = state.settings as Record<string, unknown> || {};
729
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
730
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
731
+ if (instNodeId !== nodeId) return false;
732
+ const sessionId = readNonEmptyString(state.instanceId);
733
+ if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
734
+ return sessionStateLooksActive(state);
735
+ });
736
+ }
737
+
738
+ function isLaunchableNode(node: any): boolean {
739
+ if (!node || node.status === 'disabled' || node.status === 'removed') return false;
740
+ const health = readNonEmptyString(node.health).toLowerCase();
741
+ if (!health) return true;
742
+ return health === 'online' || health === 'unknown';
743
+ }
744
+
745
+ /** Whether a mesh node's daemon/machine identity resolves to THIS coordinator daemon
746
+ * (i.e. the queue session can be spawned by a direct local `launch_cli`). */
747
+ function isLocalAutoLaunchNode(node: any): boolean {
748
+ const daemonId = readNonEmptyString(node?.daemonId);
749
+ const machineId = readNonEmptyString(node?.machineId);
750
+ const appConfig = loadConfig();
751
+ const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
752
+
753
+ // Route BOTH the daemonId and the machineId through the canonical machine-core
754
+ // equivalence helper so a node carrying any interchangeable id form (bare `mach_<hex>`
755
+ // or a `daemon_`/`standalone_` prefixed form) resolves to THIS coordinator instead of
756
+ // being misjudged as remote. machineId used to use a raw `===`, which — AND-combined
757
+ // with the daemonId match — would misjudge a local node as remote whenever a
758
+ // form-mismatched machineId arrived, dispatching a local task to a remote node (B-2).
759
+ const daemonMatchesLocal = !daemonId || daemonIdsEquivalent(daemonId, localMachineId);
760
+ const machineMatchesLocal = !machineId || daemonIdsEquivalent(machineId, localMachineId);
761
+
762
+ if (node?.isLocalWorktree === true) {
763
+ return daemonMatchesLocal && machineMatchesLocal;
764
+ }
765
+ if (daemonId || machineId) {
766
+ return daemonMatchesLocal && machineMatchesLocal;
767
+ }
768
+ return true;
769
+ }
770
+
771
+ /**
772
+ * Resolve how a pending queue task should be auto-launched onto a node.
773
+ *
774
+ * - `local`: spawn directly on this daemon via cliManager.handleCliCommand('launch_cli').
775
+ * - `remote`: forward `launch_cli` to the node's daemon via dispatchMeshCommand
776
+ * (mirrors what mesh_launch_session does). Requires dispatchMeshCommand AND a
777
+ * resolvable coordinator daemonId for relay-safe completion routing.
778
+ * - `skip`: not launchable from here — carries the reason (e.g. a remote node with
779
+ * no dispatch transport, or no coordinator daemonId to stamp).
780
+ */
781
+ function resolveAutoLaunchTarget(components: DaemonComponents, node: any): {
782
+ mode: 'local' | 'remote' | 'skip';
783
+ reason?: string;
784
+ daemonId?: string;
785
+ coordinatorDaemonId?: string;
786
+ } {
787
+ if (isLocalAutoLaunchNode(node)) return { mode: 'local' };
788
+
789
+ // Remote node. Forwarding the launch is possible only with a dispatch transport
790
+ // (cloud mode) plus a coordinator daemonId to stamp into the worker so completion
791
+ // events route back here. Without either, fall back to a graceful skip.
792
+ const daemonId = readNonEmptyString(node?.daemonId);
793
+ if (!daemonId) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
794
+ if (!components.dispatchMeshCommand) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
795
+ const coordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
796
+ if (!coordinatorDaemonId) return { mode: 'skip', reason: 'remote_auto_launch_no_coordinator_daemon_id' };
797
+ return { mode: 'remote', daemonId, coordinatorDaemonId };
798
+ }
799
+
800
+ function activeAssignedCount(meshId: string): number {
801
+ return getQueue(meshId, { status: ['assigned'] as any }).length;
802
+ }
803
+
804
+ /** Active assignments that hold the one-active-per-node / global-parallel invariant
805
+ * (everything except read-only diagnoses, which run unbounded by the write cap). */
806
+ export function activeWriteAssignedCount(meshId: string): number {
807
+ return getQueue(meshId, { status: ['assigned'] as any })
808
+ .filter(task => !isTaskReadonly(task)).length;
809
+ }
810
+
811
+ /** Active read-only assignments, for the read-only safety cap. */
812
+ export function activeReadonlyAssignedCount(meshId: string): number {
813
+ return getQueue(meshId, { status: ['assigned'] as any })
814
+ .filter(isTaskReadonly).length;
815
+ }
816
+
817
+ function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
818
+ return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
819
+ }
820
+
821
+ /** Active (status='assigned') task count for a node — the load metric for
822
+ * least-loaded / round-robin ranking. Lower = preferred. */
823
+ function nodeActiveLoad(meshId: string, nodeId: string): number {
824
+ return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
825
+ }
826
+
827
+ /**
828
+ * Resolve the canonical repo root for reading a mesh's in-tree `.adhdev/mesh.json`
829
+ * overlay. Prefers a base (non-worktree) node's repoRoot/workspace — the canonical
830
+ * checkout that carries the repo file — and falls back to any node so a worktree-only
831
+ * mesh still resolves a root. Returns '' when no node declares a path.
832
+ */
833
+ function resolveMeshRepoRootForScheduling(mesh: any): string {
834
+ const nodes = Array.isArray(mesh?.nodes) ? mesh.nodes : [];
835
+ const pickRoot = (n: any) => readNonEmptyString(n?.repoRoot) || readNonEmptyString(n?.workspace);
836
+ const base = nodes.find((n: any) => n?.isLocalWorktree !== true && pickRoot(n));
837
+ if (base) return pickRoot(base);
838
+ const anyNode = nodes.find((n: any) => pickRoot(n));
839
+ return anyNode ? pickRoot(anyNode) : '';
840
+ }
841
+
842
+ /**
843
+ * The repo-local `.adhdev/mesh.json` `policy.scheduling` overlay for this mesh, when
844
+ * present and valid. LOCAL-WINS: a value here overrides the stored mesh policy. Cached
845
+ * by mtime in the loader, so calling this on every reconcile tick is cheap.
846
+ */
847
+ function resolveMeshSchedulingOverride(mesh: any): MeshJsonSchedulingConfig | undefined {
848
+ const repoRoot = resolveMeshRepoRootForScheduling(mesh);
849
+ if (!repoRoot) return undefined;
850
+ try {
851
+ return loadMeshJsonConfig(repoRoot).config?.scheduling;
852
+ } catch {
853
+ return undefined;
854
+ }
855
+ }
856
+
857
+ /**
858
+ * The mesh-wide scheduling strategy. Resolution order (LOCAL-WINS):
859
+ * 1. `.adhdev/mesh.json` policy.scheduling.distribution (2-mode → strategy), then
860
+ * 2. the stored mesh policy schedulingStrategy raw 4-union (escape hatch), then
861
+ * 3. 'first_eligible' (strict no-change default).
862
+ * Only governs the final tie-break; eligibility, capacity, and priority gates apply
863
+ * identically to every strategy.
864
+ */
865
+ function resolveSchedulingStrategy(mesh: any): RepoMeshSchedulingStrategy {
866
+ const override = resolveMeshSchedulingOverride(mesh);
867
+ if (override?.distribution) return distributionToStrategy(override.distribution);
868
+ return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
869
+ }
870
+
871
+ /**
872
+ * Order eligible nodes for assignment per the mesh scheduling pipeline:
873
+ * PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
874
+ *
875
+ * The caller has already applied the TAG hard-filter and is responsible for the
876
+ * MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
877
+ * decides the *preference order* among nodes that are otherwise eligible.
878
+ *
879
+ * - 'first_eligible' (default): returns the input order verbatim and does NOT touch
880
+ * the round-robin cursor — byte-for-byte the pre-feature behavior.
881
+ * - 'priority_only': schedulingPriority desc, then input order (load ignored).
882
+ * - 'least_loaded' (the user-facing 'spread' mode): schedulingPriority desc, then
883
+ * active load asc, then — among nodes still tied at (priority, load) — the input
884
+ * order is rotated by a per-mesh cursor that advances once per pass. The rotation
885
+ * tie-break is ALWAYS on for least_loaded so a single 'spread' mode subsumes the
886
+ * former separate 'round_robin' strategy (two equal-load nodes still alternate
887
+ * fairly across passes instead of the lower index always winning).
888
+ * - 'round_robin': retained as an escape-hatch alias; behaves identically to
889
+ * 'least_loaded' now that least_loaded carries the rotation.
890
+ *
891
+ * `nodes` carries the original config/array index so the tie-break can fall back to
892
+ * deterministic input order. `bumpCursor` advances the round-robin cursor exactly
893
+ * once per scheduling pass (consulted for both 'least_loaded' and 'round_robin').
894
+ */
895
+ interface RankableNode { nodeId: string; node: any; index: number }
896
+
897
+ /** Test-only: resolve a mesh's effective scheduling strategy through the full
898
+ * LOCAL-WINS path (`.adhdev/mesh.json` distribution → strategy, else stored policy).
899
+ * Exposed so the repo-file overlay wiring can be exercised by a direct call. */
900
+ export function __resolveSchedulingStrategyForTests(mesh: any): RepoMeshSchedulingStrategy {
901
+ return resolveSchedulingStrategy(mesh);
902
+ }
903
+
904
+ /** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
905
+ * scheduling pipeline can be unit-tested without standing up live CLI sessions. */
906
+ export function __orderEligibleNodesForTests(
907
+ meshId: string,
908
+ strategy: RepoMeshSchedulingStrategy,
909
+ nodes: RankableNode[],
910
+ opts?: { bumpCursor?: boolean },
911
+ ): RankableNode[] {
912
+ return orderEligibleNodes(meshId, strategy, nodes, opts);
913
+ }
914
+
915
+ function orderEligibleNodes(
916
+ meshId: string,
917
+ strategy: RepoMeshSchedulingStrategy,
918
+ nodes: RankableNode[],
919
+ opts?: { bumpCursor?: boolean },
920
+ ): RankableNode[] {
921
+ if (strategy === 'first_eligible' || nodes.length <= 1) {
922
+ return nodes;
923
+ }
924
+
925
+ const priorityOf = (n: { node: any }) => resolveNodeSchedulingPriority(n.node?.policy);
926
+
927
+ // Round-robin rotation offset: rotate the deterministic input order by a
928
+ // per-mesh cursor so the tie-break winner among equal (priority, load) nodes
929
+ // cycles across passes. The cursor advances once per scheduling pass. Applied
930
+ // to both 'least_loaded' (the 'spread' mode — rotation absorbed as its
931
+ // tie-break) and the legacy 'round_robin' alias.
932
+ let rotation = 0;
933
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
934
+ const cursor = opts?.bumpCursor
935
+ ? MeshRuntimeStore.getInstance().bumpSchedulerCursor(meshId)
936
+ : MeshRuntimeStore.getInstance().getSchedulerCursor(meshId);
937
+ rotation = ((cursor % nodes.length) + nodes.length) % nodes.length;
938
+ }
939
+
940
+ // Rotation rank: position of each node after rotating input order by `rotation`.
941
+ // For non-round-robin strategies rotation is 0, so this is just the input index.
942
+ const rotationRank = (index: number) => (index - rotation + nodes.length) % nodes.length;
943
+
944
+ return [...nodes].sort((a, b) => {
945
+ const prioDelta = priorityOf(b) - priorityOf(a); // higher priority first
946
+ if (prioDelta !== 0) return prioDelta;
947
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
948
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
949
+ if (loadDelta !== 0) return loadDelta;
950
+ }
951
+ return rotationRank(a.index) - rotationRank(b.index);
952
+ });
953
+ }
954
+
955
+ /** Active assignments on a (node, provider) — pre-launch guard for the per-(node,
956
+ * provider) maxParallel cap. The authoritative enforcement is in the claim
957
+ * transaction; this only avoids spawning a session that would fail the claim. */
958
+ function activeProviderAssignedCount(meshId: string, nodeId: string, providerType: string): number {
959
+ return getQueue(meshId, { status: ['assigned'] as any })
960
+ .filter(task => task.assignedNodeId === nodeId && task.assignedProviderType === providerType).length;
961
+ }
962
+
963
+ export function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
964
+ if (getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId)) {
965
+ return true;
966
+ }
967
+ // Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
968
+ // work queue. A session completing a still-active direct dispatch IS an active
969
+ // assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
970
+ // the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
971
+ // so the coordinator polling get_pending_mesh_events never observes task_completed and the
972
+ // session goes silently idle. This check runs before markSessionTerminal marks the
973
+ // dispatch terminal, so the in-flight dispatch is still observable here.
974
+ try {
975
+ if (getActiveDirectDispatches(meshId).some(d => d.sessionId === sessionId)) return true;
976
+ if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
977
+ } catch { /* best-effort — fall through to false */ }
978
+ return false;
979
+ }
980
+
981
+ function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
982
+ return components.instanceManager.getByCategory('cli').filter((inst: any) => {
983
+ const state = inst.getState();
984
+ const settings = state.settings as Record<string, unknown> || {};
985
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
986
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
987
+ if (instNodeId !== nodeId) return false;
988
+ const status = readNonEmptyString(state.status).toLowerCase();
989
+ return !isTerminalSessionStatus(status);
990
+ }).length;
991
+ }
992
+
993
+ function recordAutoLaunchEvent(meshId: string, args: {
994
+ phase: 'skipped' | 'started' | 'failed' | 'completed';
995
+ taskId: string;
996
+ nodeId?: string;
997
+ providerType?: string;
998
+ sessionId?: string;
999
+ reason?: string;
1000
+ error?: string;
1001
+ }) {
1002
+ // Suppress consecutive identical `skipped` entries for the same task (4s reconcile
1003
+ // re-trigger noise). Non-skip phases and changed reasons always record and reset
1004
+ // the de-dup so genuine state transitions remain visible in the ledger.
1005
+ const dedupKey = `${meshId}:${args.taskId}`;
1006
+ const currentSig = `${args.phase}|${args.reason || ''}`;
1007
+ if (args.phase === 'skipped' && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
1008
+ return;
1009
+ }
1010
+ lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
1011
+ if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
1012
+ // Bound memory: drop the oldest insertion (Map preserves insertion order).
1013
+ const oldest = lastAutoLaunchLedgerKey.keys().next().value;
1014
+ if (oldest !== undefined) lastAutoLaunchLedgerKey.delete(oldest);
1015
+ }
1016
+ try {
1017
+ appendLedgerEntry(meshId, {
1018
+ kind: 'session_auto_launch',
1019
+ nodeId: args.nodeId,
1020
+ sessionId: args.sessionId,
1021
+ providerType: args.providerType,
1022
+ payload: {
1023
+ phase: args.phase,
1024
+ taskId: args.taskId,
1025
+ reason: args.reason,
1026
+ error: args.error,
1027
+ },
1028
+ });
1029
+ } catch (e: any) {
1030
+ LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
1031
+ }
1032
+ }
1033
+
1034
+ function markAutoLaunch(meshId: string, taskId: string, args: {
1035
+ status: 'skipped' | 'started' | 'failed' | 'completed';
1036
+ reason?: string;
1037
+ nodeId?: string;
1038
+ providerType?: string;
1039
+ sessionId?: string;
1040
+ error?: string;
1041
+ }) {
1042
+ recordTaskAutoLaunch(meshId, taskId, {
1043
+ status: args.status,
1044
+ reason: args.reason || args.error,
1045
+ nodeId: args.nodeId,
1046
+ providerType: args.providerType,
1047
+ sessionId: args.sessionId,
1048
+ });
1049
+ recordAutoLaunchEvent(meshId, {
1050
+ phase: args.status,
1051
+ taskId,
1052
+ nodeId: args.nodeId,
1053
+ providerType: args.providerType,
1054
+ sessionId: args.sessionId,
1055
+ reason: args.reason,
1056
+ error: args.error,
1057
+ });
1058
+ // Fix (1): actively notify the coordinator of a non-self-resolving skip; re-arm the
1059
+ // notification on any non-skip transition (started/completed) so a later genuine skip
1060
+ // re-notifies.
1061
+ if (args.status === 'skipped') {
1062
+ notifyCoordinatorOfActionableSkip(meshId, taskId, args.reason, args.nodeId);
1063
+ } else {
1064
+ lastActionableSkipNotified.delete(`${meshId}:${taskId}`);
1065
+ }
1066
+ }
1067
+
1068
+ async function resolveUsableProvider(
1069
+ components: DaemonComponents,
1070
+ nodeId: string,
1071
+ node: any,
1072
+ requiredTags?: string[],
1073
+ ): Promise<{ providerType?: string; reason?: string }> {
1074
+ const providerPriority = normalizeProviderPriority(node?.policy);
1075
+ if (!providerPriority.length) return { reason: 'missing_provider_priority' };
1076
+ const providerLoader = components.providerLoader;
1077
+ if (!providerLoader) return { reason: 'provider_loader_unavailable' };
1078
+
1079
+ const failed: string[] = [];
1080
+ for (const requestedType of providerPriority) {
1081
+ const normalizedType = typeof providerLoader.resolveAlias === 'function'
1082
+ ? providerLoader.resolveAlias(requestedType)
1083
+ : requestedType;
1084
+ // Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
1085
+ // means only hermes-cli qualifies, not any other type in providerPriority).
1086
+ if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
1087
+ failed.push(`${requestedType}: required_tags_mismatch`);
1088
+ continue;
1089
+ }
1090
+ if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
1091
+ failed.push(`${requestedType}: disabled`);
1092
+ continue;
1093
+ }
1094
+ let detected: any;
1095
+ try {
1096
+ detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
1097
+ } catch (e: any) {
1098
+ failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
1099
+ continue;
1100
+ }
1101
+ if (typeof providerLoader.setCliDetectionResults === 'function') {
1102
+ providerLoader.setCliDetectionResults([{
1103
+ id: normalizedType,
1104
+ installed: !!detected,
1105
+ path: detected?.path,
1106
+ }], false);
1107
+ }
1108
+ (components as any).onStatusChange?.();
1109
+ if (detected) return { providerType: normalizedType };
1110
+ failed.push(`${requestedType}: not detected`);
1111
+ }
1112
+ return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
1113
+ }
1114
+
1115
+ // Canonical mesh node-id normalization. A node may arrive from the local config
1116
+ // form (`id`) or the inline-cache form (`nodeId`/`node_id`) — see
1117
+ // readInlineMeshNodeId in commands/router.ts. Comparing only `node.id` against a
1118
+ // task.targetNodeId silently drops inline-cached worktree nodes, leaving a
1119
+ // target-routed task permanently pending with a misleading
1120
+ // `no_node_satisfies_required_tags` skip.
1121
+ function readMeshNodeId(node: any): string {
1122
+ // Delegate to the shared 3-way (id / nodeId / node_id) normalizer so this
1123
+ // and every other mesh node-id read agree on identity. Coalesce to '' to
1124
+ // preserve the existing string return contract for callers that do
1125
+ // `=== task.targetNodeId` / `if (!nodeId)`.
1126
+ return normalizeMeshNodeId(node) ?? '';
1127
+ }
1128
+
1129
+ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
1130
+ const queue = getQueue(meshId);
1131
+ const pending = queue.filter(task => task.status === 'pending');
1132
+ if (!pending.length) return false;
1133
+
1134
+ // Write cap + read-only cap resolved through the shared helpers, with the
1135
+ // repo-local `.adhdev/mesh.json` overlay winning over the stored policy
1136
+ // (LOCAL-WINS). Both the cap value and the read-only multiplier route through
1137
+ // the same resolvers the observability projection uses, so the enforced and
1138
+ // exposed caps can never drift.
1139
+ const schedulingOverride = resolveMeshSchedulingOverride(mesh);
1140
+ const maxParallelTasks = resolveMaxParallelTasks(
1141
+ schedulingOverride?.maxParallel ?? mesh?.policy?.maxParallelTasks,
1142
+ );
1143
+ // Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
1144
+ // write-task parallel cap. To prevent runaway auto-launch they get their own,
1145
+ // higher safety cap (readonlyMultiplier × the write cap, default 2×).
1146
+ const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks, schedulingOverride?.readonlyMultiplier);
1147
+ for (const task of pending) {
1148
+ const isReadonly = isTaskReadonly(task);
1149
+ if (isReadonly) {
1150
+ if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
1151
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
1152
+ continue;
1153
+ }
1154
+ } else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
1155
+ // Write tasks are capped; skip this one but keep scanning so a later
1156
+ // read-only task in the queue can still launch under its own cap.
1157
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
1158
+ continue;
1159
+ }
1160
+ if (task.targetSessionId) {
1161
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
1162
+ continue;
1163
+ }
1164
+
1165
+ // Per-task await-claim guard. A prior auto-launch already spawned a session for
1166
+ // this task and we are waiting for that session's idle→claim to land (remote
1167
+ // claims arrive via the worker→coordinator agent:ready pull, which can lag well
1168
+ // past the per-node cooldown). Re-launching now would spawn a duplicate orphan
1169
+ // session that never gets work. The task leaves `pending` the instant the claim
1170
+ // succeeds, so this guard only suppresses the in-flight window; if the launched
1171
+ // session never reaches idle within the window, a later tick retries.
1172
+ if (task.autoLaunch?.status === 'completed' && task.autoLaunch.sessionId) {
1173
+ const launchedAtMs = Date.parse(task.autoLaunch.updatedAt);
1174
+ if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
1175
+ // Record the skip in the ledger ONLY (dedup'd). Do NOT call markAutoLaunch
1176
+ // here: recordTaskAutoLaunch overwrites task.autoLaunch wholesale, which would
1177
+ // erase the very `completed` record (status + sessionId + updatedAt) this guard
1178
+ // reads on the next tick, reopening the duplicate-launch hole it closes.
1179
+ recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim', nodeId: task.autoLaunch.nodeId, sessionId: task.autoLaunch.sessionId });
1180
+ continue;
1181
+ }
1182
+ }
1183
+
1184
+ const candidateNodes = Array.isArray(mesh?.nodes)
1185
+ ? mesh.nodes.filter((node: any) => {
1186
+ // Bug A: match the target pin with the shared 3-form (id / nodeId / node_id)
1187
+ // normalizer, mirroring the remote-idle drain (meshNodeIdMatches at the
1188
+ // getRemoteIdleSessions filter). A strict `readMeshNodeId(node) !== targetNodeId`
1189
+ // dropped a target node whose identity arrived under a different form (a freshly
1190
+ // mesh_clone_node'd worktree), emptying candidateNodes and mislabelling the skip.
1191
+ if (task.targetNodeId && !meshNodeIdMatches(node, task.targetNodeId)) return false;
1192
+ // WTDISPATCH-FANOUT: a convergence task is base-only (it merges/pushes onto
1193
+ // base). Never auto-launch a worktree-clone session for it — that is the very
1194
+ // fan-out the claim guard refuses, so spinning the session up would only waste
1195
+ // a launch that can never claim. Mirrors claimNextQueueTask's convergence gate.
1196
+ if (task.taskMode === 'convergence' && node?.isLocalWorktree === true) return false;
1197
+ // Skip nodes that can never satisfy requiredTags regardless of which provider
1198
+ // from providerPriority is selected. A node satisfies tags if at least one
1199
+ // provider in its priority list would produce matching capability tags.
1200
+ if (task.requiredTags?.length) {
1201
+ const priorities = normalizeProviderPriority(node?.policy);
1202
+ const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
1203
+ return providerCandidates.some(p =>
1204
+ nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
1205
+ );
1206
+ }
1207
+ return true;
1208
+ })
1209
+ : [];
1210
+ if (!candidateNodes.length) {
1211
+ // Bug A: distinguish the two ways the candidate set empties. A task pinned to a
1212
+ // targetNodeId whose node is absent from the mesh (or whose id arrived under a
1213
+ // different form) is a ROUTING miss — report it as `target_node_id_unmatched`, not
1214
+ // the hard-coded `no_node_satisfies_required_tags`, which mislabelled a 3-form
1215
+ // node-id mismatch as a capability failure and sent diagnosis down the wrong path.
1216
+ // Only fall back to the tag reason when no target pin is in play, or the pin DID
1217
+ // match a node but its tags excluded it (a genuine capability miss).
1218
+ const targetPinUnmatched = !!task.targetNodeId
1219
+ && !(Array.isArray(mesh?.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, task.targetNodeId)));
1220
+ // Fix (2): a `convergence` task is base-only — the candidate filter above
1221
+ // (`taskMode === 'convergence' && node.isLocalWorktree`) deliberately drops every
1222
+ // worktree-clone node, so candidateNodes can empty out NOT because the target is
1223
+ // missing or tag-incapable, but because every node the task could land on is a
1224
+ // worktree. Reporting that as `target_node_id_unmatched` / `no_node_satisfies_
1225
+ // required_tags` mislabels the cause and sends diagnosis down the wrong path.
1226
+ // Detect it explicitly and report the same reason mesh_send_task uses for a direct
1227
+ // convergence dispatch onto a worktree, so both surfaces agree.
1228
+ const convergenceOntoWorktree = task.taskMode === 'convergence'
1229
+ && Array.isArray(mesh?.nodes)
1230
+ && (() => {
1231
+ const matched = (mesh.nodes as any[]).filter((n: any) =>
1232
+ !task.targetNodeId || meshNodeIdMatches(n, task.targetNodeId));
1233
+ return matched.length > 0 && matched.every((n: any) => n?.isLocalWorktree === true);
1234
+ })();
1235
+ markAutoLaunch(meshId, task.id, {
1236
+ status: 'skipped',
1237
+ reason: convergenceOntoWorktree
1238
+ ? 'mesh_convergence_target_is_worktree'
1239
+ : (targetPinUnmatched ? 'target_node_id_unmatched' : 'no_node_satisfies_required_tags'),
1240
+ nodeId: task.targetNodeId,
1241
+ });
1242
+ continue;
1243
+ }
1244
+
1245
+ // PRIORITY → TIE-BREAK: order the eligible (TAG-filtered) candidate nodes by
1246
+ // the mesh scheduling strategy. 'first_eligible' (default) returns them in
1247
+ // config/array order unchanged, so distribution is strictly opt-in. The
1248
+ // per-node MAX-ALLOC capacity gate (nodeHasActiveAssignment, provider cap,
1249
+ // maxConcurrentSessions) is still applied inside the loop below; this only
1250
+ // chooses which eligible node is *tried first*.
1251
+ const strategy = resolveSchedulingStrategy(mesh);
1252
+ const orderedCandidateNodes = strategy === 'first_eligible'
1253
+ ? candidateNodes
1254
+ : orderEligibleNodes(
1255
+ meshId,
1256
+ strategy,
1257
+ candidateNodes
1258
+ .map((node: any, index: number) => ({ nodeId: readMeshNodeId(node), node, index }))
1259
+ .filter((c: RankableNode) => c.nodeId),
1260
+ { bumpCursor: true },
1261
+ ).map((c: RankableNode) => c.node);
1262
+
1263
+ for (const node of orderedCandidateNodes) {
1264
+ const nodeId = readMeshNodeId(node);
1265
+ if (!nodeId) continue;
1266
+ const launchKey = `${meshId}:${nodeId}`;
1267
+ const now = Date.now();
1268
+ const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
1269
+ if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
1270
+ if (autoLaunchInProgress.has(launchKey)) {
1271
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
1272
+ continue;
1273
+ }
1274
+ if (now < cooldownUntil) {
1275
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
1276
+ continue;
1277
+ }
1278
+ if (isDirtyNode(node)) {
1279
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
1280
+ continue;
1281
+ }
1282
+ if (!isLaunchableNode(node)) {
1283
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
1284
+ continue;
1285
+ }
1286
+ const launchTarget = resolveAutoLaunchTarget(components, node);
1287
+ if (launchTarget.mode === 'skip') {
1288
+ // Remote node we can't reach (no transport / no coordinator daemonId).
1289
+ // Set a cooldown so the 4s reconcile loop doesn't re-attempt this node
1290
+ // every tick; the de-dup'd skip ledger keeps it diagnosable without flood.
1291
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: launchTarget.reason || 'auto_launch_unavailable', nodeId });
1292
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1293
+ continue;
1294
+ }
1295
+ // Write tasks keep the one-active-per-node invariant (worktree isolation);
1296
+ // read-only diagnoses may auto-launch onto a node that already has an active
1297
+ // assignment. Classified by the shared isTaskReadonly predicate.
1298
+ if (!isTaskReadonly(task) && nodeHasActiveAssignment(meshId, nodeId)) {
1299
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
1300
+ continue;
1301
+ }
1302
+ const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
1303
+ if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
1304
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
1305
+ continue;
1306
+ }
1307
+
1308
+ autoLaunchInProgress.add(launchKey);
1309
+ try {
1310
+ const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
1311
+ if (!resolved.providerType) {
1312
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
1313
+ continue;
1314
+ }
1315
+
1316
+ // Don't spawn a session for a (node, provider) already at its declared
1317
+ // maxParallel cap — it would launch only to fail the claim. The claim
1318
+ // transaction enforces the cap regardless; this just avoids a doomed launch.
1319
+ const providerCap = resolveProviderMaxParallel(node?.policy, resolved.providerType);
1320
+ if (
1321
+ providerCap !== undefined
1322
+ && activeProviderAssignedCount(meshId, nodeId, resolved.providerType) >= providerCap
1323
+ ) {
1324
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_provider_parallel_reached', nodeId, providerType: resolved.providerType });
1325
+ continue;
1326
+ }
1327
+
1328
+ // Shared worker-launch envelope. For a local node it spawns directly on this
1329
+ // daemon; for a remote node the identical command is forwarded to the node's
1330
+ // daemon (mirrors mesh_launch_session), with the coordinator daemonId stamped
1331
+ // so the worker's completion events route back to this coordinator.
1332
+ const launchSettings: Record<string, unknown> = {
1333
+ // Worker launch envelope: role + mesh context so worker can route completion events.
1334
+ role: 'worker',
1335
+ meshNodeFor: meshId,
1336
+ meshNodeId: nodeId,
1337
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1338
+ // Coordinator-dispatched worker: auto-approve unless mesh/node policy
1339
+ // opts out (default true). Lands in settingsOverride and beats the
1340
+ // global per-provider-type autoApprove config (see shouldAutoApprove).
1341
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1342
+ launchedByCoordinator: true,
1343
+ autoLaunchedForQueueTaskId: task.id,
1344
+ };
1345
+
1346
+ if (launchTarget.mode === 'remote') {
1347
+ // Relay-safe completion routing: stamp the coordinator anchor the same way
1348
+ // mesh_launch_session does so the worker forwards events back to this daemon.
1349
+ const remoteSettings: Record<string, unknown> = {
1350
+ ...launchSettings,
1351
+ meshCoordinatorDaemonId: launchTarget.coordinatorDaemonId,
1352
+ meshCoordinatorNodeId: nodeId,
1353
+ };
1354
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1355
+ let launchResult: any;
1356
+ try {
1357
+ launchResult = await components.dispatchMeshCommand!(launchTarget.daemonId!, 'launch_cli', {
1358
+ cliType: resolved.providerType,
1359
+ dir: node.workspace,
1360
+ settings: remoteSettings,
1361
+ });
1362
+ } catch (e: any) {
1363
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: `remote_launch_dispatch_failed: ${e?.message || String(e)}`, nodeId, providerType: resolved.providerType });
1364
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1365
+ return false;
1366
+ }
1367
+ const payload = (launchResult && typeof launchResult === 'object' && 'payload' in launchResult && launchResult.payload && typeof launchResult.payload === 'object')
1368
+ ? launchResult.payload
1369
+ : launchResult;
1370
+ if (!payload?.success) {
1371
+ const reason = readNonEmptyString(payload?.error) || 'remote_launch_cli_failed';
1372
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1373
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1374
+ return false;
1375
+ }
1376
+ // Remote launch is async: the worker session will register and emit agent:ready,
1377
+ // which (forwarded back here) drives the claim via the normal event path / PHASE 1
1378
+ // reconcile. Set a cooldown so the 4s loop doesn't re-launch before that lands.
1379
+ const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
1380
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || undefined });
1381
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1382
+ return true;
1383
+ }
1384
+
1385
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1386
+ const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
1387
+ cliType: resolved.providerType,
1388
+ dir: node.workspace,
1389
+ settings: launchSettings,
1390
+ });
1391
+ if (!launchResult?.success) {
1392
+ const reason = launchResult?.error || 'launch_cli_failed';
1393
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1394
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1395
+ return false;
1396
+ }
1397
+ const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
1398
+ if (!sessionId) {
1399
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
1400
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1401
+ return false;
1402
+ }
1403
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
1404
+ // Readiness barrier: a freshly-spawned local CLI session is NOT yet
1405
+ // interactive — its PTY prints the input prompt (and the adapter flips
1406
+ // isReady()) only ~2-6s after launch. Dispatching the task immediately
1407
+ // pushes the first (often large) message into a not-yet-ready PTY, which
1408
+ // could throw "not ready" and bounce the task through requeue (on win32
1409
+ // this raced the auto-launch cooldown and stranded the worker idle).
1410
+ // Await interactive readiness before claiming/dispatching so the very
1411
+ // first message lands cleanly. The adapter's queue-until-ready path is the
1412
+ // backstop if readiness is reported late; this just avoids the churn.
1413
+ await waitForLocalSessionReady(components, sessionId);
1414
+ tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
1415
+ return true;
1416
+ } catch (e: any) {
1417
+ markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
1418
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
1419
+ return false;
1420
+ } finally {
1421
+ autoLaunchInProgress.delete(launchKey);
1422
+ }
1423
+ }
1424
+ }
1425
+ return false;
1426
+ }
1427
+
1428
+ export interface MeshQueueTriggerResult {
1429
+ success: true;
1430
+ meshId: string;
1431
+ pendingBefore: number;
1432
+ assignedBefore: number;
1433
+ pendingAfter: number;
1434
+ assignedAfter: number;
1435
+ claimed: boolean;
1436
+ newlyAssignedTasks: Array<{
1437
+ id: string;
1438
+ nodeId?: string;
1439
+ sessionId?: string;
1440
+ }>;
1441
+ localIdleSessionsChecked: number;
1442
+ remoteIdleSessionsChecked: number;
1443
+ skippedSessions: Array<{
1444
+ nodeId?: string;
1445
+ sessionId?: string;
1446
+ reason: string;
1447
+ status?: string;
1448
+ }>;
1449
+ autoLaunchStarted: boolean;
1450
+ /**
1451
+ * True when a worker session is already on its way to claim a still-pending task —
1452
+ * either launched this tick (autoLaunchStarted) or launched on a prior tick and still
1453
+ * booting/awaiting-claim. Callers MUST treat this as "wait, do not launch another
1454
+ * session": a second launch double-edits the worktree. Mutually informative with
1455
+ * `noIdleMeshSessionAvailable`, which is suppressed whenever this is true.
1456
+ */
1457
+ autoLaunchPending?: boolean;
1458
+ noIdleMeshSessionAvailable?: boolean;
1459
+ }
1460
+
1461
+ function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
1462
+ return getQueue(meshId, { status: [status] as any }).length;
1463
+ }
1464
+
1465
+ function getQueueStatusById(meshId: string): Map<string, string> {
1466
+ return new Map(getQueue(meshId).map(task => [task.id, task.status]));
1467
+ }
1468
+
1469
+ export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
1470
+ const mesh = getMeshWithCache(components, meshId);
1471
+ const pendingBefore = countQueueStatus(meshId, 'pending');
1472
+ const assignedBefore = countQueueStatus(meshId, 'assigned');
1473
+ const beforeStatus = getQueueStatusById(meshId);
1474
+ const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
1475
+ let localIdleSessionsChecked = 0;
1476
+ let remoteIdleSessionsChecked = 0;
1477
+ let autoLaunchStarted = false;
1478
+ if (!mesh) {
1479
+ return {
1480
+ success: true,
1481
+ meshId,
1482
+ pendingBefore,
1483
+ assignedBefore,
1484
+ pendingAfter: pendingBefore,
1485
+ assignedAfter: assignedBefore,
1486
+ claimed: false,
1487
+ newlyAssignedTasks: [],
1488
+ localIdleSessionsChecked,
1489
+ remoteIdleSessionsChecked,
1490
+ skippedSessions: [{ reason: 'mesh_not_found' }],
1491
+ autoLaunchStarted,
1492
+ noIdleMeshSessionAvailable: true,
1493
+ };
1494
+ }
1495
+
1496
+ // Collect every idle mesh session (local CLI instances + remote idle records)
1497
+ // as drain candidates. The drain ORDER depends on the scheduling strategy:
1498
+ // - 'first_eligible' (default): local-first, then remote, exactly as before.
1499
+ // - otherwise: local + remote merged into one pool and drained in scheduling
1500
+ // order (priority → load → tie-break). This local-first debias is required
1501
+ // because without it the coordinator's own local node is always visited
1502
+ // first and greedily absorbs all untargeted work before any remote idle
1503
+ // session is even considered — the comparator alone can't spread work if
1504
+ // local is always tried first.
1505
+ type IdleCandidate = { nodeId: string; sessionId: string; providerType: string; origin: 'local' | 'remote'; node: any };
1506
+ const strategy = resolveSchedulingStrategy(mesh);
1507
+ const localCandidates: IdleCandidate[] = [];
1508
+
1509
+ const cliInstances = components.instanceManager.getByCategory('cli');
1510
+ for (const inst of cliInstances) {
1511
+ const state = inst.getState();
1512
+ const settings = state.settings as Record<string, unknown> || {};
1513
+
1514
+ const instMeshId = readNonEmptyString(settings.meshNodeFor);
1515
+ if (instMeshId !== meshId) continue;
1516
+
1517
+ const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1518
+ if (!nodeId) continue;
1519
+
1520
+ if (!isIdleSessionState(state)) {
1521
+ const status = readNonEmptyString(state.status).toLowerCase();
1522
+ skippedSessions.push({
1523
+ nodeId,
1524
+ sessionId: readNonEmptyString(state.instanceId),
1525
+ reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
1526
+ status: status || undefined,
1527
+ });
1528
+ continue;
1529
+ }
1530
+
1531
+ const sessionId = state.instanceId;
1532
+ const providerType = state.type || readNonEmptyString(settings.providerType);
1533
+
1534
+ if (providerType) {
1535
+ localIdleSessionsChecked += 1;
1536
+ localCandidates.push({ nodeId, sessionId, providerType, origin: 'local', node: mesh.nodes.find((n: any) => meshNodeIdMatches(n, nodeId)) });
1537
+ } else {
1538
+ skippedSessions.push({
1539
+ nodeId,
1540
+ sessionId,
1541
+ reason: 'provider_type_missing',
1542
+ });
1543
+ }
1544
+ }
1545
+
1546
+ let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
1547
+ try {
1548
+ remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions(meshId);
1549
+ } catch { /* best-effort */ }
1550
+
1551
+ const remoteCandidates: IdleCandidate[] = [];
1552
+ for (const idle of remoteSessions) {
1553
+ // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
1554
+ // `n.id`, so an inline-cached worktree node whose identity arrived under a
1555
+ // different form is not silently dropped — leaving a remote idle session
1556
+ // unable to claim its pending queue task.
1557
+ const node = mesh.nodes.find((n: any) => meshNodeIdMatches(n, idle.nodeId));
1558
+ if (node) {
1559
+ remoteIdleSessionsChecked += 1;
1560
+ remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: 'remote', node });
1561
+ }
1562
+ }
1563
+
1564
+ const assignIdleCandidate = (candidate: IdleCandidate): void => {
1565
+ const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
1566
+ if (assigned && candidate.origin === 'remote') {
1567
+ try {
1568
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(meshId, candidate.nodeId, candidate.sessionId);
1569
+ } catch { /* best-effort */ }
1570
+ }
1571
+ };
1572
+
1573
+ if (strategy === 'first_eligible') {
1574
+ // Strict no-change: drain local idle sessions first (original order), then
1575
+ // remote idle sessions. tryAssignQueueTask is a no-op when nothing matches.
1576
+ for (const candidate of localCandidates) assignIdleCandidate(candidate);
1577
+ for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
1578
+ } else {
1579
+ // Merge local + remote into one pool and drain in scheduling order. Each
1580
+ // assignment mutates a node's active load, and the next pick re-reads it,
1581
+ // so re-ranking after every assignment keeps the spread fair as load shifts.
1582
+ const pool = [...localCandidates, ...remoteCandidates];
1583
+ const baseIndex = new Map<string, number>();
1584
+ pool.forEach((c, i) => { if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i); });
1585
+ // Bump the round-robin cursor once for this whole drain pass.
1586
+ const uniqueNodes = [...new Set(pool.map(c => c.nodeId))]
1587
+ .map((nodeId, index) => ({ nodeId, node: pool.find(c => c.nodeId === nodeId)?.node, index }));
1588
+ const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
1589
+ const rankIndex = new Map<string, number>(ranked.map((r, i) => [r.nodeId, i]));
1590
+ const remaining = [...pool];
1591
+ while (remaining.length > 0) {
1592
+ // Re-rank each pass so a node that just took work defers its next session.
1593
+ remaining.sort((a, b) => {
1594
+ const aPrio = resolveNodeSchedulingPriority(a.node?.policy);
1595
+ const bPrio = resolveNodeSchedulingPriority(b.node?.policy);
1596
+ if (aPrio !== bPrio) return bPrio - aPrio;
1597
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
1598
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
1599
+ if (loadDelta !== 0) return loadDelta;
1600
+ }
1601
+ return (rankIndex.get(a.nodeId) ?? 0) - (rankIndex.get(b.nodeId) ?? 0);
1602
+ });
1603
+ assignIdleCandidate(remaining.shift()!);
1604
+ }
1605
+ }
1606
+
1607
+ autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
1608
+ const afterQueue = getQueue(meshId);
1609
+ const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
1610
+ const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
1611
+ const newlyAssignedTasks = afterQueue
1612
+ .filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
1613
+ .map(task => ({
1614
+ id: task.id,
1615
+ nodeId: task.assignedNodeId,
1616
+ sessionId: task.assignedSessionId,
1617
+ }));
1618
+
1619
+ // An auto-launch is "pending" when the coordinator has already spun a session up
1620
+ // for a still-pending task and is waiting on that session's idle→claim. This covers
1621
+ // two ticks:
1622
+ // - THIS tick fired the launch (autoLaunchStarted), or
1623
+ // - a PRIOR tick launched a session that is still booting/awaiting-claim — the
1624
+ // per-task await-claim guard (maybeAutoLaunchOneQueueSession) deliberately
1625
+ // declines to launch again, so autoLaunchStarted is false even though a session
1626
+ // is on its way to claim this task.
1627
+ // Without this signal, the second tick reports `noIdleMeshSessionAvailable` and the
1628
+ // MCP guidance tells the coordinator to launch ANOTHER worker — producing a duplicate
1629
+ // session that double-edits the worktree. The claim itself is fine; only the wording
1630
+ // was wrong, so we surface `autoLaunchPending` to suppress the bad "launch one more"
1631
+ // advice while the just-launched session converges.
1632
+ const autoLaunchPending = autoLaunchStarted || afterQueue.some(task => {
1633
+ if (task.status !== 'pending') return false;
1634
+ const al = task.autoLaunch;
1635
+ if (!al || (al.status !== 'started' && al.status !== 'completed')) return false;
1636
+ const launchedAtMs = Date.parse(al.updatedAt);
1637
+ return Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
1638
+ });
1639
+
1640
+ return {
1641
+ success: true,
1642
+ meshId,
1643
+ pendingBefore,
1644
+ assignedBefore,
1645
+ pendingAfter,
1646
+ assignedAfter,
1647
+ claimed: newlyAssignedTasks.length > 0,
1648
+ newlyAssignedTasks,
1649
+ localIdleSessionsChecked,
1650
+ remoteIdleSessionsChecked,
1651
+ skippedSessions,
1652
+ autoLaunchStarted,
1653
+ ...(autoLaunchPending ? { autoLaunchPending: true } : {}),
1654
+ // Only report "no idle session, go launch one" when nothing is already on its way.
1655
+ // A pending auto-launch (this tick or a prior still-converging one) means a session
1656
+ // WILL claim shortly, so it is not a no-session-available situation.
1657
+ ...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchPending
1658
+ ? { noIdleMeshSessionAvailable: true }
1659
+ : {}),
1660
+ };
1661
+ }
1662
+
1663
+ export async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
1664
+ meshId: string;
1665
+ nodeId: string;
1666
+ sessionId?: string;
1667
+ providerType?: string;
1668
+ }): Promise<void> {
1669
+ const mesh = getMeshWithCache(components, args.meshId);
1670
+ const node = mesh?.nodes?.find((candidate: any) => meshNodeIdMatches(candidate, args.nodeId));
1671
+ const workspace = readNonEmptyString(node?.workspace);
1672
+ if (!workspace) return;
1673
+ if (!existsSync(workspace)) return;
1674
+
1675
+ const policy = resolveAutoFastForwardPolicy(mesh);
1676
+ if (!policy.enabled) return;
1677
+ if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
1678
+
1679
+ const throttleKey = `${args.meshId}:${args.nodeId}`;
1680
+ const now = Date.now();
1681
+ const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
1682
+ if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
1683
+ idleAutoFastForwardLastAttempt.set(throttleKey, now);
1684
+
1685
+ const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
1686
+ ? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
1687
+ : undefined;
1688
+ try {
1689
+ const dryRun = await fastForwardMeshNode({
1690
+ meshId: args.meshId,
1691
+ nodeId: args.nodeId,
1692
+ workspace,
1693
+ execute: false,
1694
+ dryRun: true,
1695
+ updateSubmodules: false,
1696
+ submoduleIgnorePaths,
1697
+ trigger: 'idle_auto',
1698
+ });
1699
+ if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
1700
+ const behind = Number(dryRun.current?.behind);
1701
+ if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
1702
+ if (policy.requireCleanSubmodules) {
1703
+ const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
1704
+ if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
1705
+ }
1706
+ await fastForwardMeshNode({
1707
+ meshId: args.meshId,
1708
+ nodeId: args.nodeId,
1709
+ workspace,
1710
+ execute: true,
1711
+ dryRun: false,
1712
+ updateSubmodules: false,
1713
+ submoduleIgnorePaths,
1714
+ trigger: 'idle_auto',
1715
+ });
1716
+ } catch (e: any) {
1717
+ LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
1718
+ }
1719
+ }
1720
+
1721
+ export function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
1722
+ meshId: string;
1723
+ nodeId: string;
1724
+ sessionId: string;
1725
+ providerType: string;
1726
+ }): void {
1727
+ setImmediate(() => {
1728
+ maybeAutoFastForwardIdleNode(components, args)
1729
+ .finally(() => {
1730
+ try {
1731
+ tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
1732
+ } catch (e: any) {
1733
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
1734
+ }
1735
+ });
1736
+ });
1737
+ }
1738
+