@adhdev/daemon-core 0.9.82-rc.45 → 0.9.82-rc.450

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