@adhdev/daemon-core 0.9.82-rc.48 → 0.9.82-rc.481

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 (473) 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 +220 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +23 -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 +51 -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 +64 -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 +48 -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 +152 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router-aggregate-status.d.ts +24 -0
  56. package/dist/commands/router-mesh-session-owner.d.ts +59 -0
  57. package/dist/commands/router-refine.d.ts +137 -0
  58. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  59. package/dist/commands/router.d.ts +204 -15
  60. package/dist/commands/upgrade-helper.d.ts +41 -1
  61. package/dist/config/chat-history.d.ts +11 -0
  62. package/dist/config/config.d.ts +19 -0
  63. package/dist/config/mesh-config.d.ts +136 -1
  64. package/dist/config/mesh-json-config.d.ts +199 -0
  65. package/dist/config/registry-resolver.d.ts +54 -0
  66. package/dist/config/repo-settings.d.ts +77 -0
  67. package/dist/config/state-store.d.ts +30 -0
  68. package/dist/daemon/dev-server.d.ts +0 -2
  69. package/dist/detection/cli-detector.d.ts +17 -0
  70. package/dist/detection/ide-detector.d.ts +13 -0
  71. package/dist/detection/win32-ide-version.d.ts +37 -0
  72. package/dist/git/change-impact-config.d.ts +159 -0
  73. package/dist/git/git-commands.d.ts +26 -2
  74. package/dist/git/git-diff.d.ts +6 -0
  75. package/dist/git/git-executor.d.ts +11 -0
  76. package/dist/git/git-status.d.ts +57 -0
  77. package/dist/git/git-types.d.ts +2 -50
  78. package/dist/git/git-worktree.d.ts +71 -1
  79. package/dist/git/index.d.ts +3 -1
  80. package/dist/index.d.ts +73 -17
  81. package/dist/index.js +52979 -18657
  82. package/dist/index.js.map +1 -1
  83. package/dist/index.mjs +59496 -25355
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/installer.d.ts +1 -4
  86. package/dist/ipc/local-ipc-server.d.ts +91 -0
  87. package/dist/launch.d.ts +1 -1
  88. package/dist/logging/async-batch-writer.d.ts +10 -0
  89. package/dist/logging/debug-config.d.ts +16 -0
  90. package/dist/logging/log-redactor.d.ts +24 -0
  91. package/dist/logging/log-tail-reader.d.ts +81 -0
  92. package/dist/logging/logger.d.ts +1 -1
  93. package/dist/mesh/contracts.d.ts +230 -0
  94. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  95. package/dist/mesh/coordinator-registry.d.ts +59 -0
  96. package/dist/mesh/mesh-active-work.d.ts +203 -0
  97. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  98. package/dist/mesh/mesh-completion-synthesis.d.ts +4 -0
  99. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  100. package/dist/mesh/mesh-delivery-policy.d.ts +104 -0
  101. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  102. package/dist/mesh/mesh-event-forwarding.d.ts +49 -0
  103. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  104. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  105. package/dist/mesh/mesh-events-pending.d.ts +246 -0
  106. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  107. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  108. package/dist/mesh/mesh-events.d.ts +6 -49
  109. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  110. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  111. package/dist/mesh/mesh-init.d.ts +128 -0
  112. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  113. package/dist/mesh/mesh-ledger.d.ts +139 -1
  114. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  115. package/dist/mesh/mesh-missions.d.ts +281 -0
  116. package/dist/mesh/mesh-node-identity.d.ts +310 -0
  117. package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
  118. package/dist/mesh/mesh-reconcile-acked-hold.d.ts +17 -0
  119. package/dist/mesh/mesh-reconcile-config.d.ts +6 -0
  120. package/dist/mesh/mesh-reconcile-identity.d.ts +6 -0
  121. package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
  122. package/dist/mesh/mesh-reconcile-v2-backstop.d.ts +16 -0
  123. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  124. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  125. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  126. package/dist/mesh/mesh-remote-event-pull.d.ts +15 -0
  127. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  128. package/dist/mesh/mesh-routing.d.ts +70 -0
  129. package/dist/mesh/mesh-runtime-store.d.ts +508 -0
  130. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  131. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  132. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  133. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  134. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  135. package/dist/mesh/mesh-work-queue.d.ts +363 -5
  136. package/dist/mesh/preview-freshness.d.ts +28 -0
  137. package/dist/mesh/refine-config.d.ts +216 -0
  138. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  139. package/dist/providers/acp-provider-instance.d.ts +5 -0
  140. package/dist/providers/approval-utils.d.ts +46 -0
  141. package/dist/providers/chat-message-normalization.d.ts +58 -1
  142. package/dist/providers/cli-provider-effect-format.d.ts +30 -0
  143. package/dist/providers/cli-provider-history-dedup.d.ts +17 -0
  144. package/dist/providers/cli-provider-input-prompt.d.ts +12 -0
  145. package/dist/providers/cli-provider-instance-types.d.ts +45 -0
  146. package/dist/providers/cli-provider-instance.d.ts +406 -30
  147. package/dist/providers/cli-provider-status-helpers.d.ts +46 -0
  148. package/dist/providers/cli-provider-transcript-merge.d.ts +7 -0
  149. package/dist/providers/contracts.d.ts +149 -6
  150. package/dist/providers/external-sources.d.ts +71 -0
  151. package/dist/providers/manual-attendance.d.ts +79 -0
  152. package/dist/providers/native-history/antigravity-claim-registry.d.ts +39 -0
  153. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  154. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  155. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  156. package/dist/providers/native-history/constants.d.ts +12 -0
  157. package/dist/providers/native-history/dispatcher.d.ts +44 -0
  158. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  159. package/dist/providers/native-history/index.d.ts +13 -0
  160. package/dist/providers/provider-instance-manager.d.ts +29 -0
  161. package/dist/providers/provider-instance.d.ts +30 -1
  162. package/dist/providers/provider-loader.d.ts +42 -5
  163. package/dist/providers/provider-trust.d.ts +31 -0
  164. package/dist/providers/read-chat-contract.d.ts +29 -0
  165. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  166. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  167. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  168. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  169. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  170. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  171. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  172. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  173. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  174. package/dist/providers/sdk/v1/index.d.ts +30 -0
  175. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  176. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  177. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  178. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  179. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  180. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  181. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  182. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  183. package/dist/providers/spec/adapter.d.ts +98 -0
  184. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  185. package/dist/providers/spec/evaluator.d.ts +45 -0
  186. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  187. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  188. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  189. package/dist/providers/spec/fsm-types.d.ts +202 -0
  190. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  191. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  192. package/dist/providers/spec/route.d.ts +4 -0
  193. package/dist/providers/spec/types.d.ts +244 -0
  194. package/dist/providers/status-monitor.d.ts +7 -7
  195. package/dist/providers/transcript-v2.d.ts +176 -0
  196. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  197. package/dist/providers/working-dir.d.ts +17 -0
  198. package/dist/repo-mesh-types.d.ts +629 -12
  199. package/dist/runtime-defaults.d.ts +2 -0
  200. package/dist/session-host/managed-host.d.ts +64 -0
  201. package/dist/session-host/runtime-surface.d.ts +10 -16
  202. package/dist/sessions/registry.d.ts +26 -0
  203. package/dist/shared-types-extra.d.ts +2 -4
  204. package/dist/shared-types.d.ts +98 -55
  205. package/dist/status/chat-tail-hot-sessions.d.ts +40 -0
  206. package/dist/status/normalize.d.ts +1 -1
  207. package/dist/status/normalize.js +1 -0
  208. package/dist/status/normalize.js.map +1 -1
  209. package/dist/status/normalize.mjs +1 -0
  210. package/dist/status/normalize.mjs.map +1 -1
  211. package/dist/status/reporter.d.ts +2 -0
  212. package/dist/status/snapshot.d.ts +26 -0
  213. package/dist/system/hash.d.ts +8 -0
  214. package/dist/system/load-better-sqlite3.d.ts +21 -0
  215. package/dist/types.d.ts +5 -0
  216. package/package.json +11 -4
  217. package/src/agent-stream/poller.ts +2 -3
  218. package/src/agent-stream/provider-adapter.ts +1 -1
  219. package/src/boot/daemon-lifecycle.ts +80 -14
  220. package/src/boot/process-hardening.ts +89 -0
  221. package/src/build-info.ts +73 -0
  222. package/src/chat/source-machine.ts +534 -0
  223. package/src/chat/source-resolver.ts +0 -0
  224. package/src/chat/subscription-updates.ts +20 -1
  225. package/src/cli-adapter-types.d.ts +3 -1
  226. package/src/cli-adapter-types.ts +68 -2
  227. package/src/cli-adapters/cli-script-runner.ts +421 -0
  228. package/src/cli-adapters/cli-state-engine.ts +1282 -0
  229. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  230. package/src/cli-adapters/provider-cli-adapter.ts +954 -1144
  231. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  232. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  233. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  234. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  235. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  236. package/src/cli-adapters/pty-transport.ts +2 -1
  237. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  238. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  239. package/src/cli-adapters/resolve-executable.ts +204 -0
  240. package/src/cli-adapters/session-host-transport.ts +2 -1
  241. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  242. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  243. package/src/cli-adapters/terminal-screen.ts +16 -81
  244. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  245. package/src/commands/chat-commands-read.ts +2767 -0
  246. package/src/commands/chat-commands-scope.ts +54 -0
  247. package/src/commands/chat-commands-shared.ts +114 -0
  248. package/src/commands/chat-commands-write.ts +891 -0
  249. package/src/commands/chat-commands.ts +19 -1841
  250. package/src/commands/cli-manager.d.ts +2 -0
  251. package/src/commands/cli-manager.ts +659 -27
  252. package/src/commands/handler.ts +845 -2
  253. package/src/commands/high-family/index.ts +28 -0
  254. package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
  255. package/src/commands/high-family/mesh-events.ts +102 -0
  256. package/src/commands/high-family/mesh-status.ts +849 -0
  257. package/src/commands/high-family/types.ts +80 -0
  258. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  259. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  260. package/src/commands/low-family/diagnostics.ts +57 -0
  261. package/src/commands/low-family/index.ts +37 -0
  262. package/src/commands/low-family/mesh-ledger.ts +62 -0
  263. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  264. package/src/commands/low-family/notification.ts +116 -0
  265. package/src/commands/low-family/refine-config.ts +106 -0
  266. package/src/commands/low-family/session-host.ts +282 -0
  267. package/src/commands/low-family/spec-providerdev.ts +217 -0
  268. package/src/commands/low-family/status-meta.ts +112 -0
  269. package/src/commands/low-family/types.ts +39 -0
  270. package/src/commands/med-family/cli-agent.ts +241 -0
  271. package/src/commands/med-family/fast-forward.ts +230 -0
  272. package/src/commands/med-family/ide.ts +163 -0
  273. package/src/commands/med-family/index.ts +37 -0
  274. package/src/commands/med-family/mesh-crud.ts +1287 -0
  275. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  276. package/src/commands/med-family/mesh-queue.ts +167 -0
  277. package/src/commands/med-family/mesh-restart.ts +92 -0
  278. package/src/commands/med-family/types.ts +153 -0
  279. package/src/commands/mesh-coordinator.ts +334 -124
  280. package/src/commands/router-aggregate-status.ts +209 -0
  281. package/src/commands/router-mesh-session-owner.ts +114 -0
  282. package/src/commands/router-refine.ts +1711 -0
  283. package/src/commands/router-worktree-cleanup.ts +870 -0
  284. package/src/commands/router.ts +795 -4143
  285. package/src/commands/stream-commands.ts +8 -0
  286. package/src/commands/upgrade-helper.ts +310 -45
  287. package/src/config/chat-history.ts +517 -24
  288. package/src/config/config.ts +30 -0
  289. package/src/config/mesh-config.ts +632 -23
  290. package/src/config/mesh-json-config.ts +376 -0
  291. package/src/config/recent-activity.ts +8 -2
  292. package/src/config/registry-resolver.ts +100 -0
  293. package/src/config/repo-settings.ts +111 -0
  294. package/src/config/state-store.ts +55 -0
  295. package/src/daemon/dev-auto-implement.ts +3 -2
  296. package/src/daemon/dev-cli-debug.ts +10 -1
  297. package/src/daemon/dev-server.ts +0 -541
  298. package/src/detection/cli-detector.ts +94 -9
  299. package/src/detection/ide-detector.ts +55 -16
  300. package/src/detection/win32-ide-version.ts +106 -0
  301. package/src/git/change-impact-config.ts +354 -0
  302. package/src/git/git-commands.ts +112 -16
  303. package/src/git/git-diff.ts +81 -11
  304. package/src/git/git-executor.ts +12 -0
  305. package/src/git/git-status.ts +767 -48
  306. package/src/git/git-types.ts +14 -62
  307. package/src/git/git-worktree.ts +261 -4
  308. package/src/git/index.ts +17 -0
  309. package/src/index.ts +213 -13
  310. package/src/installer.d.ts +1 -1
  311. package/src/installer.ts +8 -6
  312. package/src/ipc/local-ipc-server.ts +278 -0
  313. package/src/launch.d.ts +1 -1
  314. package/src/launch.ts +37 -28
  315. package/src/logging/async-batch-writer.ts +55 -0
  316. package/src/logging/command-log.ts +7 -5
  317. package/src/logging/debug-config.ts +25 -0
  318. package/src/logging/debug-trace.ts +7 -2
  319. package/src/logging/log-redactor.ts +100 -0
  320. package/src/logging/log-tail-reader.ts +341 -0
  321. package/src/logging/logger.ts +14 -7
  322. package/src/mesh/contracts.ts +469 -0
  323. package/src/mesh/coordinator-prompt.ts +572 -34
  324. package/src/mesh/coordinator-registry.ts +121 -0
  325. package/src/mesh/mesh-active-work.ts +706 -0
  326. package/src/mesh/mesh-clone-grace.ts +68 -0
  327. package/src/mesh/mesh-completion-synthesis.ts +416 -0
  328. package/src/mesh/mesh-coordinator-config.ts +97 -0
  329. package/src/mesh/mesh-delivery-policy.ts +284 -0
  330. package/src/mesh/mesh-event-classify.ts +78 -0
  331. package/src/mesh/mesh-event-forwarding.ts +2002 -0
  332. package/src/mesh/mesh-event-trace.ts +67 -0
  333. package/src/mesh/mesh-events-coordinator.ts +32 -0
  334. package/src/mesh/mesh-events-pending.ts +1494 -0
  335. package/src/mesh/mesh-events-stale.ts +452 -0
  336. package/src/mesh/mesh-events-utils.ts +443 -0
  337. package/src/mesh/mesh-events.ts +43 -1035
  338. package/src/mesh/mesh-fast-forward.ts +856 -0
  339. package/src/mesh/mesh-host-ownership.ts +111 -0
  340. package/src/mesh/mesh-init.ts +350 -0
  341. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  342. package/src/mesh/mesh-ledger.ts +898 -102
  343. package/src/mesh/mesh-magi-status.ts +223 -0
  344. package/src/mesh/mesh-missions.ts +695 -0
  345. package/src/mesh/mesh-node-identity.ts +2065 -0
  346. package/src/mesh/mesh-queue-assignment.ts +2263 -0
  347. package/src/mesh/mesh-reconcile-acked-hold.ts +230 -0
  348. package/src/mesh/mesh-reconcile-config.ts +66 -0
  349. package/src/mesh/mesh-reconcile-identity.ts +103 -0
  350. package/src/mesh/mesh-reconcile-loop.ts +1473 -0
  351. package/src/mesh/mesh-reconcile-v2-backstop.ts +62 -0
  352. package/src/mesh/mesh-refine-batch.ts +205 -0
  353. package/src/mesh/mesh-refine-gates.ts +1686 -0
  354. package/src/mesh/mesh-refine-status.ts +231 -0
  355. package/src/mesh/mesh-remote-event-pull.ts +279 -0
  356. package/src/mesh/mesh-review-inbox.ts +308 -0
  357. package/src/mesh/mesh-routing.ts +291 -0
  358. package/src/mesh/mesh-runtime-store.ts +2150 -0
  359. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  360. package/src/mesh/mesh-task-inflight.ts +70 -0
  361. package/src/mesh/mesh-task-stats.ts +161 -0
  362. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  363. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  364. package/src/mesh/mesh-work-queue.ts +1437 -147
  365. package/src/mesh/preview-freshness.ts +163 -0
  366. package/src/mesh/refine-config.ts +423 -0
  367. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  368. package/src/providers/acp-provider-instance.ts +43 -10
  369. package/src/providers/approval-utils.d.ts +5 -0
  370. package/src/providers/approval-utils.ts +100 -6
  371. package/src/providers/chat-message-normalization.ts +126 -4
  372. package/src/providers/cli-provider-effect-format.ts +53 -0
  373. package/src/providers/cli-provider-history-dedup.ts +75 -0
  374. package/src/providers/cli-provider-input-prompt.ts +133 -0
  375. package/src/providers/cli-provider-instance-types.ts +131 -0
  376. package/src/providers/cli-provider-instance.ts +2709 -499
  377. package/src/providers/cli-provider-status-helpers.ts +123 -0
  378. package/src/providers/cli-provider-transcript-merge.ts +114 -0
  379. package/src/providers/contracts.d.ts +55 -0
  380. package/src/providers/contracts.ts +160 -6
  381. package/src/providers/extension-provider-instance.ts +12 -7
  382. package/src/providers/external-sources.ts +218 -0
  383. package/src/providers/ide-provider-instance.ts +35 -12
  384. package/src/providers/manual-attendance.ts +105 -0
  385. package/src/providers/native-history/antigravity-claim-registry.ts +138 -0
  386. package/src/providers/native-history/antigravity-cli-transcript.ts +1275 -0
  387. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  388. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  389. package/src/providers/native-history/constants.ts +19 -0
  390. package/src/providers/native-history/dispatcher.ts +617 -0
  391. package/src/providers/native-history/hermes-cli-transcript.ts +312 -0
  392. package/src/providers/native-history/index.ts +30 -0
  393. package/src/providers/provider-instance-manager.ts +71 -0
  394. package/src/providers/provider-instance.ts +24 -1
  395. package/src/providers/provider-loader.ts +700 -55
  396. package/src/providers/provider-schema.ts +87 -14
  397. package/src/providers/provider-trust.ts +114 -0
  398. package/src/providers/read-chat-contract.ts +76 -16
  399. package/src/providers/sdk/README.md +49 -0
  400. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  401. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  402. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  403. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  404. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  405. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  406. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  407. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  408. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  409. package/src/providers/sdk/v1/index.ts +152 -0
  410. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  411. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  412. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  413. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  414. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  415. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  416. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  417. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  418. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  419. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  420. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  421. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  422. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  423. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  424. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  425. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  426. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  427. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  428. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  429. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  430. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  431. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  432. package/src/providers/sdk/v1/validators/index.ts +19 -0
  433. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  434. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  435. package/src/providers/spec/adapter.ts +246 -0
  436. package/src/providers/spec/cli-adapter.ts +1064 -0
  437. package/src/providers/spec/evaluator.ts +407 -0
  438. package/src/providers/spec/fsm-driver.ts +1528 -0
  439. package/src/providers/spec/fsm-evaluator.ts +290 -0
  440. package/src/providers/spec/fsm-loader.ts +128 -0
  441. package/src/providers/spec/fsm-types.ts +301 -0
  442. package/src/providers/spec/native-history-executor.ts +1241 -0
  443. package/src/providers/spec/pre-launch-trust.ts +104 -0
  444. package/src/providers/spec/route.ts +51 -0
  445. package/src/providers/spec/types.ts +284 -0
  446. package/src/providers/status-monitor.d.ts +7 -7
  447. package/src/providers/status-monitor.ts +37 -22
  448. package/src/providers/transcript-v2.ts +567 -0
  449. package/src/providers/types/interactive-prompt.ts +536 -0
  450. package/src/providers/version-archive.ts +64 -24
  451. package/src/providers/working-dir.ts +23 -0
  452. package/src/repo-mesh-types.ts +868 -13
  453. package/src/runtime-defaults.ts +39 -0
  454. package/src/session-host/managed-host.ts +218 -0
  455. package/src/session-host/runtime-surface.ts +20 -80
  456. package/src/sessions/registry.ts +44 -0
  457. package/src/shared-types-extra.ts +2 -4
  458. package/src/shared-types.d.ts +8 -0
  459. package/src/shared-types.ts +136 -55
  460. package/src/status/builders.ts +26 -6
  461. package/src/status/chat-tail-hot-sessions.ts +117 -2
  462. package/src/status/normalize.ts +2 -0
  463. package/src/status/reporter.ts +19 -1
  464. package/src/status/snapshot.ts +95 -26
  465. package/src/system/hash.ts +23 -0
  466. package/src/system/host-memory.ts +29 -12
  467. package/src/system/load-better-sqlite3.ts +68 -0
  468. package/src/types.ts +5 -0
  469. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  470. package/dist/mesh/mesh-sync.d.ts +0 -53
  471. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  472. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  473. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,2263 @@
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, taskDependenciesSatisfied, meshTaskNotBeforeReady, meshTaskPriorityRank } 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 } from '../repo-mesh-types.js';
17
+ import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
18
+ import { normalizeMeshNodeId, meshNodeIdMatches, daemonIdsEquivalent, canonicalDaemonId, normalizeMeshWorkspaceForCompare, meshWorkspacesEquivalent, sessionIdsEquivalent, type MeshNodeIdentified } from '@adhdev/mesh-shared';
19
+ import { findTerminalLedgerEvidenceForTask, hasUnterminalDirectDispatchLedgerEntry } from './mesh-events-stale.js';
20
+ import { readNonEmptyString } from './mesh-events-utils.js';
21
+ import { readMeshNodeDaemonId } from './mesh-node-identity.js';
22
+ import { queuePendingMeshCoordinatorEvent, retractPendingDispatchBlockedEvent } from './mesh-events-pending.js';
23
+ import { isWorktreeBootstrapStaleRunning, shouldDeferDispatchForBootstrap } from './worktree-bootstrap-config.js';
24
+ import { isWithinCloneBootstrapGrace } from './mesh-clone-grace.js';
25
+ import { beginTaskDispatchInFlight, endTaskDispatchInFlight } from './mesh-task-inflight.js';
26
+
27
+ /**
28
+ * CANON: the single canonical coordinator-daemon id this daemon stamps onto every
29
+ * worker dispatch (meshContext.coordinatorDaemonId / sourceCoordinatorDaemonId / the
30
+ * co-located meshCoordinatorDaemonId anchor). loadConfig().machineId is the bare
31
+ * `mach_X` form; canonicalizing to `daemon_mach_X` unifies it with the MCP-side
32
+ * resolveCoordinatorDaemonId producer so the two dispatch paths can never stamp a
33
+ * worker's coordinator anchor in two different forms — the CANON-IDENTITY
34
+ * double-dispatch root cause. Consumers of the anchor already compare under
35
+ * daemonIdsEquivalent / expandDaemonIdForms, so the exact form is form-agnostic on
36
+ * the read side; this only removes the producer-side skew.
37
+ */
38
+ function localCoordinatorDaemonId(): string | undefined {
39
+ return canonicalDaemonId(readNonEmptyString(loadConfig().machineId));
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Idle auto fast-forward throttle state
44
+ // ---------------------------------------------------------------------------
45
+ const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
46
+ const idleAutoFastForwardLastAttempt = new Map<string, number>();
47
+
48
+ export function __resetIdleAutoFastForwardForTests(): void {
49
+ idleAutoFastForwardLastAttempt.clear();
50
+ }
51
+
52
+ export function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
53
+ const localMesh = getMesh(meshId);
54
+ const cachedMesh = components.router?.getCachedInlineMesh(meshId);
55
+ if (!localMesh) return cachedMesh;
56
+ if (!cachedMesh) return localMesh;
57
+ return mergeInlineCacheOnlyNodes(localMesh, cachedMesh);
58
+ }
59
+
60
+ /**
61
+ * Claim-time membership view unification (CLAIMSTALL fix).
62
+ *
63
+ * The coordinator's claim path — triggerMeshQueue → autoLaunch candidate filter
64
+ * and the local/remote idle-session drain — reads mesh membership through
65
+ * getMeshWithCache, which historically returned the local-config mesh verbatim
66
+ * whenever one existed. A freshly cloned worktree node is registered ONLY into the
67
+ * router's inline mesh cache: clone_mesh_node's `meshRecord.inline` branch calls
68
+ * updateInlineMeshNode, NOT addNode, so the worktree node never reaches local
69
+ * config (meshes.json). The config-first view therefore omits the worktree node,
70
+ * while send_task — which resolves membership through getMeshForCommand(preferInline)
71
+ * over the same inline cache — sees it. That view asymmetry is the stall: a queue
72
+ * task pinned to the worktree node reports `target_node_id_unmatched` (autoLaunch
73
+ * candidate filter / targetPinUnmatched check) and the node's idle session is
74
+ * dropped from the drain pool (mesh.nodes.find miss), so claim never fires and the
75
+ * task is stranded pending — even though nodeId matching itself is correct.
76
+ *
77
+ * Fix: union the local-config nodes with any inline-cache-ONLY nodes, so the claim
78
+ * view matches the command (send_task) view. Base (non-worktree) nodes present in
79
+ * local config stay config-authoritative — their entry is taken verbatim from
80
+ * localMesh, so base node claim/matching is byte-for-byte unchanged. Only nodes
81
+ * that exist solely in the inline cache (the cloned worktree nodes) are appended.
82
+ * Identity comparison uses the shared 3-form normalizer (id / nodeId / node_id),
83
+ * identical to every other claim-path consumer — the matching logic is untouched,
84
+ * only which nodes are visible.
85
+ */
86
+ function mergeInlineCacheOnlyNodes(localMesh: any, cachedMesh: any): any {
87
+ const localNodes = Array.isArray(localMesh?.nodes) ? localMesh.nodes : [];
88
+ const cachedNodes = Array.isArray(cachedMesh?.nodes) ? cachedMesh.nodes : [];
89
+ if (!cachedNodes.length) return localMesh;
90
+ const cacheOnly = cachedNodes.filter((cachedNode: any) => {
91
+ const cachedId = readMeshNodeId(cachedNode);
92
+ // Unidentifiable cache entries can never be a claim/route target — skip them
93
+ // rather than appending junk that no consumer can address.
94
+ if (!cachedId) return false;
95
+ return !localNodes.some((localNode: any) => meshNodeIdMatches(localNode, cachedId));
96
+ });
97
+ if (!cacheOnly.length) return localMesh;
98
+ return { ...localMesh, nodes: [...localNodes, ...cacheOnly] };
99
+ }
100
+
101
+ // ---------------------------------------------------------------------------
102
+ // Queue assignment
103
+ // ---------------------------------------------------------------------------
104
+
105
+ // Per-dispatch confirmation timeout (Bug B). A dispatch promise that never settles —
106
+ // a saturated remote P2P relay that hangs, or a transport that resolves only after
107
+ // the worker acks — would otherwise leave the just-claimed queue row 'assigned' with
108
+ // its delivery stuck 'delivering' forever: the .catch that requeues never fires, and
109
+ // PHASE 3 reconcile skips the row (it counts 0 pending). Racing the dispatch against
110
+ // this timeout guarantees a hung dispatch deterministically returns the task to
111
+ // 'pending' for re-dispatch. Generous so a merely-slow-but-live dispatch (a cold
112
+ // remote relay) is never reclaimed early; the reconcile assigned-stranded watchdog is
113
+ // the durable cross-restart backstop for a timer lost to a daemon restart.
114
+ const DISPATCH_CONFIRM_TIMEOUT_MS = 120_000;
115
+
116
+ // Cold-open connect budget for the warmup-aware REMOTE task dispatch deadline. A
117
+ // remote `agent_command` to a peer whose mesh DataChannel is not open yet first has
118
+ // to drive the cross-machine (often TURN-relayed) handshake; charging that warmup
119
+ // against the response budget is the same cold-open false-timeout the git_status
120
+ // probe path already guards against. This budget bounds ONLY the "channel not open
121
+ // yet" phase; once the channel is warm the DISPATCH_CONFIRM_TIMEOUT_MS response
122
+ // budget governs (identical to the legacy flat guard for an already-open peer, so
123
+ // no latency is added to a normal dispatch). Matches the daemon-cloud
124
+ // DaemonMeshManager CONNECT_TIMEOUT_MS (45s) so the caller-side deadline tracks the
125
+ // transport's own cold-open window rather than guessing.
126
+ //
127
+ // Sourced from the unified, env-overridable MESH_CONNECT_TIMEOUT_MS (runtime-defaults)
128
+ // — the SAME budget the router's direct-peer git_status probe uses. Previously this
129
+ // was a hard-coded 45_000 while the probe path was env-overridable, so setting the
130
+ // env tuned the probe but silently left this dispatch path at 45s (a silent
131
+ // asymmetry). They now move together.
132
+ const DISPATCH_CONNECT_TIMEOUT_MS = MESH_CONNECT_TIMEOUT_MS;
133
+
134
+ // Fail-loud (throttled) trace for a remote dispatch that ran with NO live mesh
135
+ // connection getter wired — the same degraded-warmup misconfiguration the git probe
136
+ // path warns about. Warn once per peer; resolveWarmupDeadlineOpts then falls back to
137
+ // the conservative combined budget instead of silently assuming "always warm".
138
+ const dispatchWarmupGetterMissingWarned = new Set<string>();
139
+ function warnDispatchWarmupGetterMissingOnce(daemonId: string): void {
140
+ if (dispatchWarmupGetterMissingWarned.has(daemonId)) return;
141
+ dispatchWarmupGetterMissingWarned.add(daemonId);
142
+ 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.`);
143
+ }
144
+
145
+ interface DeliverTaskContext {
146
+ meshId: string;
147
+ nodeId: string;
148
+ sessionId: string;
149
+ providerType: string;
150
+ task: MeshWorkQueueEntry;
151
+ transport: 'remote' | 'local';
152
+ sourceCoordinatorSessionId?: string;
153
+ sourceCoordinatorDaemonId?: string;
154
+ }
155
+
156
+ // Readiness barrier for the LOCAL auto-launch path. A just-spawned CLI session is
157
+ // not interactive until its PTY prints the input prompt (the adapter flips
158
+ // isReady() / settles to idle ~2-6s later). Poll the local adapter until it reports
159
+ // ready (or idle), bounded by a generous timeout so a slow/contended boot still
160
+ // lands, and a hard cap so a session that never becomes interactive doesn't block the
161
+ // reconcile loop forever (the adapter's queue-until-ready path is the backstop then).
162
+ const LOCAL_LAUNCH_READY_TIMEOUT_MS = 15_000;
163
+ const LOCAL_LAUNCH_READY_POLL_MS = 100;
164
+
165
+ async function waitForLocalSessionReady(components: DaemonComponents, sessionId: string): Promise<void> {
166
+ const adapter = components.cliManager?.adapters?.get(sessionId) as
167
+ | { isReady?: () => boolean; currentStatus?: string }
168
+ | undefined;
169
+ // No locally-resolvable adapter (e.g. a remote/forwarded session that somehow
170
+ // reached this branch) → nothing to wait on; let dispatch proceed.
171
+ if (!adapter || typeof adapter.isReady !== 'function') return;
172
+ const deadline = Date.now() + LOCAL_LAUNCH_READY_TIMEOUT_MS;
173
+ while (Date.now() < deadline) {
174
+ if (adapter.isReady() || adapter.currentStatus === 'idle') return;
175
+ await new Promise<void>(resolve => setTimeout(resolve, LOCAL_LAUNCH_READY_POLL_MS));
176
+ }
177
+ LOG.warn('MeshQueue', `Auto-launched session ${sessionId} not interactive after ${LOCAL_LAUNCH_READY_TIMEOUT_MS}ms; dispatching anyway (adapter queue-until-ready will buffer)`);
178
+ }
179
+
180
+ // CONS scope 3: the SINGLE source of truth for dispatching a claimed task to its
181
+ // session. The remote (P2P dispatchMeshCommand) and local (cliManager.handleCliCommand)
182
+ // branches differ ONLY in the transport call — the delivery record, the delivered/failed
183
+ // transitions, the pending-requeue-on-failure, the dispatch_failed ledger entry, AND the
184
+ // Bug B hang timeout are identical and live here once so a future change to the dispatch
185
+ // lifecycle cannot drift between the two paths. The caller passes a `dispatchThunk` that
186
+ // performs only the transport-specific send and returns its promise.
187
+ //
188
+ // Cold-open warmup (remote only): the REMOTE transport speaks over a P2P
189
+ // DataChannel that may still be opening when the first task is dispatched to a peer.
190
+ // When `warmup` is supplied the dispatch is awaited under the warmup-aware deadline
191
+ // (mesh-warmup-deadline) — the cold-open handshake is charged to the connect budget
192
+ // and only the warm round trip to the DISPATCH_CONFIRM_TIMEOUT_MS response budget —
193
+ // so the very first dispatch to a not-yet-open peer is no longer false-timed at the
194
+ // combined window. An already-open peer behaves identically to the legacy flat guard
195
+ // (response budget governs from t0), so a normal dispatch sees no added latency. The
196
+ // LOCAL transport (in-process cliManager) has no channel to warm up and keeps the
197
+ // flat Bug B hang guard.
198
+ function deliverTaskToSession(
199
+ dispatchThunk: () => Promise<unknown>,
200
+ ctx: DeliverTaskContext,
201
+ warmup?: { daemonId: string; getConnection?: (daemonId: string) => Record<string, unknown> | null },
202
+ ): void {
203
+ const delivery = createSessionDelivery({
204
+ meshId: ctx.meshId,
205
+ nodeId: ctx.nodeId,
206
+ sessionId: ctx.sessionId,
207
+ providerType: ctx.providerType,
208
+ taskId: ctx.task.id,
209
+ kind: 'task',
210
+ message: ctx.task.message,
211
+ status: 'delivering',
212
+ ...(ctx.sourceCoordinatorSessionId ? { sourceCoordinatorSessionId: ctx.sourceCoordinatorSessionId } : {}),
213
+ ...(ctx.sourceCoordinatorDaemonId ? { sourceCoordinatorDaemonId: ctx.sourceCoordinatorDaemonId } : {}),
214
+ });
215
+
216
+ // Invoke the transport synchronously (preserves the prior fire-and-forget timing,
217
+ // and lets a synchronous throw fall into the same failure path as a rejection).
218
+ let dispatchPromise: Promise<unknown>;
219
+ try {
220
+ dispatchPromise = Promise.resolve(dispatchThunk());
221
+ } catch (e) {
222
+ dispatchPromise = Promise.reject(e);
223
+ }
224
+
225
+ let timer: ReturnType<typeof setTimeout> | undefined;
226
+ let guarded: Promise<unknown>;
227
+ if (warmup) {
228
+ // Remote P2P: cold-open-aware deadline. awaitWithWarmupDeadline owns its own
229
+ // timers (so `timer` stays undefined and the clearTimeout below is a no-op),
230
+ // and rejects with Error('timeout') when either budget lapses — the same
231
+ // retryable failure shape the catch below already handles (requeue + ledger).
232
+ guarded = awaitWithWarmupDeadline(dispatchPromise, resolveWarmupDeadlineOpts({
233
+ getConnection: warmup.getConnection,
234
+ daemonId: warmup.daemonId,
235
+ connectTimeoutMs: DISPATCH_CONNECT_TIMEOUT_MS,
236
+ responseTimeoutMs: DISPATCH_CONFIRM_TIMEOUT_MS,
237
+ onMissingGetter: warnDispatchWarmupGetterMissingOnce,
238
+ }));
239
+ } else {
240
+ guarded = Promise.race([
241
+ dispatchPromise,
242
+ new Promise<never>((_, reject) => {
243
+ timer = setTimeout(
244
+ () => reject(new Error(`dispatch_confirm_timeout after ${DISPATCH_CONFIRM_TIMEOUT_MS}ms`)),
245
+ DISPATCH_CONFIRM_TIMEOUT_MS,
246
+ );
247
+ // Never keep the process alive solely for this confirm-timeout timer.
248
+ if (typeof (timer as { unref?: () => void })?.unref === 'function') (timer as { unref: () => void }).unref();
249
+ }),
250
+ ]);
251
+ }
252
+
253
+ guarded.then(() => {
254
+ if (timer) clearTimeout(timer);
255
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
256
+ }).catch((e: any) => {
257
+ if (timer) clearTimeout(timer);
258
+ // A dispatch failure (transport reject OR hang timeout) is most often transient —
259
+ // a busy/refusing adapter, or a relay that never acked — not a permanent task
260
+ // failure. Marking the task terminal here would permanently kill tasks a later
261
+ // tick delivers fine. Return it to 'pending' and record a retryable dispatch_failed
262
+ // ledger entry so the reconcile loop re-dispatches it. Identical for both transports.
263
+ LOG.error('MeshQueue', `Failed to dispatch task via ${ctx.transport} to node ${ctx.nodeId}: ${e?.message}`);
264
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
265
+ // The dispatch failed — the task is no longer in-flight (it returns to pending
266
+ // for a clean re-dispatch). Clear the single-flight mark so a legitimate
267
+ // requeue/re-claim is not blocked as if a worker were still generating.
268
+ endTaskDispatchInFlight(ctx.meshId, ctx.task.id);
269
+ updateTaskStatus(ctx.meshId, ctx.task.id, 'pending');
270
+ try {
271
+ appendLedgerEntry(ctx.meshId, {
272
+ kind: 'dispatch_failed' as any,
273
+ nodeId: ctx.nodeId,
274
+ sessionId: ctx.sessionId,
275
+ payload: { taskId: ctx.task.id, deliveryId: delivery.id, error: e?.message, retryable: true, transport: ctx.transport },
276
+ });
277
+ } catch { /* ledger write is best-effort */ }
278
+ });
279
+ }
280
+
281
+ // WTCLAIM: workspace normalization for base-vs-worktree comparison now lives in
282
+ // @adhdev/mesh-shared (normalizeMeshWorkspaceForCompare) so the enqueue→claim path,
283
+ // the mesh_status per-node session filter, and the read_chat node scope guard all
284
+ // share one comparison rule instead of drifting module-private copies.
285
+
286
+ export function tryAssignQueueTask(
287
+ components: DaemonComponents,
288
+ meshId: string,
289
+ nodeId: string,
290
+ sessionId: string,
291
+ providerType: string
292
+ ): boolean {
293
+ const mesh = getMeshWithCache(components, meshId);
294
+ // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
295
+ // `n.id` — a stamp-form nodeId vs the mesh node's config-form id must still
296
+ // resolve, mirroring the remote idle-session path below (:1341).
297
+ const node = mesh?.nodes.find((n: any) => meshNodeIdMatches(n, nodeId));
298
+
299
+ // WORKTREE-CLAIM-GATE-BYPASS: the SINGLE claim-time gate for the worktree-bootstrap defer.
300
+ // tryAssignQueueTask is the one funnel every claim path flows through — the event-driven
301
+ // agent:ready drain, the triggerMeshQueue idle-session drain (local + remote), the
302
+ // auto-launch claim, and the PHASE 3 reconcile re-drain all call it. The agent:ready handler
303
+ // (mesh-event-forwarding) deferred its OWN claim while a worktree node's bootstrap was still
304
+ // 'running', but it ALSO called setRemoteIdleSession first — registering the session as a
305
+ // claim candidate. A concurrent triggerMeshQueue drain then pulled that candidate and claimed
306
+ // through tryAssignQueueTask within ~0.16s, BYPASSING the event-handler-local defer: the task
307
+ // dispatched into a half-built worktree (native addons not yet installed → child daemon dies
308
+ // → empty session, totalMessages=0). The transport ack returns ok:true, so neither the
309
+ // assigned-stranded watchdog nor the pending-only PHASE 3 reconcile ever re-fires it → the
310
+ // session is stranded empty forever.
311
+ //
312
+ // Lowering the gate HERE makes the defer a property of the claim itself, not of one caller:
313
+ // a worktree node whose bootstrap is still 'running' can never be claimed from any path. The
314
+ // task stays pending (we return false WITHOUT touching its status — no fail/cancel), so the
315
+ // bootstrap_complete refire (triggerMeshQueue re-fired on worktree_bootstrap_complete) re-runs
316
+ // this claim and passes once status is no longer 'running'. The registered remote-idle session
317
+ // persists for REMOTE_IDLE_SESSION_TTL_MS (5min > observed ~2m8s bootstrap), so the refire
318
+ // still finds a live candidate to re-claim. Identity uses meshNodeIdMatches (the same shared
319
+ // 3-form normalizer the defer guard uses), never a raw === — canon-identity regression guard.
320
+ // Conservative: any non-'running' status (idle/complete/failed/absent/unknown) does NOT gate,
321
+ // so a base node and a fully-bootstrapped worktree keep prior behavior exactly.
322
+ // COMPLETION-PROPAGATION F7 (C2 SSOT): resolve the node's bootstrap status from the router's
323
+ // synchronous inline cache FIRST — the authoritative source markWorktreeBootstrapTerminalState
324
+ // stamps synchronously — falling back to the merged claim view only when the inline node carries
325
+ // no bootstrap status. getMeshWithCache takes a config-REGISTERED node verbatim from local
326
+ // config, whose bootstrap status lags the inline stamp (the detached async persist chain), so a
327
+ // config-registered worktree node could read a stale 'running' here and defer a claim whose
328
+ // bootstrap is already complete. Reading the inline node removes that stale-'running' defer,
329
+ // symmetric with the remote dispatch guard (cli-agent.ts F6). Conservative: only override with
330
+ // the inline node when it actually carries a status (an incomplete inline entry never masks a
331
+ // genuine config 'running').
332
+ const inlineBootstrapNode = (() => {
333
+ try {
334
+ const inlineMesh = components.router?.getCachedInlineMesh?.(meshId);
335
+ const inlineNode = Array.isArray(inlineMesh?.nodes)
336
+ ? inlineMesh.nodes.find((n: any) => meshNodeIdMatches(n, nodeId))
337
+ : undefined;
338
+ return readNonEmptyString(inlineNode?.worktreeBootstrap?.status) ? inlineNode : undefined;
339
+ } catch { return undefined; }
340
+ })();
341
+ const bootstrapGateNode = inlineBootstrapNode ?? node;
342
+ if ((bootstrapGateNode as { worktreeBootstrap?: { status?: string } } | undefined)?.worktreeBootstrap?.status === 'running') {
343
+ // Fix (3) safety net + F7: shouldDeferDispatchForBootstrap returns false when the 'running'
344
+ // state is stale (older than the backstop AND git-clean) — treat that as silently complete
345
+ // and allow the claim; otherwise defer (leave the task pending) so the claim re-fires once
346
+ // bootstrap reaches a terminal state and never dispatches into a half-built worktree.
347
+ if (!shouldDeferDispatchForBootstrap(bootstrapGateNode as any)) {
348
+ 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)`);
349
+ } else {
350
+ 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)`);
351
+ return false;
352
+ }
353
+ }
354
+
355
+ // WTCLAIM (fix-B extended to the enqueue→claim path): a base-targeted task must never be
356
+ // claimed by — and dispatched into — a co-located worktree-clone session, nor vice versa.
357
+ // The drain candidate's nodeId is derived from settings.meshNodeId || settings.nodeId
358
+ // (triggerMeshQueue), so a worktree session whose meshNodeId is empty/stale falls back to
359
+ // settings.nodeId = the BASE node id and impersonates the base node here. fix-B's worker-side
360
+ // workspace scope only ran for sessionless dispatch (meshScopeNodeId && !targetSessionId); the
361
+ // claim path ALWAYS carries a targetSessionId, so it never engaged. Apply the same scope here:
362
+ // for a LOCAL claiming session (adapter resolvable on this daemon), require its actual
363
+ // workingDir to match the target node's declared workspace. On a confirmed mismatch, refuse the
364
+ // claim so the task returns to pending for the correctly-scoped session/node to pull. Scoped to
365
+ // local sessions where the workspace is verifiable — a remote session lives on another daemon
366
+ // whose paths we cannot compare here (and remote candidates are already nodeId-matched from
367
+ // getRemoteIdleSessions). Conservative by design: when either workspace is unknown we do NOT
368
+ // skip, so a node with no declared workspace keeps its prior behavior and no legitimate claim
369
+ // is starved.
370
+ // WTDISPATCH (residual of WTCLAIM): the cross-node claim guard must reach EVERY claiming
371
+ // session this daemon can observe — not only those whose adapter happens to be in
372
+ // cliManager.adapters. An auto-launched worker session can carry its node binding on the
373
+ // CLI-instance settings while its session-host record shows no_node_binding, and the
374
+ // event-driven / remote-idle drain (agent:ready → setRemoteIdleSession → tryAssignQueueTask)
375
+ // can pass a nodeId that does NOT belong to the claiming session — a sibling worktree node
376
+ // on the SAME daemon. The adapter-only WTCLAIM check (rc.361/4c5b30b1) never engaged for a
377
+ // session observed solely via instanceManager, so session A could pull node B's task and
378
+ // node A's task was left with no session to claim it (no task_dispatched — it never dispatches).
379
+ //
380
+ // Resolve the claiming session's REAL identity from the adapter workingDir, then fall back to
381
+ // the live CLI instance's workspace + its stamped meshNodeId, and refuse a claim that
382
+ // contradicts EITHER (fail-closed). Reuses the shared meshWorkspacesEquivalent / meshNodeIdMatches
383
+ // comparators — no new comparison logic. Conservative: when neither the workspace NOR the stamp
384
+ // is resolvable we do NOT refuse, so a node with no declared workspace keeps prior behavior and
385
+ // a genuinely remote (cross-daemon) candidate stays nodeId-matched from getRemoteIdleSessions.
386
+ const localClaimAdapter = components.cliManager?.adapters?.get(sessionId) as { workingDir?: string } | undefined;
387
+ let claimInstanceWorkspace = '';
388
+ let claimStampedNodeId = '';
389
+ try {
390
+ const claimState = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
391
+ claimInstanceWorkspace = readNonEmptyString(claimState?.workspace);
392
+ const claimSettings = (claimState?.settings as Record<string, unknown>) || {};
393
+ claimStampedNodeId = readNonEmptyString(claimSettings.meshNodeId);
394
+ } catch { /* best-effort — fall through to the conservative (no refuse) path */ }
395
+
396
+ const nodeWorkspaceRaw = readNonEmptyString(node?.workspace);
397
+ const sessionWorkspaceRaw = readNonEmptyString(localClaimAdapter?.workingDir) || claimInstanceWorkspace;
398
+
399
+ if (claimStampedNodeId && nodeId) {
400
+ // The session carries its OWN meshNodeId stamp — its authoritative node identity, set when
401
+ // the coordinator launched/dispatched it (mesh-routing trusts this stamp FIRST). When it
402
+ // matches the claim target the session genuinely belongs to this node, so the stamp settles
403
+ // it and the workspace heuristic is skipped (a base/worktree pair can legitimately share a
404
+ // workspace). When it does NOT match, the claim is a cross-node leak — refuse, fail-closed.
405
+ if (!meshNodeIdMatches({ id: claimStampedNodeId } as MeshNodeIdentified, nodeId)) {
406
+ LOG.info('MeshQueue', `WTDISPATCH: refusing claim for node ${nodeId} (${sessionId}) — session is bound to node "${claimStampedNodeId}" (cross-node claim blocked)`);
407
+ return false;
408
+ }
409
+ } else if (sessionWorkspaceRaw && nodeWorkspaceRaw && !meshWorkspacesEquivalent(sessionWorkspaceRaw, nodeWorkspaceRaw)) {
410
+ // No stamp (the no_node_binding worker) — fall back to the workspace to tell two co-located
411
+ // sibling worktree sessions apart. WTCLAIM, now reaching instanceManager-observable sessions
412
+ // too. Conservative: unknown workspace on either side → do NOT refuse (no legitimate claim
413
+ // starved; a genuinely remote cross-daemon candidate stays nodeId-matched as before).
414
+ LOG.info('MeshQueue', `WTCLAIM: refusing claim for node ${nodeId} (${sessionId}) — session workspace "${normalizeMeshWorkspaceForCompare(sessionWorkspaceRaw)}" ≠ node workspace "${normalizeMeshWorkspaceForCompare(nodeWorkspaceRaw)}" (cross-workspace dispatch blocked)`);
415
+ return false;
416
+ }
417
+
418
+ const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
419
+ // Per-(node, provider) maxParallel cap (RepoMeshNodePolicy.providerRoles) layers
420
+ // on top of the global/taskMode caps — stricter wins. Resolved here where the
421
+ // claiming session's providerType + node policy are both known, then enforced
422
+ // inside the atomic claim transaction so concurrent claims can't overshoot it.
423
+ const providerMaxParallel = resolveProviderMaxParallel(node?.policy, providerType);
424
+ // WTDISPATCH-FANOUT: tell the atomic claim whether the claiming node is a worktree
425
+ // clone so a `convergence` task (base-only: merge → push → cleanup) is refused for
426
+ // worktree sessions. Without it, every sibling worktree session on this daemon could
427
+ // claim the same convergence intent and race push/production-deploy (the 4-way fan-out).
428
+ const nodeIsWorktree = node?.isLocalWorktree === true;
429
+ const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
430
+ providerType,
431
+ ...(providerMaxParallel !== undefined ? { providerMaxParallel } : {}),
432
+ nodeIsWorktree,
433
+ });
434
+ if (!task) {
435
+ return false;
436
+ }
437
+
438
+ const terminal = findTerminalLedgerEvidenceForTask({
439
+ meshId,
440
+ taskId: task.id,
441
+ });
442
+ if (terminal) {
443
+ const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
444
+ updateTaskStatus(meshId, task.id, status);
445
+ LOG.info('MeshQueue', `Skipped dispatch for terminal task ${task.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
446
+ traceMeshEventDrop('dispatch_terminal_ledger', {
447
+ taskId: task.id,
448
+ sessionId,
449
+ nodeId,
450
+ meshId,
451
+ event: 'agent_command',
452
+ }, terminal.kind);
453
+ return false;
454
+ }
455
+
456
+ LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
457
+
458
+ // FALSE-BLOCKER-CLONE-QUEUE (stale-event clear): the task just claimed and will dispatch,
459
+ // so any actionable blocker previously paged for it (e.g. a 'target_node_id_unmatched'
460
+ // emitted during the clone/bootstrap propagation window before the node became
461
+ // claimable) is now stale — re-arm the de-dup ledger and retract any undelivered
462
+ // dispatch_blocked event so the coordinator does not keep seeing a resolved blocker.
463
+ retractActionableSkipIfPreviouslyNotified(meshId, task.id);
464
+
465
+ // CANON-IDENTITY single-flight: mark the just-claimed task in-flight the moment it
466
+ // is handed to a transport. The atomic claim already prevents a concurrent claim,
467
+ // but this lets requeueTask distinguish a genuinely-generating task (refuse the
468
+ // operator requeue — it would open a second session) from a stale assigned row
469
+ // (still requeueable). Cleared when the task leaves `assigned` (terminal / dispatch
470
+ // failure / cancel / reclaim).
471
+ beginTaskDispatchInFlight(meshId, task.id);
472
+
473
+ // CANON-IDENTITY: read the remote daemon id through the normalizing helper so a node
474
+ // whose daemonId arrives in a non-top-level-camelCase serialization form (daemon_id /
475
+ // machine.daemonId / lastProbe.machine.daemon_id / …) is still recognized as remote.
476
+ // Reading raw `node.daemonId` here made the guard false for those forms, so the remote
477
+ // block was skipped and execution fell through to the LOCAL cliManager.handleCliCommand
478
+ // path — which has no adapter for the remote sessionId and threw
479
+ // 'Cannot read properties of undefined (reading handleCliCommand)'.
480
+ const remoteDaemonId = readMeshNodeDaemonId(node ?? {});
481
+ if (remoteDaemonId && components.dispatchMeshCommand) {
482
+ const isLocalNode = components.cliManager.adapters.has(sessionId);
483
+ if (!isLocalNode) {
484
+ const localDaemonIdForDispatch = localCoordinatorDaemonId();
485
+ // (3) Originating coordinator session that enqueued this task — route its
486
+ // completion back to that exact session (multi-coordinator). Carried over P2P
487
+ // to the remote worker, which echoes it on its completion event.
488
+ const sourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId) || undefined;
489
+ const dispatchMeshCommand = components.dispatchMeshCommand;
490
+ // CONS3: only the transport call differs — everything else (delivery record,
491
+ // status transitions, requeue-on-failure, ledger, Bug B hang timeout) is in
492
+ // the shared deliverTaskToSession helper.
493
+ deliverTaskToSession(
494
+ () => dispatchMeshCommand(remoteDaemonId, 'agent_command', {
495
+ targetSessionId: sessionId,
496
+ cliType: providerType,
497
+ action: 'send_chat',
498
+ message: task.message,
499
+ meshContext: {
500
+ meshId,
501
+ nodeId,
502
+ taskId: task.id,
503
+ ...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
504
+ ...(sourceCoordinatorSessionId ? { coordinatorSessionId: sourceCoordinatorSessionId } : {}),
505
+ },
506
+ }),
507
+ {
508
+ meshId,
509
+ nodeId,
510
+ sessionId,
511
+ providerType,
512
+ task,
513
+ transport: 'remote',
514
+ ...(sourceCoordinatorSessionId ? { sourceCoordinatorSessionId } : {}),
515
+ ...(localDaemonIdForDispatch ? { sourceCoordinatorDaemonId: localDaemonIdForDispatch } : {}),
516
+ },
517
+ // Warmup-aware deadline: this dispatch can be the FIRST command to a
518
+ // peer whose mesh DataChannel is still opening — charge the cold-open
519
+ // handshake to the connect budget, not the response budget.
520
+ { daemonId: remoteDaemonId, getConnection: components.getMeshPeerConnectionStatus },
521
+ );
522
+ return true;
523
+ }
524
+ }
525
+
526
+ // Stamp mesh context onto the session so completion events route correctly
527
+ // via setupMeshEventForwarding. Without this, manually-opened idle sessions
528
+ // (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
529
+ // agent:generating_completed is silently dropped as isMeshDelegate=false.
530
+ try {
531
+ const inst = components.instanceManager.getInstance(sessionId);
532
+ if (inst && typeof inst.updateSettings === 'function') {
533
+ // Adopting a (possibly manually-opened) local session as a worker: apply the
534
+ // delegated-worker auto-approve policy here too, so a session that was launched
535
+ // without autoApprove still auto-approves once the coordinator dispatches a task
536
+ // to it (the "approval notification fires only for certain delegated sessions"
537
+ // case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
538
+ //
539
+ // This local-dispatch branch also runs on the coordinator daemon for a co-located
540
+ // session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
541
+ // the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
542
+ // the anchor the forwarder keys on), matching what mesh_launch_session stamps.
543
+ const localDaemonId = localCoordinatorDaemonId();
544
+ const localSourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId);
545
+ inst.updateSettings({
546
+ meshNodeFor: meshId,
547
+ meshNodeId: nodeId,
548
+ launchedByCoordinator: true,
549
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
550
+ ...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
551
+ // COMPLETION-PROPAGATION F5: (re)stamp the coordinator SESSION anchor from THIS
552
+ // task's sourceCoordinatorSessionId with PRIORITY — a manually-launched (or reused)
553
+ // session may already carry a stale anchor from mesh_launch_session or a prior task,
554
+ // and a stale session anchor makes the completion unicast to the wrong/absent
555
+ // coordinator session (targetCoordinatorSessionId), stranding it. When this task
556
+ // carries a source, overwrite; when it carries NONE, CLEAR the anchor to undefined
557
+ // (updateSettings merges, so an explicit undefined overrides) so the completion
558
+ // cannot be misrouted by a stale unicast anchor and instead BROADCASTS — the real
559
+ // coordinator (which drains its own pending queue) then picks it up. Daemon-level
560
+ // routing (meshCoordinatorDaemonId above) is unaffected.
561
+ meshCoordinatorSessionId: localSourceCoordinatorSessionId || undefined,
562
+ });
563
+ }
564
+ } catch { /* best-effort — dispatch still proceeds */ }
565
+
566
+ // CONS3: same shared dispatch lifecycle as the remote branch — only the transport
567
+ // (cliManager.handleCliCommand) differs.
568
+ // ARCH-REFACTOR R1: carry meshContext (incl. taskId) on the LOCAL dispatch too, so
569
+ // handleCliCommand's send_chat path binds this task to its turn (per-turn identity).
570
+ // Previously only the remote branch shipped meshContext.taskId; the local path relied
571
+ // on the last-write-wins session scalar, which races a follow-up task and made the
572
+ // completion echo the wrong taskId (the standalone NOTIF-MISDELIVER repro).
573
+ deliverTaskToSession(
574
+ () => components.cliManager.handleCliCommand('agent_command', {
575
+ targetSessionId: sessionId,
576
+ cliType: providerType,
577
+ action: 'send_chat',
578
+ message: task.message,
579
+ meshContext: {
580
+ meshId,
581
+ nodeId,
582
+ taskId: task.id,
583
+ ...(localCoordinatorDaemonId() ? { coordinatorDaemonId: localCoordinatorDaemonId() } : {}),
584
+ ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { coordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
585
+ },
586
+ }),
587
+ {
588
+ meshId,
589
+ nodeId,
590
+ sessionId,
591
+ providerType,
592
+ task,
593
+ transport: 'local',
594
+ ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
595
+ ...(localCoordinatorDaemonId() ? { sourceCoordinatorDaemonId: localCoordinatorDaemonId() } : {}),
596
+ },
597
+ );
598
+
599
+ return true;
600
+ }
601
+
602
+ const autoLaunchInProgress = new Set<string>();
603
+ const autoLaunchCooldownUntil = new Map<string, number>();
604
+ const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
605
+ // A remote auto-launch (launch_cli forward) is fire-and-async: the worker session
606
+ // spawns, reaches idle, emits agent:ready, that ready is queued on the worker, pulled
607
+ // by this coordinator (reconcile PHASE 1), and only THEN claims the task. That round
608
+ // trip routinely exceeds the 5s per-(mesh,node) cooldown, so cooldown alone lets the
609
+ // reconcile loop fire a SECOND launch for the same still-pending task before the first
610
+ // session's claim lands — every tick spawns yet another orphan session (observed live:
611
+ // 26 sessions for one task). This is a per-TASK await-claim window: once a task has a
612
+ // successfully-launched session whose claim we are still waiting on, do not launch it
613
+ // again until the window lapses. It is generous (a slow remote spawn can take tens of
614
+ // seconds) but bounded so a launch that silently never reaches idle is eventually retried.
615
+ const AUTO_LAUNCH_AWAIT_CLAIM_MS = 90_000;
616
+
617
+ // AUTOLAUNCH-CLAIM-CHURN. For a REMOTE node the launch→claim handshake is purely
618
+ // event-sourced: the worker's agent:ready must be pulled (reconcile PHASE 1) to run
619
+ // setRemoteIdleSession before the drain can claim. If that pull is lost, nothing recovers,
620
+ // and after AUTO_LAUNCH_AWAIT_CLAIM_MS the loop used to blindly RESPAWN a new session — whose
621
+ // respawn guards (nodeHasLiveSessionPendingClaim / liveSessionCountForNode) scan only the LOCAL
622
+ // instanceManager, so the remote pending-claim session is invisible and a fresh ghost accumulates
623
+ // every ~90s (observed live 2026-07-04: task 8b188c64, and 7 ghost sessions on this worktree's
624
+ // own task at 11:23-11:34). Instead of respawning on window expiry, we re-drive the claim for the
625
+ // EXISTING session; when its liveness cannot be positively determined we EXTEND the window with
626
+ // exponential backoff (90 → 180 → 360s) and, only after the cap, deliver the task directly into
627
+ // the launched session (the mesh_send_task-equivalent) rather than spawning another worker.
628
+ const AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES = 2;
629
+ // Local mirror of REMOTE_IDLE_SESSION_TTL_MS (mesh-event-forwarding) — kept here to avoid a
630
+ // cross-module import cycle. Used when (re)registering a launched remote session as an idle
631
+ // claim candidate during the await-claim re-drive.
632
+ const AUTO_LAUNCH_REMOTE_IDLE_TTL_MS = 5 * 60 * 1000;
633
+
634
+ // Per-task await-claim backoff state, keyed `${meshId}::${taskId}`. `cycles` counts how many
635
+ // times the window has been extended; `nextAttemptAtMs` rate-limits the re-drive to the backoff
636
+ // cadence so the 4s reconcile tick does not hammer it. Cleared once the task claims, the direct
637
+ // dispatch fires, or a respawn is authorized. In-memory (per process); a stale entry is harmless
638
+ // (it only defers a respawn) and self-clears on the next resolution.
639
+ interface AwaitClaimBackoffState { cycles: number; nextAttemptAtMs: number; }
640
+ const autoLaunchAwaitClaimBackoff = new Map<string, AwaitClaimBackoffState>();
641
+
642
+ // Test hooks: reset / seed the await-claim backoff state between cases.
643
+ export function __resetAutoLaunchAwaitClaimBackoffForTests(): void {
644
+ autoLaunchAwaitClaimBackoff.clear();
645
+ }
646
+ export function __seedAutoLaunchAwaitClaimBackoffForTests(meshId: string, taskId: string, state: AwaitClaimBackoffState): void {
647
+ autoLaunchAwaitClaimBackoff.set(`${meshId}::${taskId}`, { ...state });
648
+ }
649
+
650
+ // Backoff window for a given cycle count: 90 → 180 → 360s (capped at the cap-cycle multiplier).
651
+ function awaitClaimWindowMs(cycles: number): number {
652
+ return AUTO_LAUNCH_AWAIT_CLAIM_MS * Math.pow(2, Math.min(cycles, AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES));
653
+ }
654
+
655
+ // Does the coordinator's remote-session view (MeshRuntimeStore remote idle sessions, populated by
656
+ // mesh event forwarding) currently show this session as a live idle claim candidate? Positive
657
+ // evidence the launched remote session is reachable — used to re-drive its claim directly instead
658
+ // of respawning. Absence is NOT proof the session is gone (the agent:ready pull may simply have
659
+ // been lost), so callers treat a false here as UNKNOWN liveness, never a definitive terminal.
660
+ function remoteSessionAppearsLive(meshId: string, sessionId: string): boolean {
661
+ if (!sessionId) return false;
662
+ try {
663
+ return MeshRuntimeStore.getInstance().getRemoteIdleSessions(meshId)
664
+ .some(s => sessionIdsEquivalent(s.sessionId, sessionId));
665
+ } catch {
666
+ return false;
667
+ }
668
+ }
669
+
670
+ // (A) Respawn-guard remote-awareness. The session ids of pending tasks whose auto-launch record
671
+ // targets `nodeId` (status started/completed with a sessionId) and is still inside its await-claim
672
+ // window — the base 90s window OR an active backoff extension. Such a session is ALREADY on its way
673
+ // to claim even when it is REMOTE (invisible to this daemon's instanceManager), so counting it
674
+ // suppresses a duplicate launch that would otherwise spawn a ghost.
675
+ function inWindowAutoLaunchSessionIdsForNode(meshId: string, nodeId: string): string[] {
676
+ const nowMs = Date.now();
677
+ const out: string[] = [];
678
+ for (const task of getQueue(meshId, { status: ['pending'] as any })) {
679
+ const al = task.autoLaunch;
680
+ const sid = al ? readNonEmptyString(al.sessionId) : '';
681
+ if (!al || (al.status !== 'started' && al.status !== 'completed') || !sid) continue;
682
+ if (!daemonIdsEquivalent(al.nodeId, nodeId)) continue;
683
+ const launchedAtMs = Date.parse(al.updatedAt);
684
+ const inBaseWindow = Number.isFinite(launchedAtMs) && nowMs - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
685
+ const inBackoff = autoLaunchAwaitClaimBackoff.has(`${meshId}::${task.id}`);
686
+ if (inBaseWindow || inBackoff) out.push(sid);
687
+ }
688
+ return out;
689
+ }
690
+
691
+ // De-dup for repeated `skipped` ledger noise: the reconcile loop re-runs the queue
692
+ // trigger every 4s, so a task that can't be claimed (e.g. a remote node with no
693
+ // transport, or a node under cooldown) would otherwise append an identical
694
+ // session_auto_launch{phase:'skipped'} entry on every tick — flooding the ledger.
695
+ // We suppress a `skipped` ledger append when the immediately-prior recorded event
696
+ // for that task was the SAME (phase, reason). Any non-skip phase (started/failed/
697
+ // completed) or a changed reason resets the de-dup so real transitions still record.
698
+ const lastAutoLaunchLedgerKey = new Map<string, string>();
699
+ const AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2000;
700
+
701
+ // Fix (1): actionable dispatch-skip notification.
702
+ //
703
+ // User-core gap: when a queued task cannot be dispatched the coordinator (Claude Code via
704
+ // MCP) had no proactive signal — the skip was only recorded to task.autoLaunch + the ledger,
705
+ // both of which the coordinator must poll to discover. For a skip that will NOT self-resolve
706
+ // (a routing miss, no capable node, a convergence task pinned to a worktree, an unusable
707
+ // provider, an unreachable remote, or a dirty workspace) the coordinator could sit waiting
708
+ // for a dispatch that can never happen. We now actively surface those — and ONLY those — as a
709
+ // pending coordinator event carrying a "why + how to act" message, routed to the originating
710
+ // coordinator (sourceCoordinator*). Transient/back-pressure skips (cooldown, in-progress,
711
+ // awaiting-claim, parallel/session caps, node not yet launch-ready, an active assignment) are
712
+ // deliberately excluded: they clear on their own and would only spam the coordinator every 4s.
713
+ const ACTIONABLE_SKIP_REASON_PREFIXES = [
714
+ 'target_node_id_unmatched',
715
+ 'no_node_satisfies_required_tags',
716
+ 'mesh_convergence_target_is_worktree',
717
+ 'remote_auto_launch_unsupported',
718
+ 'remote_auto_launch_no_coordinator_daemon_id',
719
+ 'missing_provider_priority',
720
+ 'provider_loader_unavailable',
721
+ 'provider_priority_unusable',
722
+ 'provider_unusable',
723
+ 'dirty_workspace',
724
+ ];
725
+
726
+ // FALSE-BLOCKER-CLONE-QUEUE: the TRANSIENT counterpart of 'target_node_id_unmatched'. A
727
+ // queue task pinned to a freshly cloned worktree node can transiently find no matching node
728
+ // (its inline-cache entry has not propagated to this coordinator daemon yet, and/or its
729
+ // worktree bootstrap is still running). That unmatch SELF-RESOLVES — it is not the permanent
730
+ // routing miss the actionable blocker exists for — so it is deliberately NOT listed in
731
+ // ACTIONABLE_SKIP_REASON_PREFIXES: isActionableSkipReason() returns false for it, so no
732
+ // "actionable blocker — will NOT clear on its own" coordinator page is emitted. The skip is
733
+ // still recorded to task.autoLaunch + the ledger for diagnosability.
734
+ const TRANSIENT_TARGET_NODE_BOOTSTRAP_PENDING_REASON = 'target_node_bootstrap_pending';
735
+
736
+ // De-dup actionable-skip coordinator notifications: emit once per (mesh, task) until the
737
+ // reason CHANGES, so the 4s reconcile loop re-marking the same skip does not re-notify. A
738
+ // non-skip transition (or a genuine reason change) re-arms it. In-memory only — a daemon
739
+ // restart re-notifies once, which is the correct behaviour after a restart.
740
+ const lastActionableSkipNotified = new Map<string, string>();
741
+
742
+ function isActionableSkipReason(reason?: string): boolean {
743
+ if (!reason) return false;
744
+ return ACTIONABLE_SKIP_REASON_PREFIXES.some(prefix => reason === prefix || reason.startsWith(prefix));
745
+ }
746
+
747
+ /**
748
+ * FALSE-BLOCKER-CLONE-QUEUE: a target pin is TRANSIENTLY (not permanently) unresolved when
749
+ * the pinned node is a freshly cloned worktree that will auto-claim once its bootstrap
750
+ * completes / its inline-cache entry propagates — as opposed to a removed/dead node whose
751
+ * unmatch is a permanent, actionable routing miss. Two signals, either suffices:
752
+ * (a) the node IS visible in the (cache-merged) mesh view but its worktree bootstrap is
753
+ * still 'running' (and not stuck past the stale backstop), or
754
+ * (b) the node is NOT visible here yet, but a clone for its id was issued within the grace
755
+ * window (propagation/bootstrap latency) — see mesh-clone-grace.
756
+ * Conservative: a node neither bootstrap-running nor recently cloned → returns false, so a
757
+ * genuinely dead node keeps its permanent, actionable 'target_node_id_unmatched'.
758
+ */
759
+ function isTargetNodeTransientlyUnresolved(mesh: any, task: MeshWorkQueueEntry): boolean {
760
+ const targetNodeId = readNonEmptyString(task.targetNodeId);
761
+ if (!targetNodeId) return false;
762
+ const node = Array.isArray(mesh?.nodes)
763
+ ? mesh.nodes.find((n: any) => meshNodeIdMatches(n, targetNodeId))
764
+ : undefined;
765
+ if (node
766
+ && (node as { worktreeBootstrap?: { status?: string } }).worktreeBootstrap?.status === 'running'
767
+ && !isWorktreeBootstrapStaleRunning(node)) {
768
+ return true;
769
+ }
770
+ return isWithinCloneBootstrapGrace(targetNodeId);
771
+ }
772
+
773
+ /**
774
+ * FALSE-BLOCKER-CLONE-QUEUE (stale-event clear): once a task whose actionable blocker we
775
+ * previously paged either gets claimed or transitions to a self-resolving state, re-arm the
776
+ * de-dup ledger (so a later genuine blocker re-notifies) AND retract any still-undelivered
777
+ * dispatch_blocked pending event, so the coordinator's pending queue no longer carries the
778
+ * stale "will NOT clear on its own" warning. Cheap: only touches the pending store when this
779
+ * (mesh, task) actually had a prior actionable notification recorded.
780
+ */
781
+ function retractActionableSkipIfPreviouslyNotified(meshId: string, taskId: string): void {
782
+ const dedupKey = `${meshId}:${taskId}`;
783
+ if (!lastActionableSkipNotified.delete(dedupKey)) return; // nothing was paged → nothing to retract
784
+ try {
785
+ const coordinatorDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
786
+ const removed = retractPendingDispatchBlockedEvent(meshId, taskId, coordinatorDaemonId);
787
+ if (removed > 0) {
788
+ LOG.info('MeshQueue', `Retracted ${removed} stale dispatch-blocked event(s) for task ${taskId} (mesh ${meshId}) — its blocker resolved`);
789
+ }
790
+ } catch (e: any) {
791
+ LOG.warn('MeshQueue', `Failed to retract stale dispatch-blocked event for task ${taskId} (mesh ${meshId}): ${e?.message || e}`);
792
+ }
793
+ }
794
+
795
+ function actionableSkipGuidance(reason: string): { summary: string; nextAction: string } {
796
+ if (reason === 'target_node_id_unmatched') return {
797
+ 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)',
798
+ 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).',
799
+ };
800
+ if (reason === 'no_node_satisfies_required_tags') return {
801
+ summary: "no node in the mesh can satisfy the task's required capability tags",
802
+ nextAction: "Relax the task's requiredTags, or add/launch a node whose provider produces the required capabilities.",
803
+ };
804
+ if (reason === 'mesh_convergence_target_is_worktree') return {
805
+ summary: 'it is a convergence task (base-only: merge → push → cleanup) but every candidate node is a worktree clone',
806
+ nextAction: 'Dispatch the convergence task to the base node, or run the deterministic fast-forward path (mesh_fast_forward_node / mesh_refine_node) instead.',
807
+ };
808
+ if (reason.startsWith('remote_auto_launch')) return {
809
+ 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)',
810
+ nextAction: 'Launch a session on that node yourself with mesh_launch_session, or ensure the remote daemon is connected over P2P.',
811
+ };
812
+ if (reason.startsWith('provider') || reason === 'missing_provider_priority') return {
813
+ summary: 'the node has no usable provider for this task (provider priority missing/unusable, or the provider loader is unavailable)',
814
+ nextAction: "Check the node's providerPriority policy and that the required CLI/ACP provider is installed and enabled on that machine.",
815
+ };
816
+ if (reason === 'dirty_workspace') return {
817
+ summary: "the node's workspace is dirty, so auto-launch is blocked to avoid clobbering uncommitted changes",
818
+ nextAction: "Clean or commit the node's working tree (or fast-forward it); the task will then auto-assign.",
819
+ };
820
+ return {
821
+ summary: `it cannot be dispatched (${reason})`,
822
+ nextAction: 'Inspect the node/mesh state with mesh_status and resolve the blocker, or re-enqueue the task.',
823
+ };
824
+ }
825
+
826
+ /** Surface a non-self-resolving dispatch skip to the originating coordinator as a pending
827
+ * event (so it is delivered actively, not only on poll). De-duped per (mesh, task, reason). */
828
+ function notifyCoordinatorOfActionableSkip(meshId: string, taskId: string, reason: string | undefined, nodeId?: string): void {
829
+ if (!isActionableSkipReason(reason)) return;
830
+ // FALSE-BLOCKER-CLONE-QUEUE chokepoint defense: a 'target_node_id_unmatched' skip whose
831
+ // node was cloned within the grace window is a TRANSIENT propagation/bootstrap gap that
832
+ // auto-clears, not a permanent routing miss — never page the coordinator for it (the
833
+ // reason classifier upstream already routes the common case to the transient reason; this
834
+ // is the single-funnel backstop for any path that still labels it as the permanent reason).
835
+ if (reason === 'target_node_id_unmatched' && isWithinCloneBootstrapGrace(readNonEmptyString(nodeId))) return;
836
+ const dedupKey = `${meshId}:${taskId}`;
837
+ if (lastActionableSkipNotified.get(dedupKey) === reason) return;
838
+ lastActionableSkipNotified.set(dedupKey, reason!);
839
+ if (lastActionableSkipNotified.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
840
+ const oldest = lastActionableSkipNotified.keys().next().value;
841
+ if (oldest !== undefined) lastActionableSkipNotified.delete(oldest);
842
+ }
843
+ let task: MeshWorkQueueEntry | undefined;
844
+ try { task = getQueue(meshId).find(t => t.id === taskId); } catch { /* best-effort */ }
845
+ // The queue is owned by this coordinator daemon, so scope the event to this daemon's id;
846
+ // the originating coordinator SESSION (if known) further narrows delivery on this daemon.
847
+ const targetCoordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
848
+ const targetCoordinatorSessionId = readNonEmptyString(task?.sourceCoordinatorSessionId);
849
+ const nodeLabel = readNonEmptyString(nodeId) || readNonEmptyString(task?.targetNodeId);
850
+ const { summary, nextAction } = actionableSkipGuidance(reason!);
851
+ 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.`;
852
+ try {
853
+ queuePendingMeshCoordinatorEvent({
854
+ event: 'mesh:dispatch_blocked',
855
+ meshId,
856
+ nodeLabel: nodeLabel || meshId,
857
+ ...(nodeLabel ? { nodeId: nodeLabel } : {}),
858
+ metadataEvent: {
859
+ source: 'mesh_queue_dispatch_skip',
860
+ taskId,
861
+ reason,
862
+ ...(nodeLabel ? { nodeId: nodeLabel } : {}),
863
+ coordinatorMessage,
864
+ },
865
+ coordinatorMessage,
866
+ queuedAt: Date.now(),
867
+ ...(targetCoordinatorDaemonId ? { targetCoordinatorDaemonId } : {}),
868
+ ...(targetCoordinatorSessionId ? { targetCoordinatorSessionId } : {}),
869
+ });
870
+ } catch (e: any) {
871
+ LOG.warn('MeshQueue', `Failed to surface actionable dispatch-skip (${reason}) for task ${taskId}: ${e?.message || e}`);
872
+ }
873
+ }
874
+
875
+ function sweepExpiredCooldowns(): void {
876
+ const now = Date.now();
877
+ for (const [key, until] of autoLaunchCooldownUntil) {
878
+ if (now >= until) autoLaunchCooldownUntil.delete(key);
879
+ }
880
+ }
881
+
882
+ function normalizeProviderPriority(policy: unknown): string[] {
883
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
884
+ ? (policy as Record<string, unknown>).providerPriority
885
+ : undefined;
886
+ if (!Array.isArray(raw)) return [];
887
+ const seen = new Set<string>();
888
+ return raw
889
+ .map(type => typeof type === 'string' ? type.trim() : '')
890
+ .filter(Boolean)
891
+ .filter(type => {
892
+ if (seen.has(type)) return false;
893
+ seen.add(type);
894
+ return true;
895
+ });
896
+ }
897
+
898
+ function isTerminalSessionStatus(status: string): boolean {
899
+ return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
900
+ }
901
+
902
+ function isIdleSessionState(state: any): boolean {
903
+ const status = readNonEmptyString(state?.status).toLowerCase();
904
+ if (isTerminalSessionStatus(status)) return false;
905
+ return status === 'idle' || state?.activeChat?.status === 'waiting_input';
906
+ }
907
+
908
+ function isDirtyNode(node: any): boolean {
909
+ return node?.health === 'dirty' || node?.git?.dirty === true;
910
+ }
911
+
912
+ function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
913
+ const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
914
+ ? mesh.policy.autoFastForward as Record<string, unknown>
915
+ : {};
916
+ const maxBehind = Number(record.maxBehind);
917
+ return {
918
+ enabled: record.enabled !== false,
919
+ ...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
920
+ requireCleanSubmodules: record.requireCleanSubmodules !== false,
921
+ };
922
+ }
923
+
924
+ function sessionStateLooksActive(state: any): boolean {
925
+ const status = readNonEmptyString(state?.status).toLowerCase();
926
+ const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
927
+ // 'long_generating' is retained as a legacy alias for the renamed 'no_progress' busy status.
928
+ const active = new Set(['generating', 'streaming', 'no_progress', 'long_generating', 'working', 'starting', 'waiting_approval']);
929
+ return active.has(status) || active.has(chatStatus);
930
+ }
931
+
932
+ function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
933
+ if (nodeHasActiveAssignment(meshId, nodeId)) return true;
934
+ return components.instanceManager.getByCategory('cli').some((inst: any) => {
935
+ const state = inst.getState();
936
+ const settings = state.settings as Record<string, unknown> || {};
937
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
938
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
939
+ // Match under canonical machine-core form, NOT a raw `!==`: a session's stamped
940
+ // meshNodeId and the candidate nodeId can carry interchangeable daemon-id forms
941
+ // (bare `mach_X` vs `daemon_mach_X`). A raw mismatch makes a BUSY node look idle,
942
+ // so the active-work gate passes and a SECOND session is launched/claimed for a
943
+ // task already running here — the CANON-IDENTITY duplicate dispatch.
944
+ if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
945
+ const sessionId = readNonEmptyString(state.instanceId);
946
+ if (currentSessionId && sessionIdsEquivalent(sessionId, currentSessionId) && isIdleSessionState(state)) return false;
947
+ return sessionStateLooksActive(state);
948
+ });
949
+ }
950
+
951
+ function isLaunchableNode(node: any): boolean {
952
+ if (!node || node.status === 'disabled' || node.status === 'removed') return false;
953
+ const health = readNonEmptyString(node.health).toLowerCase();
954
+ if (!health) return true;
955
+ return health === 'online' || health === 'unknown';
956
+ }
957
+
958
+ /** Whether a mesh node's daemon/machine identity resolves to THIS coordinator daemon
959
+ * (i.e. the queue session can be spawned by a direct local `launch_cli`). */
960
+ function isLocalAutoLaunchNode(node: any): boolean {
961
+ const daemonId = readNonEmptyString(node?.daemonId);
962
+ const machineId = readNonEmptyString(node?.machineId);
963
+ const appConfig = loadConfig();
964
+ const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
965
+
966
+ // Route BOTH the daemonId and the machineId through the canonical machine-core
967
+ // equivalence helper so a node carrying any interchangeable id form (bare `mach_<hex>`
968
+ // or a `daemon_`/`standalone_` prefixed form) resolves to THIS coordinator instead of
969
+ // being misjudged as remote. machineId used to use a raw `===`, which — AND-combined
970
+ // with the daemonId match — would misjudge a local node as remote whenever a
971
+ // form-mismatched machineId arrived, dispatching a local task to a remote node (B-2).
972
+ const daemonMatchesLocal = !daemonId || daemonIdsEquivalent(daemonId, localMachineId);
973
+ const machineMatchesLocal = !machineId || daemonIdsEquivalent(machineId, localMachineId);
974
+
975
+ if (node?.isLocalWorktree === true) {
976
+ return daemonMatchesLocal && machineMatchesLocal;
977
+ }
978
+ if (daemonId || machineId) {
979
+ return daemonMatchesLocal && machineMatchesLocal;
980
+ }
981
+ return true;
982
+ }
983
+
984
+ /**
985
+ * Resolve how a pending queue task should be auto-launched onto a node.
986
+ *
987
+ * - `local`: spawn directly on this daemon via cliManager.handleCliCommand('launch_cli').
988
+ * - `remote`: forward `launch_cli` to the node's daemon via dispatchMeshCommand
989
+ * (mirrors what mesh_launch_session does). Requires dispatchMeshCommand AND a
990
+ * resolvable coordinator daemonId for relay-safe completion routing.
991
+ * - `skip`: not launchable from here — carries the reason (e.g. a remote node with
992
+ * no dispatch transport, or no coordinator daemonId to stamp).
993
+ */
994
+ function resolveAutoLaunchTarget(components: DaemonComponents, node: any): {
995
+ mode: 'local' | 'remote' | 'skip';
996
+ reason?: string;
997
+ daemonId?: string;
998
+ coordinatorDaemonId?: string;
999
+ } {
1000
+ if (isLocalAutoLaunchNode(node)) return { mode: 'local' };
1001
+
1002
+ // Remote node. Forwarding the launch is possible only with a dispatch transport
1003
+ // (cloud mode) plus a coordinator daemonId to stamp into the worker so completion
1004
+ // events route back here. Without either, fall back to a graceful skip.
1005
+ //
1006
+ // CANON-IDENTITY: read the daemonId through the normalizing helper (same defect class
1007
+ // as the dispatch guard above). A raw `node.daemonId` read misses non-top-level-camelCase
1008
+ // serialization forms (daemon_id / machine.daemonId / lastProbe.machine.daemon_id / …),
1009
+ // so a genuinely-remote node arriving in one of those forms read empty here and was
1010
+ // wrongly skipped as `remote_auto_launch_unsupported`. readMeshNodeDaemonId returns
1011
+ // undefined (falsy) when absent — equivalent to the old readNonEmptyString + !daemonId
1012
+ // guard, so local/self auto-launch is unchanged.
1013
+ const daemonId = readMeshNodeDaemonId(node ?? {});
1014
+ if (!daemonId) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
1015
+ if (!components.dispatchMeshCommand) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
1016
+ // CANON: stamp the canonical `daemon_mach_` coordinator anchor onto the remote
1017
+ // worker (meshCoordinatorDaemonId) so its completion forwards back under the same
1018
+ // form every other dispatch path uses — no producer-side coordinator-id skew.
1019
+ const coordinatorDaemonId = localCoordinatorDaemonId();
1020
+ if (!coordinatorDaemonId) return { mode: 'skip', reason: 'remote_auto_launch_no_coordinator_daemon_id' };
1021
+ return { mode: 'remote', daemonId, coordinatorDaemonId };
1022
+ }
1023
+
1024
+ function activeAssignedCount(meshId: string): number {
1025
+ return getQueue(meshId, { status: ['assigned'] as any }).length;
1026
+ }
1027
+
1028
+ /** Active assignments that hold the one-active-per-node / global-parallel invariant
1029
+ * (everything except read-only diagnoses, which run unbounded by the write cap). */
1030
+ export function activeWriteAssignedCount(meshId: string): number {
1031
+ return getQueue(meshId, { status: ['assigned'] as any })
1032
+ .filter(task => !isTaskReadonly(task)).length;
1033
+ }
1034
+
1035
+ /** Active read-only assignments, for the read-only safety cap. */
1036
+ export function activeReadonlyAssignedCount(meshId: string): number {
1037
+ return getQueue(meshId, { status: ['assigned'] as any })
1038
+ .filter(isTaskReadonly).length;
1039
+ }
1040
+
1041
+ function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
1042
+ // Canonical-form match, NOT a raw `===`: an assigned row stamped in one daemon-id
1043
+ // form (e.g. `daemon_mach_X`) must still register as this node's active work when
1044
+ // the candidate nodeId arrives bare (`mach_X`). A raw mismatch makes the node look
1045
+ // free, letting a second write task auto-launch onto an already-busy node and
1046
+ // breaking the one-write-per-node (worktree isolation) invariant.
1047
+ return getQueue(meshId, { status: ['assigned'] as any }).some(task => daemonIdsEquivalent(task.assignedNodeId, nodeId));
1048
+ }
1049
+
1050
+ /** Active (status='assigned') task count for a node — the load metric for
1051
+ * least-loaded / round-robin ranking. Lower = preferred. */
1052
+ function nodeActiveLoad(meshId: string, nodeId: string): number {
1053
+ return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
1054
+ }
1055
+
1056
+ /**
1057
+ * The mesh-wide scheduling strategy, read from the MACHINE-LOCAL stored mesh
1058
+ * policy. Resolution order:
1059
+ * 1. the stored mesh policy schedulingStrategy raw 4-union, then
1060
+ * 2. 'first_eligible' (strict no-change default).
1061
+ * Policy is machine-local only — there is no repo-file (`.adhdev/mesh.json`)
1062
+ * overlay. Only governs the final tie-break; eligibility, capacity, and priority
1063
+ * gates apply identically to every strategy.
1064
+ */
1065
+ function resolveSchedulingStrategy(mesh: any): RepoMeshSchedulingStrategy {
1066
+ return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
1067
+ }
1068
+
1069
+ /**
1070
+ * Order eligible nodes for assignment per the mesh scheduling pipeline:
1071
+ * PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
1072
+ *
1073
+ * The caller has already applied the TAG hard-filter and is responsible for the
1074
+ * MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
1075
+ * decides the *preference order* among nodes that are otherwise eligible.
1076
+ *
1077
+ * - 'first_eligible' (default): returns the input order verbatim and does NOT touch
1078
+ * the round-robin cursor — byte-for-byte the pre-feature behavior.
1079
+ * - 'priority_only': schedulingPriority desc, then input order (load ignored).
1080
+ * - 'least_loaded' (the user-facing 'spread' mode): schedulingPriority desc, then
1081
+ * active load asc, then — among nodes still tied at (priority, load) — the input
1082
+ * order is rotated by a per-mesh cursor that advances once per pass. The rotation
1083
+ * tie-break is ALWAYS on for least_loaded so a single 'spread' mode subsumes the
1084
+ * former separate 'round_robin' strategy (two equal-load nodes still alternate
1085
+ * fairly across passes instead of the lower index always winning).
1086
+ * - 'round_robin': retained as an escape-hatch alias; behaves identically to
1087
+ * 'least_loaded' now that least_loaded carries the rotation.
1088
+ *
1089
+ * `nodes` carries the original config/array index so the tie-break can fall back to
1090
+ * deterministic input order. `bumpCursor` advances the round-robin cursor exactly
1091
+ * once per scheduling pass (consulted for both 'least_loaded' and 'round_robin').
1092
+ */
1093
+ interface RankableNode { nodeId: string; node: any; index: number }
1094
+
1095
+ /** Test-only: resolve a mesh's effective scheduling strategy through the full
1096
+ * LOCAL-WINS path (`.adhdev/mesh.json` distribution → strategy, else stored policy).
1097
+ * Exposed so the repo-file overlay wiring can be exercised by a direct call. */
1098
+ export function __resolveSchedulingStrategyForTests(mesh: any): RepoMeshSchedulingStrategy {
1099
+ return resolveSchedulingStrategy(mesh);
1100
+ }
1101
+
1102
+ /** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
1103
+ * scheduling pipeline can be unit-tested without standing up live CLI sessions. */
1104
+ export function __orderEligibleNodesForTests(
1105
+ meshId: string,
1106
+ strategy: RepoMeshSchedulingStrategy,
1107
+ nodes: RankableNode[],
1108
+ opts?: { bumpCursor?: boolean },
1109
+ ): RankableNode[] {
1110
+ return orderEligibleNodes(meshId, strategy, nodes, opts);
1111
+ }
1112
+
1113
+ /** One idle session eligible to claim a queued task, together with the resolved
1114
+ * mesh node record it belongs to. Local candidates come from live CLI instances,
1115
+ * remote candidates from the registered remote-idle-session store; the two arrive
1116
+ * with their `nodeId` under different serialization forms. */
1117
+ type IdleCandidate = { nodeId: string; sessionId: string; providerType: string; origin: 'local' | 'remote'; node: any };
1118
+
1119
+ /**
1120
+ * Merge local + remote idle candidates into the scheduling pool with a single,
1121
+ * form-canonical node identity.
1122
+ *
1123
+ * INVARIANT: every candidate in the returned pool carries its `nodeId` in
1124
+ * CANONICAL (normalized) form, and `uniqueNodes` has exactly one entry per
1125
+ * physical node. Local and remote candidates arrive with their `nodeId` under
1126
+ * mixed forms (config `id`, wire `nodeId`, DB `node_id`). Downstream scheduling
1127
+ * keys the pool by raw-string equality (Set dedup, baseIndex, rankIndex,
1128
+ * nodeActiveLoad), so two candidates for the SAME physical node under two
1129
+ * different forms would otherwise be treated as two distinct nodes — form-drift
1130
+ * that splits a node's load and double-ranks it. Canonicalizing here (via the
1131
+ * resolved node record, which meshNodeIdMatches already matched form-agnostically)
1132
+ * makes every later `=== nodeId` comparison operate on one agreed form. Falls back
1133
+ * to the raw candidate id when the node is unresolved (an unresolved candidate
1134
+ * cannot be normalized, but also has no sibling to collide with).
1135
+ */
1136
+ function buildSchedulingPool(
1137
+ localCandidates: IdleCandidate[],
1138
+ remoteCandidates: IdleCandidate[],
1139
+ ): { pool: IdleCandidate[]; uniqueNodes: RankableNode[] } {
1140
+ const pool = [...localCandidates, ...remoteCandidates].map(c => ({
1141
+ ...c,
1142
+ nodeId: normalizeMeshNodeId(c.node) ?? c.nodeId,
1143
+ }));
1144
+ // Both sides are canonical now, so raw `===` in the Set dedup and the node
1145
+ // re-lookup is form-safe.
1146
+ const uniqueNodes: RankableNode[] = [...new Set(pool.map(c => c.nodeId))]
1147
+ .map((nodeId, index) => ({
1148
+ nodeId,
1149
+ node: pool.find(c => meshNodeIdMatches({ id: c.nodeId } as MeshNodeIdentified, nodeId))?.node,
1150
+ index,
1151
+ }));
1152
+ return { pool, uniqueNodes };
1153
+ }
1154
+
1155
+ /** Test-only: the pool-canonicalization + unique-node collapse stage. Exposed so
1156
+ * the mixed-form dedup invariant can be unit-tested without a live daemon. */
1157
+ export function __buildSchedulingPoolForTests(
1158
+ localCandidates: IdleCandidate[],
1159
+ remoteCandidates: IdleCandidate[],
1160
+ ): { pool: IdleCandidate[]; uniqueNodes: RankableNode[] } {
1161
+ return buildSchedulingPool(localCandidates, remoteCandidates);
1162
+ }
1163
+
1164
+ function orderEligibleNodes(
1165
+ meshId: string,
1166
+ strategy: RepoMeshSchedulingStrategy,
1167
+ nodes: RankableNode[],
1168
+ opts?: { bumpCursor?: boolean },
1169
+ ): RankableNode[] {
1170
+ if (strategy === 'first_eligible' || nodes.length <= 1) {
1171
+ return nodes;
1172
+ }
1173
+
1174
+ const priorityOf = (n: { node: any }) => resolveNodeSchedulingPriority(n.node?.policy);
1175
+
1176
+ // Round-robin rotation offset: rotate the deterministic input order by a
1177
+ // per-mesh cursor so the tie-break winner among equal (priority, load) nodes
1178
+ // cycles across passes. The cursor advances once per scheduling pass. Applied
1179
+ // to both 'least_loaded' (the 'spread' mode — rotation absorbed as its
1180
+ // tie-break) and the legacy 'round_robin' alias.
1181
+ let rotation = 0;
1182
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
1183
+ const cursor = opts?.bumpCursor
1184
+ ? MeshRuntimeStore.getInstance().bumpSchedulerCursor(meshId)
1185
+ : MeshRuntimeStore.getInstance().getSchedulerCursor(meshId);
1186
+ rotation = ((cursor % nodes.length) + nodes.length) % nodes.length;
1187
+ }
1188
+
1189
+ // Rotation rank: position of each node after rotating input order by `rotation`.
1190
+ // For non-round-robin strategies rotation is 0, so this is just the input index.
1191
+ const rotationRank = (index: number) => (index - rotation + nodes.length) % nodes.length;
1192
+
1193
+ return [...nodes].sort((a, b) => {
1194
+ const prioDelta = priorityOf(b) - priorityOf(a); // higher priority first
1195
+ if (prioDelta !== 0) return prioDelta;
1196
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
1197
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
1198
+ if (loadDelta !== 0) return loadDelta;
1199
+ }
1200
+ return rotationRank(a.index) - rotationRank(b.index);
1201
+ });
1202
+ }
1203
+
1204
+ /** Active assignments on a (node, provider) — pre-launch guard for the per-(node,
1205
+ * provider) maxParallel cap. The authoritative enforcement is in the claim
1206
+ * transaction; this only avoids spawning a session that would fail the claim. */
1207
+ function activeProviderAssignedCount(meshId: string, nodeId: string, providerType: string): number {
1208
+ return getQueue(meshId, { status: ['assigned'] as any })
1209
+ .filter(task => daemonIdsEquivalent(task.assignedNodeId, nodeId) && task.assignedProviderType === providerType).length;
1210
+ }
1211
+
1212
+ export function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
1213
+ if (getQueue(meshId, { status: ['assigned'] as any }).some(task => sessionIdsEquivalent(task.assignedSessionId, sessionId))) {
1214
+ return true;
1215
+ }
1216
+ // Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
1217
+ // work queue. A session completing a still-active direct dispatch IS an active
1218
+ // assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
1219
+ // the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
1220
+ // so the coordinator polling get_pending_mesh_events never observes task_completed and the
1221
+ // session goes silently idle. This check runs before markSessionTerminal marks the
1222
+ // dispatch terminal, so the in-flight dispatch is still observable here.
1223
+ try {
1224
+ if (getActiveDirectDispatches(meshId).some(d => sessionIdsEquivalent(d.sessionId, sessionId))) return true;
1225
+ if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
1226
+ } catch { /* best-effort — fall through to false */ }
1227
+ return false;
1228
+ }
1229
+
1230
+ /**
1231
+ * CANON-IDENTITY single-flight hardening (restart-safe, observation-based).
1232
+ *
1233
+ * The in-memory single-flight Set (mesh-task-inflight) is process-local and is LOST on a
1234
+ * daemon restart — after a restart, a task still being generated by a live local worker is
1235
+ * no longer marked in-flight, so requeueTask's Set check passes and would re-open the task
1236
+ * for a duplicate second dispatch. This recovers the "still generating" signal from
1237
+ * observable runtime state instead of the in-memory mark: a session is actively generating
1238
+ * when its live local CLI instance reports an active (generating/streaming/…) status — the
1239
+ * same predicate the dispatch active-work gate uses (sessionStateLooksActive).
1240
+ *
1241
+ * Local-only by design: it inspects THIS daemon's instanceManager. The primary cross-process
1242
+ * fix (IpcTransport requeue delegating to the mesh-host daemon) keeps begin (dispatch) and
1243
+ * check (requeue guard) co-located so the in-memory mark stays authoritative in the common
1244
+ * path; this is the restart-safety net for sessions hosted on this daemon. A genuinely
1245
+ * dead/stale session is not generating → returns false → the requeue proceeds as before.
1246
+ */
1247
+ export function isSessionActivelyGenerating(components: DaemonComponents, sessionId: string): boolean {
1248
+ if (!sessionId) return false;
1249
+ const state = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
1250
+ if (!state) return false;
1251
+ return sessionStateLooksActive(state);
1252
+ }
1253
+
1254
+ /**
1255
+ * RECLAIM-FALSEPOS tri-state busy verdict for a session id.
1256
+ *
1257
+ * The binary isSessionActivelyGenerating() folds "absence of a positive generating
1258
+ * signal" into a definitive NEGATIVE (returns false when the instance is absent). But a
1259
+ * REMOTE session (never in THIS daemon's instanceManager) — or a locally-present session
1260
+ * looked up under a skewed id form — then looks "not generating" and can be reclaimed out
1261
+ * from under a worker that is genuinely mid-turn. This resolves an explicit three-way
1262
+ * verdict instead:
1263
+ * - GENERATING — a locally-present instance reports an active/streaming state.
1264
+ * - IDLE_CONFIRMED — a locally-present instance reports a non-active (idle/terminal)
1265
+ * state. Positive local evidence the worker is not working.
1266
+ * - UNKNOWN — no locally-present instance matches (remote / gone / id-skew) or
1267
+ * the observation failed. NEVER treated as IDLE_CONFIRMED.
1268
+ *
1269
+ * The lookup scans getByCategory('cli') with sessionIdsEquivalent (the same equivalence
1270
+ * matching nodeHasActiveMeshWork / liveSessionCountForNode use) rather than a raw
1271
+ * instanceManager.getInstance(id) Map.get, so an id-form-skewed but present session is
1272
+ * found (closing the same id-form-skew hole class e245c2f9's F1 fixed elsewhere).
1273
+ */
1274
+ export type SessionBusyVerdict = 'GENERATING' | 'IDLE_CONFIRMED' | 'UNKNOWN';
1275
+ export function resolveSessionBusyVerdict(components: DaemonComponents, sessionId: string): SessionBusyVerdict {
1276
+ if (!sessionId) return 'UNKNOWN';
1277
+ try {
1278
+ const instances = components.instanceManager?.getByCategory?.('cli') || [];
1279
+ const inst = instances.find((i: any) => {
1280
+ const sid = readNonEmptyString(i?.getState?.().instanceId);
1281
+ return sid && sessionIdsEquivalent(sid, sessionId);
1282
+ });
1283
+ if (!inst) return 'UNKNOWN'; // remote / gone / id-form skew not present locally
1284
+ const state = inst.getState?.();
1285
+ if (!state) return 'UNKNOWN';
1286
+ return sessionStateLooksActive(state) ? 'GENERATING' : 'IDLE_CONFIRMED';
1287
+ } catch {
1288
+ return 'UNKNOWN'; // failed observation ⇒ unknown, never a definitive idle
1289
+ }
1290
+ }
1291
+
1292
+ function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
1293
+ const localInstances = components.instanceManager.getByCategory('cli').filter((inst: any) => {
1294
+ const state = inst.getState();
1295
+ const settings = state.settings as Record<string, unknown> || {};
1296
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
1297
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1298
+ // Canonical-form match (see nodeHasActiveMeshWork): a daemon-id form skew between
1299
+ // the session's stamped nodeId and the candidate nodeId must not undercount this
1300
+ // node's live sessions, which would defeat the maxConcurrentSessions cap.
1301
+ if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
1302
+ const status = readNonEmptyString(state.status).toLowerCase();
1303
+ return !isTerminalSessionStatus(status);
1304
+ });
1305
+ let count = localInstances.length;
1306
+ // (A) AUTOLAUNCH-CLAIM-CHURN: also count launched-but-not-yet-claimed sessions targeting this
1307
+ // node whose await-claim window is still open. A REMOTE such session is invisible to the local
1308
+ // instanceManager above, so without this the maxConcurrentSessions cap undercounts it and a
1309
+ // duplicate ghost launch slips through. Exclude any id already represented by a local instance
1310
+ // so a co-located launch is not double-counted.
1311
+ const localSessionIds = localInstances
1312
+ .map((inst: any) => readNonEmptyString(inst.getState().instanceId))
1313
+ .filter(Boolean);
1314
+ for (const sid of inWindowAutoLaunchSessionIdsForNode(meshId, nodeId)) {
1315
+ if (!localSessionIds.some(local => sessionIdsEquivalent(local, sid))) count += 1;
1316
+ }
1317
+ return count;
1318
+ }
1319
+
1320
+ /**
1321
+ * DOUBLE-DISPATCH auto-launch gate: does this node already have a LIVE mesh session that
1322
+ * is NOT holding an assigned queue task — i.e. one that is idle, booting toward its first
1323
+ * claim, or in a momentary non-idle flip? Such a session WILL claim a still-pending task
1324
+ * on its own via the idle→claim / agent:ready drain, so spawning a NEW session here only
1325
+ * races it and yields a duplicate worker that double-stamps the same taskId (the
1326
+ * enqueue → drain-miss → auto-launch RCA: the drain skipped a momentarily-non-idle idle
1327
+ * session as a candidate, and the write-only nodeHasActiveAssignment gate — which only
1328
+ * inspects status='assigned' rows — could not see the about-to-claim session either).
1329
+ *
1330
+ * A session that already HOLDS an assigned queue task is genuine concurrent work, not a
1331
+ * free claimer, and is excluded — so a read-only auto-launch onto a busy-but-no-idle node
1332
+ * is still allowed. A node with NO live mesh session at all (dead, or never launched) does
1333
+ * not match, preserving the legitimate first-session spawn.
1334
+ */
1335
+ function nodeHasLiveSessionPendingClaim(components: DaemonComponents, meshId: string, nodeId: string): boolean {
1336
+ // (A) AUTOLAUNCH-CLAIM-CHURN remote-awareness: a task whose auto-launch record targets this
1337
+ // node and is still inside its await-claim window (base or backoff) already has a session on
1338
+ // its way to claim — even when that session is REMOTE and thus invisible to the local
1339
+ // instanceManager scan below. Treat it as a live pending-claim session so a duplicate launch
1340
+ // is suppressed and no ghost accumulates every ~90s.
1341
+ if (inWindowAutoLaunchSessionIdsForNode(meshId, nodeId).length > 0) return true;
1342
+ // Session ids currently holding an assigned queue task on this node — those are busy,
1343
+ // not pending claimers, so they must NOT suppress a (read-only) launch.
1344
+ const busySessionIds = new Set(
1345
+ getQueue(meshId, { status: ['assigned'] as any })
1346
+ .filter(task => daemonIdsEquivalent(task.assignedNodeId, nodeId))
1347
+ .map(task => readNonEmptyString(task.assignedSessionId))
1348
+ .filter(Boolean),
1349
+ );
1350
+ return components.instanceManager.getByCategory('cli').some((inst: any) => {
1351
+ const state = inst.getState();
1352
+ const settings = state.settings as Record<string, unknown> || {};
1353
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
1354
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1355
+ // Canonical-form match (see nodeHasActiveMeshWork / liveSessionCountForNode): a
1356
+ // daemon-id form skew must not make a present session look absent and reopen the
1357
+ // duplicate-launch hole.
1358
+ if (!daemonIdsEquivalent(instNodeId, nodeId)) return false;
1359
+ const status = readNonEmptyString(state.status).toLowerCase();
1360
+ if (isTerminalSessionStatus(status)) return false; // dead → no claimer here, allow launch
1361
+ const sessionId = readNonEmptyString(state.instanceId);
1362
+ if (sessionId && busySessionIds.has(sessionId)) return false; // busy with its own assigned task
1363
+ return true; // live + unassigned → will claim the pending task itself
1364
+ });
1365
+ }
1366
+
1367
+ function recordAutoLaunchEvent(meshId: string, args: {
1368
+ phase: 'skipped' | 'started' | 'failed' | 'completed';
1369
+ taskId: string;
1370
+ nodeId?: string;
1371
+ providerType?: string;
1372
+ sessionId?: string;
1373
+ reason?: string;
1374
+ error?: string;
1375
+ }) {
1376
+ // Suppress consecutive identical `skipped` entries for the same task (4s reconcile
1377
+ // re-trigger noise). Non-skip phases and changed reasons always record and reset
1378
+ // the de-dup so genuine state transitions remain visible in the ledger.
1379
+ const dedupKey = `${meshId}:${args.taskId}`;
1380
+ const currentSig = `${args.phase}|${args.reason || ''}`;
1381
+ if (args.phase === 'skipped' && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
1382
+ return;
1383
+ }
1384
+ lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
1385
+ if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
1386
+ // Bound memory: drop the oldest insertion (Map preserves insertion order).
1387
+ const oldest = lastAutoLaunchLedgerKey.keys().next().value;
1388
+ if (oldest !== undefined) lastAutoLaunchLedgerKey.delete(oldest);
1389
+ }
1390
+ try {
1391
+ appendLedgerEntry(meshId, {
1392
+ kind: 'session_auto_launch',
1393
+ nodeId: args.nodeId,
1394
+ sessionId: args.sessionId,
1395
+ providerType: args.providerType,
1396
+ payload: {
1397
+ phase: args.phase,
1398
+ taskId: args.taskId,
1399
+ reason: args.reason,
1400
+ error: args.error,
1401
+ },
1402
+ });
1403
+ } catch (e: any) {
1404
+ LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
1405
+ }
1406
+ }
1407
+
1408
+ function markAutoLaunch(meshId: string, taskId: string, args: {
1409
+ status: 'skipped' | 'started' | 'failed' | 'completed';
1410
+ reason?: string;
1411
+ nodeId?: string;
1412
+ providerType?: string;
1413
+ sessionId?: string;
1414
+ error?: string;
1415
+ }) {
1416
+ recordTaskAutoLaunch(meshId, taskId, {
1417
+ status: args.status,
1418
+ reason: args.reason || args.error,
1419
+ nodeId: args.nodeId,
1420
+ providerType: args.providerType,
1421
+ sessionId: args.sessionId,
1422
+ });
1423
+ recordAutoLaunchEvent(meshId, {
1424
+ phase: args.status,
1425
+ taskId,
1426
+ nodeId: args.nodeId,
1427
+ providerType: args.providerType,
1428
+ sessionId: args.sessionId,
1429
+ reason: args.reason,
1430
+ error: args.error,
1431
+ });
1432
+ // Fix (1): actively notify the coordinator of a non-self-resolving skip; re-arm the
1433
+ // notification on any non-skip transition (started/completed) so a later genuine skip
1434
+ // re-notifies.
1435
+ if (args.status === 'skipped') {
1436
+ if (isActionableSkipReason(args.reason)) {
1437
+ notifyCoordinatorOfActionableSkip(meshId, taskId, args.reason, args.nodeId);
1438
+ } else if (args.reason === TRANSIENT_TARGET_NODE_BOOTSTRAP_PENDING_REASON) {
1439
+ // FALSE-BLOCKER-CLONE-QUEUE (stale-event clear): the unmatch is now known to be a
1440
+ // self-resolving clone/bootstrap window — retract any earlier actionable blocker we
1441
+ // paged for this same task. Other transient/back-pressure reasons (cooldown, caps)
1442
+ // intentionally do NOT retract: they can mask a still-standing real blocker.
1443
+ retractActionableSkipIfPreviouslyNotified(meshId, taskId);
1444
+ }
1445
+ } else {
1446
+ // started/completed: the task is progressing — re-arm the de-dup ledger and retract
1447
+ // any still-undelivered stale blocker for it.
1448
+ retractActionableSkipIfPreviouslyNotified(meshId, taskId);
1449
+ }
1450
+ }
1451
+
1452
+ async function resolveUsableProvider(
1453
+ components: DaemonComponents,
1454
+ nodeId: string,
1455
+ node: any,
1456
+ requiredTags?: string[],
1457
+ ): Promise<{ providerType?: string; reason?: string }> {
1458
+ const providerPriority = normalizeProviderPriority(node?.policy);
1459
+ if (!providerPriority.length) return { reason: 'missing_provider_priority' };
1460
+ const providerLoader = components.providerLoader;
1461
+ if (!providerLoader) return { reason: 'provider_loader_unavailable' };
1462
+
1463
+ const failed: string[] = [];
1464
+ for (const requestedType of providerPriority) {
1465
+ const normalizedType = typeof providerLoader.resolveAlias === 'function'
1466
+ ? providerLoader.resolveAlias(requestedType)
1467
+ : requestedType;
1468
+ // Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
1469
+ // means only hermes-cli qualifies, not any other type in providerPriority).
1470
+ if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
1471
+ failed.push(`${requestedType}: required_tags_mismatch`);
1472
+ continue;
1473
+ }
1474
+ if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
1475
+ failed.push(`${requestedType}: disabled`);
1476
+ continue;
1477
+ }
1478
+ let detected: any;
1479
+ try {
1480
+ detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
1481
+ } catch (e: any) {
1482
+ failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
1483
+ continue;
1484
+ }
1485
+ if (typeof providerLoader.setCliDetectionResults === 'function') {
1486
+ providerLoader.setCliDetectionResults([{
1487
+ id: normalizedType,
1488
+ installed: !!detected,
1489
+ path: detected?.path,
1490
+ }], false);
1491
+ }
1492
+ (components as any).onStatusChange?.();
1493
+ if (detected) return { providerType: normalizedType };
1494
+ failed.push(`${requestedType}: not detected`);
1495
+ }
1496
+ return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
1497
+ }
1498
+
1499
+ // Canonical mesh node-id normalization. A node may arrive from the local config
1500
+ // form (`id`) or the inline-cache form (`nodeId`/`node_id`) — see
1501
+ // readInlineMeshNodeId in commands/router.ts. Comparing only `node.id` against a
1502
+ // task.targetNodeId silently drops inline-cached worktree nodes, leaving a
1503
+ // target-routed task permanently pending with a misleading
1504
+ // `no_node_satisfies_required_tags` skip.
1505
+ function readMeshNodeId(node: any): string {
1506
+ // Delegate to the shared 3-way (id / nodeId / node_id) normalizer so this
1507
+ // and every other mesh node-id read agree on identity. Coalesce to '' to
1508
+ // preserve the existing string return contract for callers that do
1509
+ // `=== task.targetNodeId` / `if (!nodeId)`.
1510
+ return normalizeMeshNodeId(node) ?? '';
1511
+ }
1512
+
1513
+ // AUTOLAUNCH-CLAIM-CHURN. The await-claim window for a launched (remote) session has expired
1514
+ // without a claim. Instead of a blind respawn, re-drive the claim for the EXISTING session,
1515
+ // backing off when its liveness is unknown, and only respawning when it is provably unclaimable.
1516
+ // Returns a directive for the caller:
1517
+ // - 'claimed' — the re-drive claimed/dispatched the task into the existing session (progress).
1518
+ // - 'fallback' — the post-cap direct dispatch delivered the task into the existing session.
1519
+ // - 'backoff' — liveness unknown; the window was extended (or is still cooling down). No launch.
1520
+ // - 'respawn' — the session is provably gone/unclaimable; the caller may launch a fresh one.
1521
+ function driveExpiredAwaitClaim(
1522
+ components: DaemonComponents,
1523
+ meshId: string,
1524
+ task: MeshWorkQueueEntry,
1525
+ ctx: { sessionId: string; nodeId: string; providerType: string },
1526
+ ): 'claimed' | 'fallback' | 'backoff' | 'respawn' {
1527
+ const { sessionId, nodeId, providerType } = ctx;
1528
+ const backoffKey = `${meshId}::${task.id}`;
1529
+ const nowMs = Date.now();
1530
+ const state = autoLaunchAwaitClaimBackoff.get(backoffKey) || { cycles: 0, nextAttemptAtMs: 0 };
1531
+ // Rate-limit re-drive attempts to the backoff cadence so the 4s reconcile tick does not hammer
1532
+ // a still-cooling-down window. The initial (no-state) expiry proceeds immediately.
1533
+ if (state.nextAttemptAtMs && nowMs < state.nextAttemptAtMs) return 'backoff';
1534
+
1535
+ const atCap = state.cycles >= AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES;
1536
+ const live = remoteSessionAppearsLive(meshId, sessionId);
1537
+
1538
+ // (B) Re-drive when the remote view shows the session live; (C) after the backoff cap, force the
1539
+ // same direct dispatch unconditionally. Both funnel through tryAssignQueueTask, which
1540
+ // idempotently (re)registers the session, delivers the task message (send_chat), and marks the
1541
+ // row assigned — the exact operation a coordinator performs manually via mesh_send_task. (D)
1542
+ // The setRemoteIdleSession re-register makes this robust to a dropped agent:ready.
1543
+ if ((live || atCap) && nodeId && providerType) {
1544
+ try {
1545
+ MeshRuntimeStore.getInstance().setRemoteIdleSession(meshId, nodeId, sessionId, providerType, nowMs + AUTO_LAUNCH_REMOTE_IDLE_TTL_MS);
1546
+ } catch { /* best-effort re-register */ }
1547
+ const assigned = tryAssignQueueTask(components, meshId, nodeId, sessionId, providerType);
1548
+ if (assigned) {
1549
+ autoLaunchAwaitClaimBackoff.delete(backoffKey);
1550
+ const isFallback = atCap && !live;
1551
+ recordAutoLaunchEvent(meshId, {
1552
+ phase: 'completed',
1553
+ taskId: task.id,
1554
+ reason: isFallback ? 'await_claim_direct_dispatch_fallback' : 'await_claim_redriven',
1555
+ nodeId,
1556
+ sessionId,
1557
+ });
1558
+ // Content-free progress line (ids only).
1559
+ LOG.info('MeshQueue', `Auto-launch await-claim ${isFallback ? 'direct-dispatch fallback' : 're-drive'} claimed task ${task.id} into existing session ${sessionId} on node ${nodeId} (mesh ${meshId})`);
1560
+ return isFallback ? 'fallback' : 'claimed';
1561
+ }
1562
+ if (atCap) {
1563
+ // The forced dispatch could not claim — the session is genuinely gone/unclaimable.
1564
+ // Authorize a fresh respawn (ghosts were already prevented through the backoff window).
1565
+ autoLaunchAwaitClaimBackoff.delete(backoffKey);
1566
+ return 'respawn';
1567
+ }
1568
+ }
1569
+ // Liveness unknown (or live-but-not-claimable) and not at cap → extend the window with backoff.
1570
+ const cycles = Math.min(state.cycles + 1, AUTO_LAUNCH_AWAIT_CLAIM_BACKOFF_CAP_CYCLES);
1571
+ autoLaunchAwaitClaimBackoff.set(backoffKey, { cycles, nextAttemptAtMs: nowMs + awaitClaimWindowMs(cycles) });
1572
+ recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim_backoff', nodeId, sessionId });
1573
+ return 'backoff';
1574
+ }
1575
+
1576
+ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
1577
+ const queue = getQueue(meshId);
1578
+ // DEPENDSON-GATE-SYMMETRY: status index over the FULL queue (incl. completed)
1579
+ // so the dependency gate below sees the terminal state of every referenced
1580
+ // dependency, not just the still-active rows.
1581
+ const statusById = new Map(queue.map(task => [task.id, task.status] as const));
1582
+ // G6: scan higher task-level priority first so a high-priority task auto-launches its
1583
+ // session ahead of an older normal/low task (getQueue is FIFO; a stable sort by priority
1584
+ // rank descending keeps created_at order within a priority band). The claim path applies
1585
+ // the same ordering, so the launched session pulls the same task the scan chose.
1586
+ const pending = queue
1587
+ .filter(task => task.status === 'pending')
1588
+ .sort((a, b) => meshTaskPriorityRank(b.priority) - meshTaskPriorityRank(a.priority));
1589
+ // AUTOLAUNCH-CLAIM-CHURN: prune await-claim backoff state for tasks of this mesh that are no
1590
+ // longer pending (claimed/completed/cancelled) so the map cannot grow without bound.
1591
+ {
1592
+ const pendingIds = new Set(pending.map(t => t.id));
1593
+ const prefix = `${meshId}::`;
1594
+ for (const key of [...autoLaunchAwaitClaimBackoff.keys()]) {
1595
+ if (key.startsWith(prefix) && !pendingIds.has(key.slice(prefix.length))) autoLaunchAwaitClaimBackoff.delete(key);
1596
+ }
1597
+ }
1598
+ if (!pending.length) return false;
1599
+
1600
+ // Write cap + read-only cap resolved through the shared helpers from the
1601
+ // MACHINE-LOCAL stored mesh policy (no repo-file overlay). These are the same
1602
+ // resolvers the observability projection uses, so the enforced and exposed
1603
+ // caps can never drift.
1604
+ const maxParallelTasks = resolveMaxParallelTasks(mesh?.policy?.maxParallelTasks);
1605
+ // Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
1606
+ // write-task parallel cap. To prevent runaway auto-launch they get their own,
1607
+ // higher safety cap (default 2× the write cap).
1608
+ const maxReadonlyParallelTasks = resolveMaxReadonlyParallelTasks(maxParallelTasks);
1609
+ for (const task of pending) {
1610
+ // DEPENDSON-GATE-SYMMETRY: never spawn a session for a task whose
1611
+ // dependsOn set is not all-completed (or that carries a system block). The
1612
+ // launched session would idle→claim and be refused by the SAME predicate in
1613
+ // claimNextQueueTask, producing orphan-session / re-launch churn. Skip it so
1614
+ // a later tick — after the dependency completes — launches it. Tasks with no
1615
+ // dependsOn pass through unchanged (predicate is true).
1616
+ if (!taskDependenciesSatisfied(task, statusById)) {
1617
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dependencies_unsatisfied' });
1618
+ continue;
1619
+ }
1620
+ // G7: never spawn a session for a task still held by its notBefore gate — the launched
1621
+ // session would idle→claim and be refused by the SAME gate in claimNextQueueTask,
1622
+ // producing orphan-session churn. Skip it so a later tick (after not_before passes)
1623
+ // launches it. Tasks with no notBefore pass through unchanged.
1624
+ if (!meshTaskNotBeforeReady(task)) {
1625
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'not_before_delayed' });
1626
+ continue;
1627
+ }
1628
+ const isReadonly = isTaskReadonly(task);
1629
+ if (isReadonly) {
1630
+ if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
1631
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
1632
+ continue;
1633
+ }
1634
+ } else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
1635
+ // Write tasks are capped; skip this one but keep scanning so a later
1636
+ // read-only task in the queue can still launch under its own cap.
1637
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
1638
+ continue;
1639
+ }
1640
+ if (task.targetSessionId) {
1641
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
1642
+ continue;
1643
+ }
1644
+
1645
+ // Per-task await-claim guard. A prior auto-launch already spawned a session for
1646
+ // this task and we are waiting for that session's idle→claim to land (remote
1647
+ // claims arrive via the worker→coordinator agent:ready pull, which can lag well
1648
+ // past the per-node cooldown). Re-launching now would spawn a duplicate orphan
1649
+ // session that never gets work. The task leaves `pending` the instant the claim
1650
+ // succeeds, so this guard only suppresses the in-flight window; if the launched
1651
+ // session never reaches idle within the window, a later tick retries.
1652
+ if (task.autoLaunch?.status === 'completed' && task.autoLaunch.sessionId) {
1653
+ const launchedAtMs = Date.parse(task.autoLaunch.updatedAt);
1654
+ const alSessionId = readNonEmptyString(task.autoLaunch.sessionId);
1655
+ const alNodeId = readNonEmptyString(task.autoLaunch.nodeId);
1656
+ const alProvider = readNonEmptyString(task.autoLaunch.providerType);
1657
+ if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
1658
+ // Record the skip in the ledger ONLY (dedup'd). Do NOT call markAutoLaunch
1659
+ // here: recordTaskAutoLaunch overwrites task.autoLaunch wholesale, which would
1660
+ // erase the very `completed` record (status + sessionId + updatedAt) this guard
1661
+ // reads on the next tick, reopening the duplicate-launch hole it closes.
1662
+ recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim', nodeId: alNodeId, sessionId: alSessionId });
1663
+ continue;
1664
+ }
1665
+ // AUTOLAUNCH-CLAIM-CHURN: the initial await-claim window expired. Rather than a blind
1666
+ // respawn (which the local-only respawn guards can't dedup for a remote pending-claim
1667
+ // session → ghost accumulation), re-drive the claim for the EXISTING launched session,
1668
+ // backing off on unknown liveness and direct-dispatching after the cap. Only a
1669
+ // 'respawn' directive falls through to a fresh launch below.
1670
+ if (Number.isFinite(launchedAtMs) && alSessionId && alNodeId) {
1671
+ const outcome = driveExpiredAwaitClaim(components, meshId, task, { sessionId: alSessionId, nodeId: alNodeId, providerType: alProvider });
1672
+ if (outcome === 'claimed' || outcome === 'fallback') return true; // progress; suppress a duplicate launch
1673
+ if (outcome === 'backoff') continue; // window extended; no respawn
1674
+ // outcome === 'respawn' → session provably gone; proceed to a fresh launch below.
1675
+ }
1676
+ }
1677
+
1678
+ const candidateNodes = Array.isArray(mesh?.nodes)
1679
+ ? mesh.nodes.filter((node: any) => {
1680
+ // Bug A: match the target pin with the shared 3-form (id / nodeId / node_id)
1681
+ // normalizer, mirroring the remote-idle drain (meshNodeIdMatches at the
1682
+ // getRemoteIdleSessions filter). A strict `readMeshNodeId(node) !== targetNodeId`
1683
+ // dropped a target node whose identity arrived under a different form (a freshly
1684
+ // mesh_clone_node'd worktree), emptying candidateNodes and mislabelling the skip.
1685
+ if (task.targetNodeId && !meshNodeIdMatches(node, task.targetNodeId)) return false;
1686
+ // WTDISPATCH-FANOUT: a convergence task is base-only (it merges/pushes onto
1687
+ // base). Never auto-launch a worktree-clone session for it — that is the very
1688
+ // fan-out the claim guard refuses, so spinning the session up would only waste
1689
+ // a launch that can never claim. Mirrors claimNextQueueTask's convergence gate.
1690
+ if (task.taskMode === 'convergence' && node?.isLocalWorktree === true) return false;
1691
+ // Skip nodes that can never satisfy requiredTags regardless of which provider
1692
+ // from providerPriority is selected. A node satisfies tags if at least one
1693
+ // provider in its priority list would produce matching capability tags.
1694
+ if (task.requiredTags?.length) {
1695
+ const priorities = normalizeProviderPriority(node?.policy);
1696
+ const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
1697
+ return providerCandidates.some(p =>
1698
+ nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
1699
+ );
1700
+ }
1701
+ return true;
1702
+ })
1703
+ : [];
1704
+ if (!candidateNodes.length) {
1705
+ // Bug A: distinguish the two ways the candidate set empties. A task pinned to a
1706
+ // targetNodeId whose node is absent from the mesh (or whose id arrived under a
1707
+ // different form) is a ROUTING miss — report it as `target_node_id_unmatched`, not
1708
+ // the hard-coded `no_node_satisfies_required_tags`, which mislabelled a 3-form
1709
+ // node-id mismatch as a capability failure and sent diagnosis down the wrong path.
1710
+ // Only fall back to the tag reason when no target pin is in play, or the pin DID
1711
+ // match a node but its tags excluded it (a genuine capability miss).
1712
+ const targetPinUnmatched = !!task.targetNodeId
1713
+ && !(Array.isArray(mesh?.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, task.targetNodeId)));
1714
+ // Fix (2): a `convergence` task is base-only — the candidate filter above
1715
+ // (`taskMode === 'convergence' && node.isLocalWorktree`) deliberately drops every
1716
+ // worktree-clone node, so candidateNodes can empty out NOT because the target is
1717
+ // missing or tag-incapable, but because every node the task could land on is a
1718
+ // worktree. Reporting that as `target_node_id_unmatched` / `no_node_satisfies_
1719
+ // required_tags` mislabels the cause and sends diagnosis down the wrong path.
1720
+ // Detect it explicitly and report the same reason mesh_send_task uses for a direct
1721
+ // convergence dispatch onto a worktree, so both surfaces agree.
1722
+ const convergenceOntoWorktree = task.taskMode === 'convergence'
1723
+ && Array.isArray(mesh?.nodes)
1724
+ && (() => {
1725
+ const matched = (mesh.nodes as any[]).filter((n: any) =>
1726
+ !task.targetNodeId || meshNodeIdMatches(n, task.targetNodeId));
1727
+ return matched.length > 0 && matched.every((n: any) => n?.isLocalWorktree === true);
1728
+ })();
1729
+ // FALSE-BLOCKER-CLONE-QUEUE: an unmatched target pin is only a PERMANENT routing
1730
+ // miss when the node is genuinely absent — a freshly cloned worktree whose
1731
+ // inline-cache entry has not propagated here yet (or whose bootstrap is still
1732
+ // running) is TRANSIENTLY unresolved and auto-claims shortly. Report that as the
1733
+ // transient (non-actionable) reason so the coordinator is not paged with a false
1734
+ // "actionable blocker — will NOT clear on its own". A genuinely dead node is neither
1735
+ // bootstrap-running nor inside the clone grace window → stays 'target_node_id_unmatched'.
1736
+ const targetTransientlyUnresolved = targetPinUnmatched
1737
+ && isTargetNodeTransientlyUnresolved(mesh, task);
1738
+ markAutoLaunch(meshId, task.id, {
1739
+ status: 'skipped',
1740
+ reason: convergenceOntoWorktree
1741
+ ? 'mesh_convergence_target_is_worktree'
1742
+ : targetTransientlyUnresolved
1743
+ ? TRANSIENT_TARGET_NODE_BOOTSTRAP_PENDING_REASON
1744
+ : (targetPinUnmatched ? 'target_node_id_unmatched' : 'no_node_satisfies_required_tags'),
1745
+ nodeId: task.targetNodeId,
1746
+ });
1747
+ continue;
1748
+ }
1749
+
1750
+ // PRIORITY → TIE-BREAK: order the eligible (TAG-filtered) candidate nodes by
1751
+ // the mesh scheduling strategy. 'first_eligible' (default) returns them in
1752
+ // config/array order unchanged, so distribution is strictly opt-in. The
1753
+ // per-node MAX-ALLOC capacity gate (nodeHasActiveAssignment, provider cap,
1754
+ // maxConcurrentSessions) is still applied inside the loop below; this only
1755
+ // chooses which eligible node is *tried first*.
1756
+ const strategy = resolveSchedulingStrategy(mesh);
1757
+ const orderedCandidateNodes = strategy === 'first_eligible'
1758
+ ? candidateNodes
1759
+ : orderEligibleNodes(
1760
+ meshId,
1761
+ strategy,
1762
+ candidateNodes
1763
+ .map((node: any, index: number) => ({ nodeId: readMeshNodeId(node), node, index }))
1764
+ .filter((c: RankableNode) => c.nodeId),
1765
+ { bumpCursor: true },
1766
+ ).map((c: RankableNode) => c.node);
1767
+
1768
+ for (const node of orderedCandidateNodes) {
1769
+ const nodeId = readMeshNodeId(node);
1770
+ if (!nodeId) continue;
1771
+ const launchKey = `${meshId}:${nodeId}`;
1772
+ const now = Date.now();
1773
+ const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
1774
+ if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
1775
+ if (autoLaunchInProgress.has(launchKey)) {
1776
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
1777
+ continue;
1778
+ }
1779
+ if (now < cooldownUntil) {
1780
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
1781
+ continue;
1782
+ }
1783
+ if (isDirtyNode(node)) {
1784
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
1785
+ continue;
1786
+ }
1787
+ if (!isLaunchableNode(node)) {
1788
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
1789
+ continue;
1790
+ }
1791
+ const launchTarget = resolveAutoLaunchTarget(components, node);
1792
+ if (launchTarget.mode === 'skip') {
1793
+ // Remote node we can't reach (no transport / no coordinator daemonId).
1794
+ // Set a cooldown so the 4s reconcile loop doesn't re-attempt this node
1795
+ // every tick; the de-dup'd skip ledger keeps it diagnosable without flood.
1796
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: launchTarget.reason || 'auto_launch_unavailable', nodeId });
1797
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1798
+ continue;
1799
+ }
1800
+ // DOUBLE-DISPATCH auto-launch gate (see nodeHasLiveSessionPendingClaim): when this
1801
+ // node already has a live session on its way to claim (idle / booting / momentary
1802
+ // non-idle flip), do NOT spawn a second one — that session pulls the pending task
1803
+ // via the normal idle→claim / agent:ready drain. Launching here races it and yields
1804
+ // a duplicate worker that double-stamps the same taskId. Applies to read-only tasks
1805
+ // too: an idle session can claim either kind, while a genuinely BUSY session (holding
1806
+ // its own assigned task) is excluded by the helper, so a read-only launch onto a
1807
+ // busy-but-no-idle node is still allowed. Skip with a transient (non-actionable)
1808
+ // reason so the coordinator is not paged; the 4s reconcile retries, and once the
1809
+ // existing session goes terminal this gate clears and a legitimate launch proceeds.
1810
+ if (nodeHasLiveSessionPendingClaim(components, meshId, nodeId)) {
1811
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_live_session_pending_claim', nodeId });
1812
+ continue;
1813
+ }
1814
+ // Write tasks keep the one-active-per-node invariant (worktree isolation);
1815
+ // read-only diagnoses may auto-launch onto a node that already has an active
1816
+ // assignment. Classified by the shared isTaskReadonly predicate.
1817
+ if (!isTaskReadonly(task) && nodeHasActiveAssignment(meshId, nodeId)) {
1818
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
1819
+ continue;
1820
+ }
1821
+ const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
1822
+ if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
1823
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
1824
+ continue;
1825
+ }
1826
+
1827
+ autoLaunchInProgress.add(launchKey);
1828
+ try {
1829
+ const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
1830
+ if (!resolved.providerType) {
1831
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
1832
+ continue;
1833
+ }
1834
+
1835
+ // Don't spawn a session for a (node, provider) already at its declared
1836
+ // maxParallel cap — it would launch only to fail the claim. The claim
1837
+ // transaction enforces the cap regardless; this just avoids a doomed launch.
1838
+ const providerCap = resolveProviderMaxParallel(node?.policy, resolved.providerType);
1839
+ if (
1840
+ providerCap !== undefined
1841
+ && activeProviderAssignedCount(meshId, nodeId, resolved.providerType) >= providerCap
1842
+ ) {
1843
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_provider_parallel_reached', nodeId, providerType: resolved.providerType });
1844
+ continue;
1845
+ }
1846
+
1847
+ // Shared worker-launch envelope. For a local node it spawns directly on this
1848
+ // daemon; for a remote node the identical command is forwarded to the node's
1849
+ // daemon (mirrors mesh_launch_session), with the coordinator daemonId stamped
1850
+ // so the worker's completion events route back to this coordinator.
1851
+ const launchSettings: Record<string, unknown> = {
1852
+ // Worker launch envelope: role + mesh context so worker can route completion events.
1853
+ role: 'worker',
1854
+ meshNodeFor: meshId,
1855
+ meshNodeId: nodeId,
1856
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1857
+ // Coordinator-dispatched worker: auto-approve unless mesh/node policy
1858
+ // opts out (default true). Lands in settingsOverride and beats the
1859
+ // global per-provider-type autoApprove config (see shouldAutoApprove).
1860
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1861
+ launchedByCoordinator: true,
1862
+ autoLaunchedForQueueTaskId: task.id,
1863
+ };
1864
+
1865
+ if (launchTarget.mode === 'remote') {
1866
+ // Relay-safe completion routing: stamp the coordinator anchor the same way
1867
+ // mesh_launch_session does so the worker forwards events back to this daemon.
1868
+ const remoteSettings: Record<string, unknown> = {
1869
+ ...launchSettings,
1870
+ meshCoordinatorDaemonId: launchTarget.coordinatorDaemonId,
1871
+ meshCoordinatorNodeId: nodeId,
1872
+ };
1873
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1874
+ let launchResult: any;
1875
+ try {
1876
+ launchResult = await components.dispatchMeshCommand!(launchTarget.daemonId!, 'launch_cli', {
1877
+ cliType: resolved.providerType,
1878
+ dir: node.workspace,
1879
+ settings: remoteSettings,
1880
+ // MAGI-KIND-PANEL model axis: forward the task's model override so the
1881
+ // remote worker session launches with it (initialModel). Best-effort.
1882
+ ...(typeof task.model === 'string' && task.model.trim() ? { initialModel: task.model.trim() } : {}),
1883
+ });
1884
+ } catch (e: any) {
1885
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: `remote_launch_dispatch_failed: ${e?.message || String(e)}`, nodeId, providerType: resolved.providerType });
1886
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1887
+ return false;
1888
+ }
1889
+ const payload = (launchResult && typeof launchResult === 'object' && 'payload' in launchResult && launchResult.payload && typeof launchResult.payload === 'object')
1890
+ ? launchResult.payload
1891
+ : launchResult;
1892
+ if (!payload?.success) {
1893
+ const reason = readNonEmptyString(payload?.error) || 'remote_launch_cli_failed';
1894
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1895
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1896
+ return false;
1897
+ }
1898
+ // Remote launch is async: the worker session will register and emit agent:ready,
1899
+ // which (forwarded back here) drives the claim via the normal event path / PHASE 1
1900
+ // reconcile. Set a cooldown so the 4s loop doesn't re-launch before that lands.
1901
+ const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
1902
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || undefined });
1903
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1904
+ return true;
1905
+ }
1906
+
1907
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1908
+ const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
1909
+ cliType: resolved.providerType,
1910
+ dir: node.workspace,
1911
+ settings: launchSettings,
1912
+ // MAGI-KIND-PANEL model axis: local launch forwards the task's model
1913
+ // override as initialModel (CLI → modelLaunchArgs; ACP → setConfigOption).
1914
+ ...(typeof task.model === 'string' && task.model.trim() ? { initialModel: task.model.trim() } : {}),
1915
+ });
1916
+ if (!launchResult?.success) {
1917
+ const reason = launchResult?.error || 'launch_cli_failed';
1918
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1919
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1920
+ return false;
1921
+ }
1922
+ const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
1923
+ if (!sessionId) {
1924
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
1925
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1926
+ return false;
1927
+ }
1928
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
1929
+ // Readiness barrier: a freshly-spawned local CLI session is NOT yet
1930
+ // interactive — its PTY prints the input prompt (and the adapter flips
1931
+ // isReady()) only ~2-6s after launch. Dispatching the task immediately
1932
+ // pushes the first (often large) message into a not-yet-ready PTY, which
1933
+ // could throw "not ready" and bounce the task through requeue (on win32
1934
+ // this raced the auto-launch cooldown and stranded the worker idle).
1935
+ // Await interactive readiness before claiming/dispatching so the very
1936
+ // first message lands cleanly. The adapter's queue-until-ready path is the
1937
+ // backstop if readiness is reported late; this just avoids the churn.
1938
+ await waitForLocalSessionReady(components, sessionId);
1939
+ tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
1940
+ return true;
1941
+ } catch (e: any) {
1942
+ markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
1943
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
1944
+ return false;
1945
+ } finally {
1946
+ autoLaunchInProgress.delete(launchKey);
1947
+ }
1948
+ }
1949
+ }
1950
+ return false;
1951
+ }
1952
+
1953
+ export interface MeshQueueTriggerResult {
1954
+ success: true;
1955
+ meshId: string;
1956
+ pendingBefore: number;
1957
+ assignedBefore: number;
1958
+ pendingAfter: number;
1959
+ assignedAfter: number;
1960
+ claimed: boolean;
1961
+ newlyAssignedTasks: Array<{
1962
+ id: string;
1963
+ nodeId?: string;
1964
+ sessionId?: string;
1965
+ }>;
1966
+ localIdleSessionsChecked: number;
1967
+ remoteIdleSessionsChecked: number;
1968
+ skippedSessions: Array<{
1969
+ nodeId?: string;
1970
+ sessionId?: string;
1971
+ reason: string;
1972
+ status?: string;
1973
+ }>;
1974
+ autoLaunchStarted: boolean;
1975
+ /**
1976
+ * True when a worker session is already on its way to claim a still-pending task —
1977
+ * either launched this tick (autoLaunchStarted) or launched on a prior tick and still
1978
+ * booting/awaiting-claim. Callers MUST treat this as "wait, do not launch another
1979
+ * session": a second launch double-edits the worktree. Mutually informative with
1980
+ * `noIdleMeshSessionAvailable`, which is suppressed whenever this is true.
1981
+ */
1982
+ autoLaunchPending?: boolean;
1983
+ noIdleMeshSessionAvailable?: boolean;
1984
+ }
1985
+
1986
+ function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
1987
+ return getQueue(meshId, { status: [status] as any }).length;
1988
+ }
1989
+
1990
+ function getQueueStatusById(meshId: string): Map<string, string> {
1991
+ return new Map(getQueue(meshId).map(task => [task.id, task.status]));
1992
+ }
1993
+
1994
+ export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
1995
+ const mesh = getMeshWithCache(components, meshId);
1996
+ const pendingBefore = countQueueStatus(meshId, 'pending');
1997
+ const assignedBefore = countQueueStatus(meshId, 'assigned');
1998
+ const beforeStatus = getQueueStatusById(meshId);
1999
+ const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
2000
+ let localIdleSessionsChecked = 0;
2001
+ let remoteIdleSessionsChecked = 0;
2002
+ let autoLaunchStarted = false;
2003
+ if (!mesh) {
2004
+ return {
2005
+ success: true,
2006
+ meshId,
2007
+ pendingBefore,
2008
+ assignedBefore,
2009
+ pendingAfter: pendingBefore,
2010
+ assignedAfter: assignedBefore,
2011
+ claimed: false,
2012
+ newlyAssignedTasks: [],
2013
+ localIdleSessionsChecked,
2014
+ remoteIdleSessionsChecked,
2015
+ skippedSessions: [{ reason: 'mesh_not_found' }],
2016
+ autoLaunchStarted,
2017
+ noIdleMeshSessionAvailable: true,
2018
+ };
2019
+ }
2020
+
2021
+ // Collect every idle mesh session (local CLI instances + remote idle records)
2022
+ // as drain candidates. The drain ORDER depends on the scheduling strategy:
2023
+ // - 'first_eligible' (default): local-first, then remote, exactly as before.
2024
+ // - otherwise: local + remote merged into one pool and drained in scheduling
2025
+ // order (priority → load → tie-break). This local-first debias is required
2026
+ // because without it the coordinator's own local node is always visited
2027
+ // first and greedily absorbs all untargeted work before any remote idle
2028
+ // session is even considered — the comparator alone can't spread work if
2029
+ // local is always tried first.
2030
+ const strategy = resolveSchedulingStrategy(mesh);
2031
+ const localCandidates: IdleCandidate[] = [];
2032
+
2033
+ const cliInstances = components.instanceManager.getByCategory('cli');
2034
+ for (const inst of cliInstances) {
2035
+ const state = inst.getState();
2036
+ const settings = state.settings as Record<string, unknown> || {};
2037
+
2038
+ const instMeshId = readNonEmptyString(settings.meshNodeFor);
2039
+ if (instMeshId !== meshId) continue;
2040
+
2041
+ const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
2042
+ if (!nodeId) continue;
2043
+
2044
+ if (!isIdleSessionState(state)) {
2045
+ const status = readNonEmptyString(state.status).toLowerCase();
2046
+ skippedSessions.push({
2047
+ nodeId,
2048
+ sessionId: readNonEmptyString(state.instanceId),
2049
+ reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
2050
+ status: status || undefined,
2051
+ });
2052
+ continue;
2053
+ }
2054
+
2055
+ const sessionId = state.instanceId;
2056
+ const providerType = state.type || readNonEmptyString(settings.providerType);
2057
+
2058
+ if (providerType) {
2059
+ localIdleSessionsChecked += 1;
2060
+ localCandidates.push({ nodeId, sessionId, providerType, origin: 'local', node: mesh.nodes.find((n: any) => meshNodeIdMatches(n, nodeId)) });
2061
+ } else {
2062
+ skippedSessions.push({
2063
+ nodeId,
2064
+ sessionId,
2065
+ reason: 'provider_type_missing',
2066
+ });
2067
+ }
2068
+ }
2069
+
2070
+ let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
2071
+ try {
2072
+ remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions(meshId);
2073
+ } catch { /* best-effort */ }
2074
+
2075
+ const remoteCandidates: IdleCandidate[] = [];
2076
+ for (const idle of remoteSessions) {
2077
+ // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
2078
+ // `n.id`, so an inline-cached worktree node whose identity arrived under a
2079
+ // different form is not silently dropped — leaving a remote idle session
2080
+ // unable to claim its pending queue task.
2081
+ const node = mesh.nodes.find((n: any) => meshNodeIdMatches(n, idle.nodeId));
2082
+ if (node) {
2083
+ remoteIdleSessionsChecked += 1;
2084
+ remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: 'remote', node });
2085
+ }
2086
+ }
2087
+
2088
+ const assignIdleCandidate = (candidate: IdleCandidate): void => {
2089
+ const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
2090
+ if (assigned && candidate.origin === 'remote') {
2091
+ try {
2092
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(meshId, candidate.nodeId, candidate.sessionId);
2093
+ } catch { /* best-effort */ }
2094
+ }
2095
+ };
2096
+
2097
+ if (strategy === 'first_eligible') {
2098
+ // Strict no-change: drain local idle sessions first (original order), then
2099
+ // remote idle sessions. tryAssignQueueTask is a no-op when nothing matches.
2100
+ for (const candidate of localCandidates) assignIdleCandidate(candidate);
2101
+ for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
2102
+ } else {
2103
+ // Merge local + remote into one pool and drain in scheduling order. Each
2104
+ // assignment mutates a node's active load, and the next pick re-reads it,
2105
+ // so re-ranking after every assignment keeps the spread fair as load shifts.
2106
+ // buildSchedulingPool canonicalizes every candidate's nodeId so the Set
2107
+ // dedup, baseIndex, rankIndex, and nodeActiveLoad keying below all agree on
2108
+ // one form (see the invariant on that helper).
2109
+ const { pool, uniqueNodes } = buildSchedulingPool(localCandidates, remoteCandidates);
2110
+ const baseIndex = new Map<string, number>();
2111
+ pool.forEach((c, i) => { if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i); });
2112
+ // Bump the round-robin cursor once for this whole drain pass.
2113
+ const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
2114
+ const rankIndex = new Map<string, number>(ranked.map((r, i) => [r.nodeId, i]));
2115
+ const remaining = [...pool];
2116
+ while (remaining.length > 0) {
2117
+ // Re-rank each pass so a node that just took work defers its next session.
2118
+ remaining.sort((a, b) => {
2119
+ const aPrio = resolveNodeSchedulingPriority(a.node?.policy);
2120
+ const bPrio = resolveNodeSchedulingPriority(b.node?.policy);
2121
+ if (aPrio !== bPrio) return bPrio - aPrio;
2122
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
2123
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
2124
+ if (loadDelta !== 0) return loadDelta;
2125
+ }
2126
+ return (rankIndex.get(a.nodeId) ?? 0) - (rankIndex.get(b.nodeId) ?? 0);
2127
+ });
2128
+ assignIdleCandidate(remaining.shift()!);
2129
+ }
2130
+ }
2131
+
2132
+ autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
2133
+ const afterQueue = getQueue(meshId);
2134
+ const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
2135
+ const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
2136
+ const newlyAssignedTasks = afterQueue
2137
+ .filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
2138
+ .map(task => ({
2139
+ id: task.id,
2140
+ nodeId: task.assignedNodeId,
2141
+ sessionId: task.assignedSessionId,
2142
+ }));
2143
+
2144
+ // An auto-launch is "pending" when the coordinator has already spun a session up
2145
+ // for a still-pending task and is waiting on that session's idle→claim. This covers
2146
+ // two ticks:
2147
+ // - THIS tick fired the launch (autoLaunchStarted), or
2148
+ // - a PRIOR tick launched a session that is still booting/awaiting-claim — the
2149
+ // per-task await-claim guard (maybeAutoLaunchOneQueueSession) deliberately
2150
+ // declines to launch again, so autoLaunchStarted is false even though a session
2151
+ // is on its way to claim this task.
2152
+ // Without this signal, the second tick reports `noIdleMeshSessionAvailable` and the
2153
+ // MCP guidance tells the coordinator to launch ANOTHER worker — producing a duplicate
2154
+ // session that double-edits the worktree. The claim itself is fine; only the wording
2155
+ // was wrong, so we surface `autoLaunchPending` to suppress the bad "launch one more"
2156
+ // advice while the just-launched session converges.
2157
+ const autoLaunchPending = autoLaunchStarted || afterQueue.some(task => {
2158
+ if (task.status !== 'pending') return false;
2159
+ const al = task.autoLaunch;
2160
+ if (!al || (al.status !== 'started' && al.status !== 'completed')) return false;
2161
+ const launchedAtMs = Date.parse(al.updatedAt);
2162
+ return Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS;
2163
+ });
2164
+
2165
+ return {
2166
+ success: true,
2167
+ meshId,
2168
+ pendingBefore,
2169
+ assignedBefore,
2170
+ pendingAfter,
2171
+ assignedAfter,
2172
+ claimed: newlyAssignedTasks.length > 0,
2173
+ newlyAssignedTasks,
2174
+ localIdleSessionsChecked,
2175
+ remoteIdleSessionsChecked,
2176
+ skippedSessions,
2177
+ autoLaunchStarted,
2178
+ ...(autoLaunchPending ? { autoLaunchPending: true } : {}),
2179
+ // Only report "no idle session, go launch one" when nothing is already on its way.
2180
+ // A pending auto-launch (this tick or a prior still-converging one) means a session
2181
+ // WILL claim shortly, so it is not a no-session-available situation.
2182
+ ...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchPending
2183
+ ? { noIdleMeshSessionAvailable: true }
2184
+ : {}),
2185
+ };
2186
+ }
2187
+
2188
+ export async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
2189
+ meshId: string;
2190
+ nodeId: string;
2191
+ sessionId?: string;
2192
+ providerType?: string;
2193
+ }): Promise<void> {
2194
+ const mesh = getMeshWithCache(components, args.meshId);
2195
+ const node = mesh?.nodes?.find((candidate: any) => meshNodeIdMatches(candidate, args.nodeId));
2196
+ const workspace = readNonEmptyString(node?.workspace);
2197
+ if (!workspace) return;
2198
+ if (!existsSync(workspace)) return;
2199
+
2200
+ const policy = resolveAutoFastForwardPolicy(mesh);
2201
+ if (!policy.enabled) return;
2202
+ if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
2203
+
2204
+ const throttleKey = `${args.meshId}:${args.nodeId}`;
2205
+ const now = Date.now();
2206
+ const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
2207
+ if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
2208
+ idleAutoFastForwardLastAttempt.set(throttleKey, now);
2209
+
2210
+ const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
2211
+ ? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
2212
+ : undefined;
2213
+ try {
2214
+ const dryRun = await fastForwardMeshNode({
2215
+ meshId: args.meshId,
2216
+ nodeId: args.nodeId,
2217
+ workspace,
2218
+ execute: false,
2219
+ dryRun: true,
2220
+ updateSubmodules: false,
2221
+ submoduleIgnorePaths,
2222
+ trigger: 'idle_auto',
2223
+ });
2224
+ if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
2225
+ const behind = Number(dryRun.current?.behind);
2226
+ if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
2227
+ if (policy.requireCleanSubmodules) {
2228
+ const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
2229
+ if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
2230
+ }
2231
+ await fastForwardMeshNode({
2232
+ meshId: args.meshId,
2233
+ nodeId: args.nodeId,
2234
+ workspace,
2235
+ execute: true,
2236
+ dryRun: false,
2237
+ updateSubmodules: false,
2238
+ submoduleIgnorePaths,
2239
+ trigger: 'idle_auto',
2240
+ });
2241
+ } catch (e: any) {
2242
+ LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
2243
+ }
2244
+ }
2245
+
2246
+ export function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
2247
+ meshId: string;
2248
+ nodeId: string;
2249
+ sessionId: string;
2250
+ providerType: string;
2251
+ }): void {
2252
+ setImmediate(() => {
2253
+ maybeAutoFastForwardIdleNode(components, args)
2254
+ .finally(() => {
2255
+ try {
2256
+ tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
2257
+ } catch (e: any) {
2258
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
2259
+ }
2260
+ });
2261
+ });
2262
+ }
2263
+