@adhdev/daemon-core 0.9.82-rc.35 → 0.9.82-rc.351

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 (318) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -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 +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +324 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +53 -13
  37. package/dist/index.js +39817 -14303
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41436 -16047
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +164 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +420 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +218 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +216 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +77 -3
  79. package/dist/providers/contracts.d.ts +139 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +14 -0
  88. package/dist/providers/provider-instance.d.ts +15 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +322 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +59 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +26 -0
  136. package/dist/system/load-better-sqlite3.d.ts +21 -0
  137. package/dist/types.d.ts +5 -0
  138. package/package.json +7 -3
  139. package/src/agent-stream/poller.ts +2 -3
  140. package/src/agent-stream/provider-adapter.ts +1 -1
  141. package/src/boot/daemon-lifecycle.ts +55 -12
  142. package/src/boot/process-hardening.ts +89 -0
  143. package/src/build-info.ts +73 -0
  144. package/src/chat/source-machine.ts +534 -0
  145. package/src/chat/source-resolver.ts +0 -0
  146. package/src/chat/subscription-updates.ts +20 -1
  147. package/src/cli-adapter-types.d.ts +1 -0
  148. package/src/cli-adapter-types.ts +47 -2
  149. package/src/cli-adapters/cli-script-runner.ts +421 -0
  150. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  151. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  152. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  153. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  154. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  155. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  156. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  157. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  158. package/src/cli-adapters/pty-transport.ts +2 -1
  159. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  160. package/src/cli-adapters/resolve-executable.ts +90 -0
  161. package/src/cli-adapters/session-host-transport.ts +2 -1
  162. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  163. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  164. package/src/cli-adapters/terminal-screen.ts +16 -81
  165. package/src/commands/chat-commands.ts +1823 -62
  166. package/src/commands/cli-manager.ts +304 -14
  167. package/src/commands/handler.ts +809 -2
  168. package/src/commands/mesh-coordinator.ts +332 -122
  169. package/src/commands/router.ts +7505 -1311
  170. package/src/commands/stream-commands.ts +8 -0
  171. package/src/commands/upgrade-helper.ts +81 -30
  172. package/src/config/chat-history.ts +483 -24
  173. package/src/config/config.ts +12 -0
  174. package/src/config/mesh-config.ts +388 -6
  175. package/src/config/recent-activity.ts +8 -2
  176. package/src/daemon/dev-auto-implement.ts +3 -2
  177. package/src/daemon/dev-cli-debug.ts +10 -1
  178. package/src/detection/cli-detector.ts +28 -9
  179. package/src/detection/ide-detector.ts +55 -16
  180. package/src/detection/win32-ide-version.ts +106 -0
  181. package/src/git/change-impact-config.ts +354 -0
  182. package/src/git/git-commands.ts +55 -14
  183. package/src/git/git-diff.ts +53 -0
  184. package/src/git/git-executor.ts +12 -0
  185. package/src/git/git-status.ts +574 -43
  186. package/src/git/git-types.ts +14 -62
  187. package/src/git/git-worktree.ts +8 -1
  188. package/src/git/index.ts +16 -0
  189. package/src/index.ts +151 -12
  190. package/src/installer.d.ts +1 -1
  191. package/src/installer.ts +8 -6
  192. package/src/ipc/local-ipc-server.ts +278 -0
  193. package/src/launch.d.ts +1 -1
  194. package/src/launch.ts +37 -28
  195. package/src/logging/async-batch-writer.ts +55 -0
  196. package/src/logging/log-redactor.ts +100 -0
  197. package/src/logging/log-tail-reader.ts +220 -0
  198. package/src/logging/logger.ts +2 -1
  199. package/src/mesh/contracts.ts +329 -0
  200. package/src/mesh/coordinator-prompt.ts +234 -31
  201. package/src/mesh/coordinator-registry.ts +121 -0
  202. package/src/mesh/mesh-active-work.ts +667 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2303 -0
  205. package/src/mesh/mesh-events-pending.ts +567 -0
  206. package/src/mesh/mesh-events-stale.ts +307 -0
  207. package/src/mesh/mesh-events-utils.ts +381 -0
  208. package/src/mesh/mesh-events.ts +30 -1035
  209. package/src/mesh/mesh-fast-forward.ts +839 -0
  210. package/src/mesh/mesh-host-ownership.ts +73 -0
  211. package/src/mesh/mesh-init.ts +260 -0
  212. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  213. package/src/mesh/mesh-ledger.ts +590 -102
  214. package/src/mesh/mesh-missions.ts +322 -0
  215. package/src/mesh/mesh-reconcile-loop.ts +989 -0
  216. package/src/mesh/mesh-refine-batch.ts +197 -0
  217. package/src/mesh/mesh-refine-status.ts +231 -0
  218. package/src/mesh/mesh-review-inbox.ts +307 -0
  219. package/src/mesh/mesh-routing.ts +291 -0
  220. package/src/mesh/mesh-runtime-store.ts +1664 -0
  221. package/src/mesh/mesh-task-stats.ts +161 -0
  222. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  223. package/src/mesh/mesh-work-queue.ts +901 -141
  224. package/src/mesh/preview-freshness.ts +118 -0
  225. package/src/mesh/refine-config.ts +423 -0
  226. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  227. package/src/providers/acp-provider-instance.ts +25 -9
  228. package/src/providers/approval-utils.d.ts +4 -0
  229. package/src/providers/approval-utils.ts +47 -5
  230. package/src/providers/chat-message-normalization.ts +45 -5
  231. package/src/providers/cli-provider-instance.ts +1041 -99
  232. package/src/providers/contracts.d.ts +55 -0
  233. package/src/providers/contracts.ts +150 -6
  234. package/src/providers/extension-provider-instance.ts +12 -7
  235. package/src/providers/external-sources.ts +218 -0
  236. package/src/providers/ide-provider-instance.ts +35 -12
  237. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  238. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  239. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  240. package/src/providers/native-history/dispatcher.ts +340 -0
  241. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  242. package/src/providers/native-history/index.ts +30 -0
  243. package/src/providers/provider-instance-manager.ts +30 -0
  244. package/src/providers/provider-instance.ts +10 -1
  245. package/src/providers/provider-loader.ts +670 -50
  246. package/src/providers/provider-schema.ts +87 -14
  247. package/src/providers/provider-trust.ts +114 -0
  248. package/src/providers/read-chat-contract.ts +76 -16
  249. package/src/providers/sdk/README.md +49 -0
  250. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  251. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  254. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  255. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  256. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  257. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  258. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  259. package/src/providers/sdk/v1/index.ts +152 -0
  260. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  261. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  262. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  263. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  264. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  265. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  280. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  281. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  282. package/src/providers/sdk/v1/validators/index.ts +19 -0
  283. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  284. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  285. package/src/providers/spec/adapter.ts +168 -0
  286. package/src/providers/spec/cli-adapter.ts +986 -0
  287. package/src/providers/spec/evaluator.ts +345 -0
  288. package/src/providers/spec/fsm-driver.ts +1065 -0
  289. package/src/providers/spec/fsm-evaluator.ts +255 -0
  290. package/src/providers/spec/fsm-loader.ts +120 -0
  291. package/src/providers/spec/fsm-types.ts +238 -0
  292. package/src/providers/spec/native-history-executor.ts +1136 -0
  293. package/src/providers/spec/pre-launch-trust.ts +104 -0
  294. package/src/providers/spec/route.ts +51 -0
  295. package/src/providers/spec/types.ts +226 -0
  296. package/src/providers/status-monitor.d.ts +7 -7
  297. package/src/providers/status-monitor.ts +37 -22
  298. package/src/providers/transcript-v2.ts +567 -0
  299. package/src/providers/types/interactive-prompt.ts +536 -0
  300. package/src/providers/version-archive.ts +64 -24
  301. package/src/providers/working-dir.ts +23 -0
  302. package/src/repo-mesh-types.ts +378 -14
  303. package/src/sessions/registry.ts +6 -0
  304. package/src/shared-types-extra.ts +2 -4
  305. package/src/shared-types.d.ts +8 -0
  306. package/src/shared-types.ts +64 -1
  307. package/src/status/builders.ts +26 -6
  308. package/src/status/normalize.ts +2 -0
  309. package/src/status/reporter.ts +19 -1
  310. package/src/status/snapshot.ts +95 -26
  311. package/src/system/host-memory.ts +29 -12
  312. package/src/system/load-better-sqlite3.ts +68 -0
  313. package/src/types.ts +5 -0
  314. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  315. package/dist/mesh/mesh-sync.d.ts +0 -53
  316. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  317. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  318. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,2303 @@
1
+ import { existsSync } from 'fs';
2
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
3
+ import { loadConfig } from '../config/config.js';
4
+ import { getMesh, getMeshByRepo } from '../config/mesh-config.js';
5
+ import { detectCLI } from '../detection/cli-detector.js';
6
+ import { LOG } from '../logging/logger.js';
7
+ import { appendLedgerEntry, buildTaskCompletionEvidence, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
8
+ import type { MeshLedgerKind, SessionRecoveryContext } from './mesh-ledger.js';
9
+ import { buildMeshNodeCapabilityTags, nodeSatisfiesRequiredTags, claimNextTask, updateSessionTaskStatus, enqueueTask, updateTaskStatus, getQueue, recordTaskAutoLaunch, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, getActiveDirectDispatches, hasPendingDependents } from './mesh-work-queue.js';
10
+ import { fastForwardMeshNode } from './mesh-fast-forward.js';
11
+ import { createSessionDelivery, markSessionDeliveriesTerminal, updateSessionDeliveryStatus, recordCompletionConflict } from './mesh-delivery-policy.js';
12
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
13
+ import { queuePendingMeshCoordinatorEvent, drainPendingMeshCoordinatorEvents } from './mesh-events-pending.js';
14
+ import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
15
+ import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent, isUnroutableDelegateRejection } from './mesh-routing.js';
16
+ import { enqueueUnresolvedDelegateForward, peekUnresolvedDelegateForwards, ackUnresolvedDelegateForward } from './mesh-unresolved-forward-outbox.js';
17
+ import { getLastDisplayMessage } from '../status/snapshot.js';
18
+ import { resolveDelegatedWorkerAutoApprove, resolveProviderMaxParallel, resolveNodeSchedulingPriority, normalizeMeshSchedulingStrategy } from '../repo-mesh-types.js';
19
+ import type { RepoMeshSchedulingStrategy } from '../repo-mesh-types.js';
20
+ import { normalizeMeshNodeId, meshNodeIdMatches, type MeshNodeIdentified } from '@adhdev/mesh-shared';
21
+ import {
22
+ findRecentTerminalLedgerEvidence,
23
+ hasDispatchAfterTerminal,
24
+ hasUnterminalDirectDispatchLedgerEntry,
25
+ buildNoProgressCompletionReconciliation,
26
+ } from './mesh-events-stale.js';
27
+ import {
28
+ buildMeshSystemMessage,
29
+ readNonEmptyString,
30
+ readRecord,
31
+ resolveEventSessionId,
32
+ readRefineJobId,
33
+ readWorkerResultMetadata,
34
+ resolveMeshSurfacedSessionPreview,
35
+ } from './mesh-events-utils.js';
36
+
37
+ // The set of coordinator-daemon ids this daemon answers to when draining the
38
+ // pending-events queue (canonical status id + bare machineId). Mirrors
39
+ // resolveCoordinatorDaemonIds in mesh-reconcile-loop — a unicast event may be
40
+ // stamped with either id depending on which dispatch path created the worker.
41
+ function resolveCoordinatorDrainDaemonIds(components: DaemonComponents): string[] {
42
+ const ids = new Set<string>();
43
+ const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
44
+ if (statusInstanceId) ids.add(statusInstanceId);
45
+ const machineId = readNonEmptyString(loadConfig().machineId);
46
+ if (machineId) ids.add(machineId);
47
+ return [...ids];
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Remote Node Idle Session Tracking
52
+ // ---------------------------------------------------------------------------
53
+ const REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
54
+
55
+ // ---------------------------------------------------------------------------
56
+ // Workspace-to-mesh lookup cache
57
+ // ---------------------------------------------------------------------------
58
+ const meshByWorkspaceCache = new Map<string, { mesh: any; cachedAt: number }>();
59
+ const MESH_WORKSPACE_CACHE_TTL_MS = 5_000;
60
+ const IDLE_AUTO_FAST_FORWARD_THROTTLE_MS = 30 * 60 * 1000;
61
+ const idleAutoFastForwardLastAttempt = new Map<string, number>();
62
+
63
+ function getCachedMeshByWorkspace(workspace: string): any {
64
+ const now = Date.now();
65
+ const cached = meshByWorkspaceCache.get(workspace);
66
+ if (cached && now - cached.cachedAt < MESH_WORKSPACE_CACHE_TTL_MS) return cached.mesh;
67
+ const mesh = getMeshByRepo(workspace);
68
+ meshByWorkspaceCache.set(workspace, { mesh, cachedAt: now });
69
+ return mesh;
70
+ }
71
+
72
+ export function __resetIdleAutoFastForwardForTests(): void {
73
+ idleAutoFastForwardLastAttempt.clear();
74
+ }
75
+
76
+ export function __resetMeshWorkspaceCacheForTests(): void {
77
+ meshByWorkspaceCache.clear();
78
+ }
79
+
80
+ function sweepExpiredRemoteIdleSessions(): void {
81
+ try {
82
+ MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
83
+ } catch { /* best-effort */ }
84
+ }
85
+
86
+ function getMeshWithCache(components: DaemonComponents, meshId: string): any | undefined {
87
+ const localMesh = getMesh(meshId);
88
+ if (localMesh) return localMesh;
89
+ return components.router?.getCachedInlineMesh(meshId);
90
+ }
91
+
92
+ const INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1000;
93
+
94
+ function isIntentionalCleanupStopMetadata(event: Record<string, unknown>): boolean {
95
+ return event.intentional === true
96
+ || event.intentionalStop === true
97
+ || event.operatorCleanup === true
98
+ || event.reason === 'operator_cleanup'
99
+ || event.stopReason === 'operator_cleanup'
100
+ || event.cleanupReason === 'operator_cleanup'
101
+ || event.source === 'mesh_cleanup_sessions'
102
+ || event.source === 'mesh_remove_node';
103
+ }
104
+
105
+ function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nodeId?: string): boolean {
106
+ if (!sessionId && !nodeId) return false;
107
+ const cutoff = Date.now() - INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS;
108
+ const entries = readLedgerEntries(meshId, { tail: 200 });
109
+ for (let i = entries.length - 1; i >= 0; i--) {
110
+ const entry = entries[i];
111
+ const timestamp = new Date(entry.timestamp).getTime();
112
+ if (!Number.isNaN(timestamp) && timestamp < cutoff) break;
113
+ if (!isIntentionalCleanupStopEntry(entry)) continue;
114
+ if (sessionId && entry.sessionId === sessionId) return true;
115
+ // Normalized node-id match (P4): the cleanup-stop entry's node id may be stored as
116
+ // `nodeId` or `node_id` and the `nodeId` arg can be in either form — a raw `===`
117
+ // would miss a genuine intentional-cleanup entry and fail to suppress the stop event.
118
+ if (!sessionId && nodeId && meshNodeIdMatches(entry as unknown as MeshNodeIdentified, nodeId)) return true;
119
+ }
120
+ return false;
121
+ }
122
+
123
+ function shouldSuppressIntentionalCleanupStop(args: {
124
+ event: string;
125
+ meshId: string;
126
+ metadataEvent: Record<string, unknown>;
127
+ sessionId?: string;
128
+ nodeId?: string;
129
+ }): boolean {
130
+ if (args.event !== 'agent:stopped' && args.event !== 'monitor:no_progress') return false;
131
+ if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
132
+ return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
133
+ }
134
+
135
+ const RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1000;
136
+
137
+ function hasFingerprintSeen(fingerprint: string): boolean {
138
+ try {
139
+ return MeshRuntimeStore.getInstance().hasCompletionFingerprint(fingerprint);
140
+ } catch {
141
+ return false;
142
+ }
143
+ }
144
+
145
+ function recordFingerprintSeen(fingerprint: string): void {
146
+ try {
147
+ const db = MeshRuntimeStore.getInstance();
148
+ db.recordCompletionFingerprint(fingerprint, RECENT_COMPLETION_FINGERPRINT_TTL_MS);
149
+ db.sweepExpiredFingerprints();
150
+ } catch { /* best-effort; duplicate events are preferable to a crash */ }
151
+ }
152
+
153
+ function readEventTimestamp(value: unknown): number | null {
154
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
155
+ if (typeof value === 'string' && value.trim()) {
156
+ const numeric = Number(value);
157
+ if (Number.isFinite(numeric)) return numeric;
158
+ const parsed = Date.parse(value);
159
+ if (Number.isFinite(parsed)) return parsed;
160
+ }
161
+ return null;
162
+ }
163
+
164
+ function buildMeshCompletionFingerprint(args: {
165
+ meshId: string;
166
+ event: string;
167
+ sessionId: string;
168
+ providerType?: string;
169
+ providerSessionId?: string;
170
+ timestamp?: number | null;
171
+ finalSummary?: string;
172
+ coordinatorDaemonId?: string;
173
+ }): string {
174
+ const timestampPart = Number.isFinite(args.timestamp)
175
+ ? String(args.timestamp)
176
+ : readNonEmptyString(args.finalSummary).slice(0, 200);
177
+ return [
178
+ args.meshId,
179
+ args.event,
180
+ args.sessionId,
181
+ args.providerType || '',
182
+ args.providerSessionId || '',
183
+ timestampPart,
184
+ args.coordinatorDaemonId || '',
185
+ ].join('::');
186
+ }
187
+
188
+ function isDuplicateMeshCompletionEvent(args: {
189
+ meshId: string;
190
+ event: string;
191
+ sessionId: string;
192
+ providerType?: string;
193
+ providerSessionId?: string;
194
+ timestamp?: number | null;
195
+ finalSummary?: string;
196
+ coordinatorDaemonId?: string;
197
+ taskId?: string;
198
+ nodeId?: string;
199
+ }): boolean {
200
+ const fingerprint = buildMeshCompletionFingerprint(args);
201
+ if (!fingerprint) return false;
202
+ if (hasFingerprintSeen(fingerprint)) {
203
+ if (args.taskId) {
204
+ recordCompletionConflict({
205
+ meshId: args.meshId,
206
+ fingerprint,
207
+ conflictingTaskId: args.taskId,
208
+ conflictingSessionId: args.sessionId,
209
+ event: args.event,
210
+ });
211
+ }
212
+ return true;
213
+ }
214
+ recordFingerprintSeen(fingerprint);
215
+ return false;
216
+ }
217
+
218
+ function isDuplicateMeshApprovalEvent(args: {
219
+ meshId: string;
220
+ sessionId: string;
221
+ providerType?: string;
222
+ timestamp?: number | null;
223
+ modalMessage?: string;
224
+ modalButtons?: unknown;
225
+ }): boolean {
226
+ const modalButtons = Array.isArray(args.modalButtons)
227
+ ? args.modalButtons.map(button => String(button).trim()).filter(Boolean)
228
+ : [];
229
+ const approvalIdentity = Number.isFinite(args.timestamp)
230
+ ? String(args.timestamp)
231
+ : JSON.stringify({ message: args.modalMessage || '', buttons: modalButtons });
232
+ if (!approvalIdentity || approvalIdentity === '{"message":"","buttons":[]}') return false;
233
+ const fingerprint = [
234
+ args.meshId,
235
+ 'agent:waiting_approval',
236
+ args.sessionId,
237
+ args.providerType || '',
238
+ approvalIdentity,
239
+ ].join('::');
240
+ if (hasFingerprintSeen(fingerprint)) return true;
241
+ recordFingerprintSeen(fingerprint);
242
+ return false;
243
+ }
244
+
245
+ function isDuplicateRefineTerminalEvent(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): boolean {
246
+ const jobId = readRefineJobId({ metadataEvent });
247
+ const fingerprint = jobId && new Set(['refine:completed', 'refine:failed']).has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
248
+ if (!fingerprint) return false;
249
+ if (hasFingerprintSeen(fingerprint)) return true;
250
+ recordFingerprintSeen(fingerprint);
251
+ return false;
252
+ }
253
+
254
+ // A worker/coordinator "false idle": the provider dropped to idle WITHOUT a confirmed
255
+ // final assistant message for the turn (a finalization timeout, or a "scheduled fallback"
256
+ // idle). This is the signal cli-provider-instance emits as
257
+ // completionDiagnostic.blockReason='missing_final_assistant' / finalAssistantPresent=false.
258
+ // Such a completion is NOT trustworthy terminal evidence: it must neither permanently
259
+ // terminate a direct-dispatch task nor suppress the genuine completion a later turn
260
+ // (commonly driven by a coordinator nudge / re-dispatch) produces.
261
+ function isFalseIdleCompletion(metadataEvent: Record<string, unknown>): boolean {
262
+ const diag = readRecord(metadataEvent.completionDiagnostic);
263
+ if (!diag) return false;
264
+ return diag.finalAssistantPresent === false || diag.blockReason === 'missing_final_assistant';
265
+ }
266
+
267
+ // The genuine-completion counterpart: a real final summary / worker result is present and
268
+ // the completion is not flagged as a missing-final-assistant false idle. Used to decide
269
+ // whether a new completion may supersede a prior WEAK (false-idle) terminal.
270
+ function isGenuineCompletionEvidence(metadataEvent: Record<string, unknown>): boolean {
271
+ if (isFalseIdleCompletion(metadataEvent)) return false;
272
+ return !!readWorkerResultMetadata(metadataEvent) || !!readNonEmptyString(metadataEvent.finalSummary);
273
+ }
274
+
275
+ // True when a terminal ledger payload was recorded from WEAK completion evidence (a false
276
+ // idle): insufficient evidence level, review-recommended, or a missing-final-assistant
277
+ // completion diagnostic. A weak terminal is non-authoritative — a later genuine completion
278
+ // (live path) or a transcript reconcile (fallback path) may supersede it.
279
+ function isWeakTerminalLedgerPayload(payload: Record<string, unknown> | undefined): boolean {
280
+ if (!payload) return false;
281
+ if (payload.evidenceLevel === 'insufficient' || payload.reviewRecommended === true) return true;
282
+ const diag = readRecord(payload.completionDiagnostic);
283
+ return diag?.finalAssistantPresent === false || diag?.blockReason === 'missing_final_assistant';
284
+ }
285
+
286
+ // The latest still-active direct-dispatch taskId for a session, resolved BEFORE the
287
+ // completion flips the dispatch row terminal. Direct dispatches (mesh_send_task) have no
288
+ // work-queue row, so this is the only taskId available to attribute the terminal ledger
289
+ // entry (and thus mesh task-stats) to — without it the terminal carries no taskId and the
290
+ // task surfaces as status='unknown' / terminalKind=null in computeMeshTaskStats.
291
+ function resolveActiveDirectDispatchTaskId(meshId: string, sessionId: string): string | undefined {
292
+ try {
293
+ const matches = getActiveDirectDispatches(meshId).filter(d => d.sessionId === sessionId);
294
+ if (!matches.length) return undefined;
295
+ // getActiveDirectDispatches returns rows ordered by dispatched_at ASC; the last is
296
+ // the most recent dispatch (the re-dispatch / nudge whose completion this is).
297
+ return readNonEmptyString(matches[matches.length - 1].taskId) || undefined;
298
+ } catch {
299
+ return undefined;
300
+ }
301
+ }
302
+
303
+ // ---------------------------------------------------------------------------
304
+ // Queue assignment
305
+ // ---------------------------------------------------------------------------
306
+
307
+ export function tryAssignQueueTask(
308
+ components: DaemonComponents,
309
+ meshId: string,
310
+ nodeId: string,
311
+ sessionId: string,
312
+ providerType: string
313
+ ): boolean {
314
+ const mesh = getMeshWithCache(components, meshId);
315
+ const node = mesh?.nodes.find((n: any) => readMeshNodeId(n) === nodeId);
316
+ const capabilityTags = buildMeshNodeCapabilityTags(node, providerType);
317
+ // Per-(node, provider) maxParallel cap (RepoMeshNodePolicy.providerRoles) layers
318
+ // on top of the global/taskMode caps — stricter wins. Resolved here where the
319
+ // claiming session's providerType + node policy are both known, then enforced
320
+ // inside the atomic claim transaction so concurrent claims can't overshoot it.
321
+ const providerMaxParallel = resolveProviderMaxParallel(node?.policy, providerType);
322
+ const task = claimNextTask(meshId, nodeId, sessionId, capabilityTags, {
323
+ providerType,
324
+ ...(providerMaxParallel !== undefined ? { providerMaxParallel } : {}),
325
+ });
326
+ if (!task) {
327
+ return false;
328
+ }
329
+
330
+ LOG.info('MeshQueue', `Node ${nodeId} (${sessionId}) pulled task ${task.id}`);
331
+
332
+ if (node?.daemonId && components.dispatchMeshCommand) {
333
+ const isLocalNode = components.cliManager.adapters.has(sessionId);
334
+ if (!isLocalNode) {
335
+ const localDaemonIdForDispatch = readNonEmptyString(loadConfig().machineId) || undefined;
336
+ // (3) Originating coordinator session that enqueued this task — route its
337
+ // completion back to that exact session (multi-coordinator). Carried over P2P
338
+ // to the remote worker, which echoes it on its completion event.
339
+ const sourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId) || undefined;
340
+ const delivery = createSessionDelivery({
341
+ meshId,
342
+ nodeId,
343
+ sessionId,
344
+ providerType,
345
+ taskId: task.id,
346
+ kind: 'task',
347
+ message: task.message,
348
+ status: 'delivering',
349
+ ...(sourceCoordinatorSessionId ? { sourceCoordinatorSessionId } : {}),
350
+ ...(localDaemonIdForDispatch ? { sourceCoordinatorDaemonId: localDaemonIdForDispatch } : {}),
351
+ });
352
+ components.dispatchMeshCommand(node.daemonId, 'agent_command', {
353
+ targetSessionId: sessionId,
354
+ cliType: providerType,
355
+ action: 'send_chat',
356
+ message: task.message,
357
+ meshContext: {
358
+ meshId,
359
+ nodeId,
360
+ taskId: task.id,
361
+ ...(localDaemonIdForDispatch ? { coordinatorDaemonId: localDaemonIdForDispatch } : {}),
362
+ ...(sourceCoordinatorSessionId ? { coordinatorSessionId: sourceCoordinatorSessionId } : {}),
363
+ },
364
+ }).then(() => {
365
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
366
+ }).catch((e: any) => {
367
+ LOG.error('MeshQueue', `Failed to dispatch task via P2P to remote node ${nodeId}: ${e?.message}`);
368
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
369
+ updateTaskStatus(meshId, task.id, 'pending');
370
+ try {
371
+ appendLedgerEntry(meshId, {
372
+ kind: 'dispatch_failed' as any,
373
+ nodeId,
374
+ sessionId,
375
+ payload: { taskId: task.id, deliveryId: delivery.id, error: e?.message, retryable: true },
376
+ });
377
+ } catch { /* ledger write is best-effort */ }
378
+ });
379
+ return true;
380
+ }
381
+ }
382
+
383
+ // Stamp mesh context onto the session so completion events route correctly
384
+ // via setupMeshEventForwarding. Without this, manually-opened idle sessions
385
+ // (mesh_launch_session without auto-launch) lack meshNodeFor/meshNodeId and
386
+ // agent:generating_completed is silently dropped as isMeshDelegate=false.
387
+ try {
388
+ const inst = components.instanceManager.getInstance(sessionId);
389
+ if (inst && typeof inst.updateSettings === 'function') {
390
+ // Adopting a (possibly manually-opened) local session as a worker: apply the
391
+ // delegated-worker auto-approve policy here too, so a session that was launched
392
+ // without autoApprove still auto-approves once the coordinator dispatches a task
393
+ // to it (the "approval notification fires only for certain delegated sessions"
394
+ // case). updateSettings preserves runtime mesh keys; passing autoApprove keeps it.
395
+ //
396
+ // This local-dispatch branch also runs on the coordinator daemon for a co-located
397
+ // session, so the coordinator daemon id IS this daemon's id. Stamp it alongside
398
+ // the node identity so the session is fully relay-safe (meshCoordinatorDaemonId is
399
+ // the anchor the forwarder keys on), matching what mesh_launch_session stamps.
400
+ const localDaemonId = readNonEmptyString(loadConfig().machineId);
401
+ const localSourceCoordinatorSessionId = readNonEmptyString(task.sourceCoordinatorSessionId);
402
+ inst.updateSettings({
403
+ meshNodeFor: meshId,
404
+ meshNodeId: nodeId,
405
+ launchedByCoordinator: true,
406
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
407
+ ...(localDaemonId ? { meshCoordinatorDaemonId: localDaemonId } : {}),
408
+ // (3) Stamp the originating coordinator session for session-anchored routing
409
+ // of this co-located worker's completion. Absent → daemon-level fallback.
410
+ ...(localSourceCoordinatorSessionId ? { meshCoordinatorSessionId: localSourceCoordinatorSessionId } : {}),
411
+ });
412
+ }
413
+ } catch { /* best-effort — dispatch still proceeds */ }
414
+
415
+ const delivery = createSessionDelivery({
416
+ meshId,
417
+ nodeId,
418
+ sessionId,
419
+ providerType,
420
+ taskId: task.id,
421
+ kind: 'task',
422
+ message: task.message,
423
+ status: 'delivering',
424
+ ...(readNonEmptyString(task.sourceCoordinatorSessionId) ? { sourceCoordinatorSessionId: readNonEmptyString(task.sourceCoordinatorSessionId) } : {}),
425
+ ...(readNonEmptyString(loadConfig().machineId) ? { sourceCoordinatorDaemonId: readNonEmptyString(loadConfig().machineId) } : {}),
426
+ });
427
+ components.cliManager.handleCliCommand('agent_command', {
428
+ targetSessionId: sessionId,
429
+ cliType: providerType,
430
+ action: 'send_chat',
431
+ message: task.message,
432
+ }).then(() => {
433
+ updateSessionDeliveryStatus(delivery.id, 'delivered');
434
+ }).catch((e: any) => {
435
+ // Mirror the remote-dispatch catch above: a local dispatch failure is most often a
436
+ // transient busy/refusal (e.g. the adapter rejected send_chat while mid-generation),
437
+ // not a permanent task failure. Marking the task terminal 'failed' here with no ledger
438
+ // and no retry permanently killed tasks that a later tick would have delivered fine.
439
+ // Return the task to 'pending' and record a retryable dispatch_failed ledger entry so
440
+ // the reconcile loop re-dispatches it, exactly as the remote branch does.
441
+ LOG.error('MeshQueue', `Failed to dispatch task locally to node ${nodeId}: ${e?.message}`);
442
+ updateSessionDeliveryStatus(delivery.id, 'failed', { lastError: e?.message, incrementAttempt: true });
443
+ updateTaskStatus(meshId, task.id, 'pending');
444
+ try {
445
+ appendLedgerEntry(meshId, {
446
+ kind: 'dispatch_failed' as any,
447
+ nodeId,
448
+ sessionId,
449
+ payload: { taskId: task.id, deliveryId: delivery.id, error: e?.message, retryable: true },
450
+ });
451
+ } catch { /* ledger write is best-effort */ }
452
+ });
453
+
454
+ return true;
455
+ }
456
+
457
+ const autoLaunchInProgress = new Set<string>();
458
+ const autoLaunchCooldownUntil = new Map<string, number>();
459
+ const AUTO_LAUNCH_COOLDOWN_MS = 5_000;
460
+ // A remote auto-launch (launch_cli forward) is fire-and-async: the worker session
461
+ // spawns, reaches idle, emits agent:ready, that ready is queued on the worker, pulled
462
+ // by this coordinator (reconcile PHASE 1), and only THEN claims the task. That round
463
+ // trip routinely exceeds the 5s per-(mesh,node) cooldown, so cooldown alone lets the
464
+ // reconcile loop fire a SECOND launch for the same still-pending task before the first
465
+ // session's claim lands — every tick spawns yet another orphan session (observed live:
466
+ // 26 sessions for one task). This is a per-TASK await-claim window: once a task has a
467
+ // successfully-launched session whose claim we are still waiting on, do not launch it
468
+ // again until the window lapses. It is generous (a slow remote spawn can take tens of
469
+ // seconds) but bounded so a launch that silently never reaches idle is eventually retried.
470
+ const AUTO_LAUNCH_AWAIT_CLAIM_MS = 90_000;
471
+
472
+ // De-dup for repeated `skipped` ledger noise: the reconcile loop re-runs the queue
473
+ // trigger every 4s, so a task that can't be claimed (e.g. a remote node with no
474
+ // transport, or a node under cooldown) would otherwise append an identical
475
+ // session_auto_launch{phase:'skipped'} entry on every tick — flooding the ledger.
476
+ // We suppress a `skipped` ledger append when the immediately-prior recorded event
477
+ // for that task was the SAME (phase, reason). Any non-skip phase (started/failed/
478
+ // completed) or a changed reason resets the de-dup so real transitions still record.
479
+ const lastAutoLaunchLedgerKey = new Map<string, string>();
480
+ const AUTO_LAUNCH_LEDGER_DEDUP_MAX = 2000;
481
+
482
+ function sweepExpiredCooldowns(): void {
483
+ const now = Date.now();
484
+ for (const [key, until] of autoLaunchCooldownUntil) {
485
+ if (now >= until) autoLaunchCooldownUntil.delete(key);
486
+ }
487
+ }
488
+
489
+ function normalizeProviderPriority(policy: unknown): string[] {
490
+ const raw = policy && typeof policy === 'object' && !Array.isArray(policy)
491
+ ? (policy as Record<string, unknown>).providerPriority
492
+ : undefined;
493
+ if (!Array.isArray(raw)) return [];
494
+ const seen = new Set<string>();
495
+ return raw
496
+ .map(type => typeof type === 'string' ? type.trim() : '')
497
+ .filter(Boolean)
498
+ .filter(type => {
499
+ if (seen.has(type)) return false;
500
+ seen.add(type);
501
+ return true;
502
+ });
503
+ }
504
+
505
+ function isTerminalSessionStatus(status: string): boolean {
506
+ return ['stopped', 'failed', 'terminated', 'exited', 'closed'].includes(status);
507
+ }
508
+
509
+ function isIdleSessionState(state: any): boolean {
510
+ const status = readNonEmptyString(state?.status).toLowerCase();
511
+ if (isTerminalSessionStatus(status)) return false;
512
+ return status === 'idle' || state?.activeChat?.status === 'waiting_input';
513
+ }
514
+
515
+ function isDirtyNode(node: any): boolean {
516
+ return node?.health === 'dirty' || node?.git?.dirty === true;
517
+ }
518
+
519
+ function resolveAutoFastForwardPolicy(mesh: any): { enabled: boolean; maxBehind?: number; requireCleanSubmodules: boolean } {
520
+ const record = mesh?.policy?.autoFastForward && typeof mesh.policy.autoFastForward === 'object' && !Array.isArray(mesh.policy.autoFastForward)
521
+ ? mesh.policy.autoFastForward as Record<string, unknown>
522
+ : {};
523
+ const maxBehind = Number(record.maxBehind);
524
+ return {
525
+ enabled: record.enabled !== false,
526
+ ...(Number.isFinite(maxBehind) && maxBehind >= 0 ? { maxBehind: Math.floor(maxBehind) } : {}),
527
+ requireCleanSubmodules: record.requireCleanSubmodules !== false,
528
+ };
529
+ }
530
+
531
+ function sessionStateLooksActive(state: any): boolean {
532
+ const status = readNonEmptyString(state?.status).toLowerCase();
533
+ const chatStatus = readNonEmptyString(state?.activeChat?.status).toLowerCase();
534
+ // 'long_generating' is retained as a legacy alias for the renamed 'no_progress' busy status.
535
+ const active = new Set(['generating', 'streaming', 'no_progress', 'long_generating', 'working', 'starting', 'waiting_approval']);
536
+ return active.has(status) || active.has(chatStatus);
537
+ }
538
+
539
+ function nodeHasActiveMeshWork(components: DaemonComponents, meshId: string, nodeId: string, currentSessionId?: string): boolean {
540
+ if (nodeHasActiveAssignment(meshId, nodeId)) return true;
541
+ return components.instanceManager.getByCategory('cli').some((inst: any) => {
542
+ const state = inst.getState();
543
+ const settings = state.settings as Record<string, unknown> || {};
544
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
545
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
546
+ if (instNodeId !== nodeId) return false;
547
+ const sessionId = readNonEmptyString(state.instanceId);
548
+ if (currentSessionId && sessionId === currentSessionId && isIdleSessionState(state)) return false;
549
+ return sessionStateLooksActive(state);
550
+ });
551
+ }
552
+
553
+ function isLaunchableNode(node: any): boolean {
554
+ if (!node || node.status === 'disabled' || node.status === 'removed') return false;
555
+ const health = readNonEmptyString(node.health).toLowerCase();
556
+ if (!health) return true;
557
+ return health === 'online' || health === 'unknown';
558
+ }
559
+
560
+ /** Whether a mesh node's daemon/machine identity resolves to THIS coordinator daemon
561
+ * (i.e. the queue session can be spawned by a direct local `launch_cli`). */
562
+ function isLocalAutoLaunchNode(node: any): boolean {
563
+ const daemonId = readNonEmptyString(node?.daemonId);
564
+ const machineId = readNonEmptyString(node?.machineId);
565
+ const appConfig = loadConfig();
566
+ const localMachineId = readNonEmptyString(appConfig.machineId) || readNonEmptyString(appConfig.registeredMachineId);
567
+ const cloudDaemonId = localMachineId ? `daemon_${localMachineId}` : '';
568
+ const standaloneDaemonId = localMachineId ? `standalone_${localMachineId}` : '';
569
+
570
+ const daemonMatchesLocal = !daemonId || daemonId === cloudDaemonId || daemonId === standaloneDaemonId;
571
+ const machineMatchesLocal = !machineId || (!!localMachineId && machineId === localMachineId);
572
+
573
+ if (node?.isLocalWorktree === true) {
574
+ return daemonMatchesLocal && machineMatchesLocal;
575
+ }
576
+ if (daemonId || machineId) {
577
+ return daemonMatchesLocal && machineMatchesLocal;
578
+ }
579
+ return true;
580
+ }
581
+
582
+ /**
583
+ * Resolve how a pending queue task should be auto-launched onto a node.
584
+ *
585
+ * - `local`: spawn directly on this daemon via cliManager.handleCliCommand('launch_cli').
586
+ * - `remote`: forward `launch_cli` to the node's daemon via dispatchMeshCommand
587
+ * (mirrors what mesh_launch_session does). Requires dispatchMeshCommand AND a
588
+ * resolvable coordinator daemonId for relay-safe completion routing.
589
+ * - `skip`: not launchable from here — carries the reason (e.g. a remote node with
590
+ * no dispatch transport, or no coordinator daemonId to stamp).
591
+ */
592
+ function resolveAutoLaunchTarget(components: DaemonComponents, node: any): {
593
+ mode: 'local' | 'remote' | 'skip';
594
+ reason?: string;
595
+ daemonId?: string;
596
+ coordinatorDaemonId?: string;
597
+ } {
598
+ if (isLocalAutoLaunchNode(node)) return { mode: 'local' };
599
+
600
+ // Remote node. Forwarding the launch is possible only with a dispatch transport
601
+ // (cloud mode) plus a coordinator daemonId to stamp into the worker so completion
602
+ // events route back here. Without either, fall back to a graceful skip.
603
+ const daemonId = readNonEmptyString(node?.daemonId);
604
+ if (!daemonId) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
605
+ if (!components.dispatchMeshCommand) return { mode: 'skip', reason: 'remote_auto_launch_unsupported' };
606
+ const coordinatorDaemonId = readNonEmptyString(loadConfig().machineId);
607
+ if (!coordinatorDaemonId) return { mode: 'skip', reason: 'remote_auto_launch_no_coordinator_daemon_id' };
608
+ return { mode: 'remote', daemonId, coordinatorDaemonId };
609
+ }
610
+
611
+ function activeAssignedCount(meshId: string): number {
612
+ return getQueue(meshId, { status: ['assigned'] as any }).length;
613
+ }
614
+
615
+ /** Active assignments that hold the one-active-per-node / global-parallel invariant
616
+ * (everything except read-only diagnoses, which run unbounded by the write cap). */
617
+ export function activeWriteAssignedCount(meshId: string): number {
618
+ return getQueue(meshId, { status: ['assigned'] as any })
619
+ .filter(task => task.taskMode !== 'live_debug_readonly').length;
620
+ }
621
+
622
+ /** Active read-only (live_debug_readonly) assignments, for the read-only safety cap. */
623
+ export function activeReadonlyAssignedCount(meshId: string): number {
624
+ return getQueue(meshId, { status: ['assigned'] as any })
625
+ .filter(task => task.taskMode === 'live_debug_readonly').length;
626
+ }
627
+
628
+ function nodeHasActiveAssignment(meshId: string, nodeId: string): boolean {
629
+ return getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedNodeId === nodeId);
630
+ }
631
+
632
+ /** Active (status='assigned') task count for a node — the load metric for
633
+ * least-loaded / round-robin ranking. Lower = preferred. */
634
+ function nodeActiveLoad(meshId: string, nodeId: string): number {
635
+ return MeshRuntimeStore.getInstance().nodeActiveAssignmentCount(meshId, nodeId);
636
+ }
637
+
638
+ /**
639
+ * The mesh-wide scheduling strategy. Defaults to 'first_eligible' (strict
640
+ * no-change) for any mesh that does not set it. Only governs the final tie-break;
641
+ * eligibility, capacity, and priority gates apply identically to every strategy.
642
+ */
643
+ function resolveSchedulingStrategy(mesh: any): RepoMeshSchedulingStrategy {
644
+ return normalizeMeshSchedulingStrategy(mesh?.policy?.schedulingStrategy);
645
+ }
646
+
647
+ /**
648
+ * Order eligible nodes for assignment per the mesh scheduling pipeline:
649
+ * PRIORITY (schedulingPriority desc) → TIE-BREAK (strategy).
650
+ *
651
+ * The caller has already applied the TAG hard-filter and is responsible for the
652
+ * MAX-ALLOC capacity gate (the per-node launch/claim checks). This function only
653
+ * decides the *preference order* among nodes that are otherwise eligible.
654
+ *
655
+ * - 'first_eligible' (default): returns the input order verbatim and does NOT touch
656
+ * the round-robin cursor — byte-for-byte the pre-feature behavior.
657
+ * - 'priority_only': schedulingPriority desc, then input order (load ignored).
658
+ * - 'least_loaded': schedulingPriority desc, then active load asc, then input order.
659
+ * - 'round_robin': same as least_loaded, but among nodes tied at (priority, load)
660
+ * the input order is rotated by a per-mesh cursor that advances once per pass.
661
+ *
662
+ * `nodes` carries the original config/array index so the tie-break can fall back to
663
+ * deterministic input order. `bumpCursor` advances the round-robin cursor exactly
664
+ * once per scheduling pass (only consulted for 'round_robin').
665
+ */
666
+ interface RankableNode { nodeId: string; node: any; index: number }
667
+
668
+ /** Test-only: the pure node-ordering stage (PRIORITY → TIE-BREAK). Exposed so the
669
+ * scheduling pipeline can be unit-tested without standing up live CLI sessions. */
670
+ export function __orderEligibleNodesForTests(
671
+ meshId: string,
672
+ strategy: RepoMeshSchedulingStrategy,
673
+ nodes: RankableNode[],
674
+ opts?: { bumpCursor?: boolean },
675
+ ): RankableNode[] {
676
+ return orderEligibleNodes(meshId, strategy, nodes, opts);
677
+ }
678
+
679
+ function orderEligibleNodes(
680
+ meshId: string,
681
+ strategy: RepoMeshSchedulingStrategy,
682
+ nodes: RankableNode[],
683
+ opts?: { bumpCursor?: boolean },
684
+ ): RankableNode[] {
685
+ if (strategy === 'first_eligible' || nodes.length <= 1) {
686
+ return nodes;
687
+ }
688
+
689
+ const priorityOf = (n: { node: any }) => resolveNodeSchedulingPriority(n.node?.policy);
690
+
691
+ // Round-robin rotation offset: rotate the deterministic input order by a
692
+ // per-mesh cursor so the tie-break winner among equal (priority, load) nodes
693
+ // cycles across passes. The cursor advances once per scheduling pass.
694
+ let rotation = 0;
695
+ if (strategy === 'round_robin') {
696
+ const cursor = opts?.bumpCursor
697
+ ? MeshRuntimeStore.getInstance().bumpSchedulerCursor(meshId)
698
+ : MeshRuntimeStore.getInstance().getSchedulerCursor(meshId);
699
+ rotation = ((cursor % nodes.length) + nodes.length) % nodes.length;
700
+ }
701
+
702
+ // Rotation rank: position of each node after rotating input order by `rotation`.
703
+ // For non-round-robin strategies rotation is 0, so this is just the input index.
704
+ const rotationRank = (index: number) => (index - rotation + nodes.length) % nodes.length;
705
+
706
+ return [...nodes].sort((a, b) => {
707
+ const prioDelta = priorityOf(b) - priorityOf(a); // higher priority first
708
+ if (prioDelta !== 0) return prioDelta;
709
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
710
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
711
+ if (loadDelta !== 0) return loadDelta;
712
+ }
713
+ return rotationRank(a.index) - rotationRank(b.index);
714
+ });
715
+ }
716
+
717
+ /** Active assignments on a (node, provider) — pre-launch guard for the per-(node,
718
+ * provider) maxParallel cap. The authoritative enforcement is in the claim
719
+ * transaction; this only avoids spawning a session that would fail the claim. */
720
+ function activeProviderAssignedCount(meshId: string, nodeId: string, providerType: string): number {
721
+ return getQueue(meshId, { status: ['assigned'] as any })
722
+ .filter(task => task.assignedNodeId === nodeId && task.assignedProviderType === providerType).length;
723
+ }
724
+
725
+ function sessionHasActiveAssignment(meshId: string, sessionId: string): boolean {
726
+ if (getQueue(meshId, { status: ['assigned'] as any }).some(task => task.assignedSessionId === sessionId)) {
727
+ return true;
728
+ }
729
+ // Direct dispatches (mesh_send_task) are tracked in mesh_direct_dispatches, not the
730
+ // work queue. A session completing a still-active direct dispatch IS an active
731
+ // assignment — without this, findRecentTerminalLedgerEvidence dedup wrongly suppresses
732
+ // the canonical agent:generating_completed for direct-dispatch tasks (validation/general),
733
+ // so the coordinator polling get_pending_mesh_events never observes task_completed and the
734
+ // session goes silently idle. This check runs before markSessionTerminal marks the
735
+ // dispatch terminal, so the in-flight dispatch is still observable here.
736
+ try {
737
+ if (getActiveDirectDispatches(meshId).some(d => d.sessionId === sessionId)) return true;
738
+ if (hasUnterminalDirectDispatchLedgerEntry(meshId, sessionId)) return true;
739
+ } catch { /* best-effort — fall through to false */ }
740
+ return false;
741
+ }
742
+
743
+ function liveSessionCountForNode(components: DaemonComponents, meshId: string, nodeId: string): number {
744
+ return components.instanceManager.getByCategory('cli').filter((inst: any) => {
745
+ const state = inst.getState();
746
+ const settings = state.settings as Record<string, unknown> || {};
747
+ if (readNonEmptyString(settings.meshNodeFor) !== meshId) return false;
748
+ const instNodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
749
+ if (instNodeId !== nodeId) return false;
750
+ const status = readNonEmptyString(state.status).toLowerCase();
751
+ return !isTerminalSessionStatus(status);
752
+ }).length;
753
+ }
754
+
755
+ function recordAutoLaunchEvent(meshId: string, args: {
756
+ phase: 'skipped' | 'started' | 'failed' | 'completed';
757
+ taskId: string;
758
+ nodeId?: string;
759
+ providerType?: string;
760
+ sessionId?: string;
761
+ reason?: string;
762
+ error?: string;
763
+ }) {
764
+ // Suppress consecutive identical `skipped` entries for the same task (4s reconcile
765
+ // re-trigger noise). Non-skip phases and changed reasons always record and reset
766
+ // the de-dup so genuine state transitions remain visible in the ledger.
767
+ const dedupKey = `${meshId}:${args.taskId}`;
768
+ const currentSig = `${args.phase}|${args.reason || ''}`;
769
+ if (args.phase === 'skipped' && lastAutoLaunchLedgerKey.get(dedupKey) === currentSig) {
770
+ return;
771
+ }
772
+ lastAutoLaunchLedgerKey.set(dedupKey, currentSig);
773
+ if (lastAutoLaunchLedgerKey.size > AUTO_LAUNCH_LEDGER_DEDUP_MAX) {
774
+ // Bound memory: drop the oldest insertion (Map preserves insertion order).
775
+ const oldest = lastAutoLaunchLedgerKey.keys().next().value;
776
+ if (oldest !== undefined) lastAutoLaunchLedgerKey.delete(oldest);
777
+ }
778
+ try {
779
+ appendLedgerEntry(meshId, {
780
+ kind: 'session_auto_launch',
781
+ nodeId: args.nodeId,
782
+ sessionId: args.sessionId,
783
+ providerType: args.providerType,
784
+ payload: {
785
+ phase: args.phase,
786
+ taskId: args.taskId,
787
+ reason: args.reason,
788
+ error: args.error,
789
+ },
790
+ });
791
+ } catch (e: any) {
792
+ LOG.warn('MeshQueue', `Failed to record auto-launch ledger event: ${e?.message || e}`);
793
+ }
794
+ }
795
+
796
+ function markAutoLaunch(meshId: string, taskId: string, args: {
797
+ status: 'skipped' | 'started' | 'failed' | 'completed';
798
+ reason?: string;
799
+ nodeId?: string;
800
+ providerType?: string;
801
+ sessionId?: string;
802
+ error?: string;
803
+ }) {
804
+ recordTaskAutoLaunch(meshId, taskId, {
805
+ status: args.status,
806
+ reason: args.reason || args.error,
807
+ nodeId: args.nodeId,
808
+ providerType: args.providerType,
809
+ sessionId: args.sessionId,
810
+ });
811
+ recordAutoLaunchEvent(meshId, {
812
+ phase: args.status,
813
+ taskId,
814
+ nodeId: args.nodeId,
815
+ providerType: args.providerType,
816
+ sessionId: args.sessionId,
817
+ reason: args.reason,
818
+ error: args.error,
819
+ });
820
+ }
821
+
822
+ async function resolveUsableProvider(
823
+ components: DaemonComponents,
824
+ nodeId: string,
825
+ node: any,
826
+ requiredTags?: string[],
827
+ ): Promise<{ providerType?: string; reason?: string }> {
828
+ const providerPriority = normalizeProviderPriority(node?.policy);
829
+ if (!providerPriority.length) return { reason: 'missing_provider_priority' };
830
+ const providerLoader = components.providerLoader;
831
+ if (!providerLoader) return { reason: 'provider_loader_unavailable' };
832
+
833
+ const failed: string[] = [];
834
+ for (const requestedType of providerPriority) {
835
+ const normalizedType = typeof providerLoader.resolveAlias === 'function'
836
+ ? providerLoader.resolveAlias(requestedType)
837
+ : requestedType;
838
+ // Skip providers that can't satisfy the task's requiredTags (e.g. provider=hermes-cli
839
+ // means only hermes-cli qualifies, not any other type in providerPriority).
840
+ if (requiredTags?.length && !nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, normalizedType))) {
841
+ failed.push(`${requestedType}: required_tags_mismatch`);
842
+ continue;
843
+ }
844
+ if (typeof providerLoader.isMachineProviderEnabled === 'function' && !providerLoader.isMachineProviderEnabled(normalizedType)) {
845
+ failed.push(`${requestedType}: disabled`);
846
+ continue;
847
+ }
848
+ let detected: any;
849
+ try {
850
+ detected = await detectCLI(normalizedType, providerLoader, { includeVersion: false });
851
+ } catch (e: any) {
852
+ failed.push(`${requestedType}: detect failed: ${e?.message || e}`);
853
+ continue;
854
+ }
855
+ if (typeof providerLoader.setCliDetectionResults === 'function') {
856
+ providerLoader.setCliDetectionResults([{
857
+ id: normalizedType,
858
+ installed: !!detected,
859
+ path: detected?.path,
860
+ }], false);
861
+ }
862
+ (components as any).onStatusChange?.();
863
+ if (detected) return { providerType: normalizedType };
864
+ failed.push(`${requestedType}: not detected`);
865
+ }
866
+ return { reason: `provider_priority_unusable: ${failed.join('; ') || nodeId}` };
867
+ }
868
+
869
+ // Canonical mesh node-id normalization. A node may arrive from the local config
870
+ // form (`id`) or the inline-cache form (`nodeId`/`node_id`) — see
871
+ // readInlineMeshNodeId in commands/router.ts. Comparing only `node.id` against a
872
+ // task.targetNodeId silently drops inline-cached worktree nodes, leaving a
873
+ // target-routed task permanently pending with a misleading
874
+ // `no_node_satisfies_required_tags` skip.
875
+ function readMeshNodeId(node: any): string {
876
+ // Delegate to the shared 3-way (id / nodeId / node_id) normalizer so this
877
+ // and every other mesh node-id read agree on identity. Coalesce to '' to
878
+ // preserve the existing string return contract for callers that do
879
+ // `=== task.targetNodeId` / `if (!nodeId)`.
880
+ return normalizeMeshNodeId(node) ?? '';
881
+ }
882
+
883
+ async function maybeAutoLaunchOneQueueSession(components: DaemonComponents, meshId: string, mesh: any): Promise<boolean> {
884
+ const queue = getQueue(meshId);
885
+ const pending = queue.filter(task => task.status === 'pending');
886
+ if (!pending.length) return false;
887
+
888
+ const maxParallelTasks = Math.max(1, Math.floor(Number(mesh?.policy?.maxParallelTasks) || 2));
889
+ // Read-only diagnoses carry no isolation/merge cost, so they are exempt from the
890
+ // write-task parallel cap. To prevent runaway auto-launch they get their own,
891
+ // higher safety cap (2x the write cap).
892
+ const maxReadonlyParallelTasks = Math.max(2, maxParallelTasks * 2);
893
+ for (const task of pending) {
894
+ const isReadonly = task.taskMode === 'live_debug_readonly';
895
+ if (isReadonly) {
896
+ if (activeReadonlyAssignedCount(meshId) >= maxReadonlyParallelTasks) {
897
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_readonly_parallel_tasks_reached' });
898
+ continue;
899
+ }
900
+ } else if (activeWriteAssignedCount(meshId) >= maxParallelTasks) {
901
+ // Write tasks are capped; skip this one but keep scanning so a later
902
+ // read-only task in the queue can still launch under its own cap.
903
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_parallel_tasks_reached' });
904
+ continue;
905
+ }
906
+ if (task.targetSessionId) {
907
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'target_session_constraint' });
908
+ continue;
909
+ }
910
+
911
+ // Per-task await-claim guard. A prior auto-launch already spawned a session for
912
+ // this task and we are waiting for that session's idle→claim to land (remote
913
+ // claims arrive via the worker→coordinator agent:ready pull, which can lag well
914
+ // past the per-node cooldown). Re-launching now would spawn a duplicate orphan
915
+ // session that never gets work. The task leaves `pending` the instant the claim
916
+ // succeeds, so this guard only suppresses the in-flight window; if the launched
917
+ // session never reaches idle within the window, a later tick retries.
918
+ if (task.autoLaunch?.status === 'completed' && task.autoLaunch.sessionId) {
919
+ const launchedAtMs = Date.parse(task.autoLaunch.updatedAt);
920
+ if (Number.isFinite(launchedAtMs) && Date.now() - launchedAtMs < AUTO_LAUNCH_AWAIT_CLAIM_MS) {
921
+ // Record the skip in the ledger ONLY (dedup'd). Do NOT call markAutoLaunch
922
+ // here: recordTaskAutoLaunch overwrites task.autoLaunch wholesale, which would
923
+ // erase the very `completed` record (status + sessionId + updatedAt) this guard
924
+ // reads on the next tick, reopening the duplicate-launch hole it closes.
925
+ recordAutoLaunchEvent(meshId, { phase: 'skipped', taskId: task.id, reason: 'awaiting_launched_session_claim', nodeId: task.autoLaunch.nodeId, sessionId: task.autoLaunch.sessionId });
926
+ continue;
927
+ }
928
+ }
929
+
930
+ const candidateNodes = Array.isArray(mesh?.nodes)
931
+ ? mesh.nodes.filter((node: any) => {
932
+ if (task.targetNodeId && readMeshNodeId(node) !== task.targetNodeId) return false;
933
+ // Skip nodes that can never satisfy requiredTags regardless of which provider
934
+ // from providerPriority is selected. A node satisfies tags if at least one
935
+ // provider in its priority list would produce matching capability tags.
936
+ if (task.requiredTags?.length) {
937
+ const priorities = normalizeProviderPriority(node?.policy);
938
+ const providerCandidates = priorities.length ? priorities : [undefined as unknown as string];
939
+ return providerCandidates.some(p =>
940
+ nodeSatisfiesRequiredTags(task.requiredTags, buildMeshNodeCapabilityTags(node, p))
941
+ );
942
+ }
943
+ return true;
944
+ })
945
+ : [];
946
+ if (!candidateNodes.length) {
947
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'no_node_satisfies_required_tags', nodeId: task.targetNodeId });
948
+ continue;
949
+ }
950
+
951
+ // PRIORITY → TIE-BREAK: order the eligible (TAG-filtered) candidate nodes by
952
+ // the mesh scheduling strategy. 'first_eligible' (default) returns them in
953
+ // config/array order unchanged, so distribution is strictly opt-in. The
954
+ // per-node MAX-ALLOC capacity gate (nodeHasActiveAssignment, provider cap,
955
+ // maxConcurrentSessions) is still applied inside the loop below; this only
956
+ // chooses which eligible node is *tried first*.
957
+ const strategy = resolveSchedulingStrategy(mesh);
958
+ const orderedCandidateNodes = strategy === 'first_eligible'
959
+ ? candidateNodes
960
+ : orderEligibleNodes(
961
+ meshId,
962
+ strategy,
963
+ candidateNodes
964
+ .map((node: any, index: number) => ({ nodeId: readMeshNodeId(node), node, index }))
965
+ .filter((c: RankableNode) => c.nodeId),
966
+ { bumpCursor: true },
967
+ ).map((c: RankableNode) => c.node);
968
+
969
+ for (const node of orderedCandidateNodes) {
970
+ const nodeId = readMeshNodeId(node);
971
+ if (!nodeId) continue;
972
+ const launchKey = `${meshId}:${nodeId}`;
973
+ const now = Date.now();
974
+ const cooldownUntil = autoLaunchCooldownUntil.get(launchKey) || 0;
975
+ if (cooldownUntil > 0 && now >= cooldownUntil) autoLaunchCooldownUntil.delete(launchKey);
976
+ if (autoLaunchInProgress.has(launchKey)) {
977
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_in_progress', nodeId });
978
+ continue;
979
+ }
980
+ if (now < cooldownUntil) {
981
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'auto_launch_cooldown', nodeId });
982
+ continue;
983
+ }
984
+ if (isDirtyNode(node)) {
985
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'dirty_workspace', nodeId });
986
+ continue;
987
+ }
988
+ if (!isLaunchableNode(node)) {
989
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_not_launch_ready', nodeId });
990
+ continue;
991
+ }
992
+ const launchTarget = resolveAutoLaunchTarget(components, node);
993
+ if (launchTarget.mode === 'skip') {
994
+ // Remote node we can't reach (no transport / no coordinator daemonId).
995
+ // Set a cooldown so the 4s reconcile loop doesn't re-attempt this node
996
+ // every tick; the de-dup'd skip ledger keeps it diagnosable without flood.
997
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: launchTarget.reason || 'auto_launch_unavailable', nodeId });
998
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
999
+ continue;
1000
+ }
1001
+ // Write tasks keep the one-active-per-node invariant (worktree isolation);
1002
+ // read-only (live_debug_readonly) diagnoses may auto-launch onto a node
1003
+ // that already has an active assignment.
1004
+ if (task.taskMode !== 'live_debug_readonly' && nodeHasActiveAssignment(meshId, nodeId)) {
1005
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'node_has_active_assignment', nodeId });
1006
+ continue;
1007
+ }
1008
+ const maxConcurrentSessions = Number(node?.policy?.maxConcurrentSessions);
1009
+ if (Number.isFinite(maxConcurrentSessions) && maxConcurrentSessions >= 0 && liveSessionCountForNode(components, meshId, nodeId) >= maxConcurrentSessions) {
1010
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_concurrent_sessions_reached', nodeId });
1011
+ continue;
1012
+ }
1013
+
1014
+ autoLaunchInProgress.add(launchKey);
1015
+ try {
1016
+ const resolved = await resolveUsableProvider(components, nodeId, node, task.requiredTags);
1017
+ if (!resolved.providerType) {
1018
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: resolved.reason || 'provider_unusable', nodeId });
1019
+ continue;
1020
+ }
1021
+
1022
+ // Don't spawn a session for a (node, provider) already at its declared
1023
+ // maxParallel cap — it would launch only to fail the claim. The claim
1024
+ // transaction enforces the cap regardless; this just avoids a doomed launch.
1025
+ const providerCap = resolveProviderMaxParallel(node?.policy, resolved.providerType);
1026
+ if (
1027
+ providerCap !== undefined
1028
+ && activeProviderAssignedCount(meshId, nodeId, resolved.providerType) >= providerCap
1029
+ ) {
1030
+ markAutoLaunch(meshId, task.id, { status: 'skipped', reason: 'max_provider_parallel_reached', nodeId, providerType: resolved.providerType });
1031
+ continue;
1032
+ }
1033
+
1034
+ // Shared worker-launch envelope. For a local node it spawns directly on this
1035
+ // daemon; for a remote node the identical command is forwarded to the node's
1036
+ // daemon (mirrors mesh_launch_session), with the coordinator daemonId stamped
1037
+ // so the worker's completion events route back to this coordinator.
1038
+ const launchSettings: Record<string, unknown> = {
1039
+ // Worker launch envelope: role + mesh context so worker can route completion events.
1040
+ role: 'worker',
1041
+ meshNodeFor: meshId,
1042
+ meshNodeId: nodeId,
1043
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1044
+ // Coordinator-dispatched worker: auto-approve unless mesh/node policy
1045
+ // opts out (default true). Lands in settingsOverride and beats the
1046
+ // global per-provider-type autoApprove config (see shouldAutoApprove).
1047
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1048
+ launchedByCoordinator: true,
1049
+ autoLaunchedForQueueTaskId: task.id,
1050
+ };
1051
+
1052
+ if (launchTarget.mode === 'remote') {
1053
+ // Relay-safe completion routing: stamp the coordinator anchor the same way
1054
+ // mesh_launch_session does so the worker forwards events back to this daemon.
1055
+ const remoteSettings: Record<string, unknown> = {
1056
+ ...launchSettings,
1057
+ meshCoordinatorDaemonId: launchTarget.coordinatorDaemonId,
1058
+ meshCoordinatorNodeId: nodeId,
1059
+ };
1060
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1061
+ let launchResult: any;
1062
+ try {
1063
+ launchResult = await components.dispatchMeshCommand!(launchTarget.daemonId!, 'launch_cli', {
1064
+ cliType: resolved.providerType,
1065
+ dir: node.workspace,
1066
+ settings: remoteSettings,
1067
+ });
1068
+ } catch (e: any) {
1069
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: `remote_launch_dispatch_failed: ${e?.message || String(e)}`, nodeId, providerType: resolved.providerType });
1070
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1071
+ return false;
1072
+ }
1073
+ const payload = (launchResult && typeof launchResult === 'object' && 'payload' in launchResult && launchResult.payload && typeof launchResult.payload === 'object')
1074
+ ? launchResult.payload
1075
+ : launchResult;
1076
+ if (!payload?.success) {
1077
+ const reason = readNonEmptyString(payload?.error) || 'remote_launch_cli_failed';
1078
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1079
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1080
+ return false;
1081
+ }
1082
+ // Remote launch is async: the worker session will register and emit agent:ready,
1083
+ // which (forwarded back here) drives the claim via the normal event path / PHASE 1
1084
+ // reconcile. Set a cooldown so the 4s loop doesn't re-launch before that lands.
1085
+ const remoteSessionId = readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.id) || readNonEmptyString(payload.runtimeSessionId);
1086
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId: remoteSessionId || undefined });
1087
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1088
+ return true;
1089
+ }
1090
+
1091
+ markAutoLaunch(meshId, task.id, { status: 'started', nodeId, providerType: resolved.providerType });
1092
+ const launchResult: any = await components.cliManager.handleCliCommand('launch_cli', {
1093
+ cliType: resolved.providerType,
1094
+ dir: node.workspace,
1095
+ settings: launchSettings,
1096
+ });
1097
+ if (!launchResult?.success) {
1098
+ const reason = launchResult?.error || 'launch_cli_failed';
1099
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason, nodeId, providerType: resolved.providerType });
1100
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1101
+ return false;
1102
+ }
1103
+ const sessionId = readNonEmptyString(launchResult.sessionId) || readNonEmptyString(launchResult.id) || readNonEmptyString(launchResult.runtimeSessionId);
1104
+ if (!sessionId) {
1105
+ markAutoLaunch(meshId, task.id, { status: 'failed', reason: 'launch_missing_session_id', nodeId, providerType: resolved.providerType });
1106
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS); sweepExpiredCooldowns();
1107
+ return false;
1108
+ }
1109
+ markAutoLaunch(meshId, task.id, { status: 'completed', nodeId, providerType: resolved.providerType, sessionId });
1110
+ tryAssignQueueTask(components, meshId, nodeId, sessionId, resolved.providerType);
1111
+ return true;
1112
+ } catch (e: any) {
1113
+ markAutoLaunch(meshId, task.id, { status: 'failed', error: e?.message || String(e), nodeId });
1114
+ autoLaunchCooldownUntil.set(launchKey, Date.now() + AUTO_LAUNCH_COOLDOWN_MS);
1115
+ return false;
1116
+ } finally {
1117
+ autoLaunchInProgress.delete(launchKey);
1118
+ }
1119
+ }
1120
+ }
1121
+ return false;
1122
+ }
1123
+
1124
+ export interface MeshQueueTriggerResult {
1125
+ success: true;
1126
+ meshId: string;
1127
+ pendingBefore: number;
1128
+ assignedBefore: number;
1129
+ pendingAfter: number;
1130
+ assignedAfter: number;
1131
+ claimed: boolean;
1132
+ newlyAssignedTasks: Array<{
1133
+ id: string;
1134
+ nodeId?: string;
1135
+ sessionId?: string;
1136
+ }>;
1137
+ localIdleSessionsChecked: number;
1138
+ remoteIdleSessionsChecked: number;
1139
+ skippedSessions: Array<{
1140
+ nodeId?: string;
1141
+ sessionId?: string;
1142
+ reason: string;
1143
+ status?: string;
1144
+ }>;
1145
+ autoLaunchStarted: boolean;
1146
+ noIdleMeshSessionAvailable?: boolean;
1147
+ }
1148
+
1149
+ function countQueueStatus(meshId: string, status: 'pending' | 'assigned'): number {
1150
+ return getQueue(meshId, { status: [status] as any }).length;
1151
+ }
1152
+
1153
+ function getQueueStatusById(meshId: string): Map<string, string> {
1154
+ return new Map(getQueue(meshId).map(task => [task.id, task.status]));
1155
+ }
1156
+
1157
+ export async function triggerMeshQueue(components: DaemonComponents, meshId: string): Promise<MeshQueueTriggerResult> {
1158
+ const mesh = getMeshWithCache(components, meshId);
1159
+ const pendingBefore = countQueueStatus(meshId, 'pending');
1160
+ const assignedBefore = countQueueStatus(meshId, 'assigned');
1161
+ const beforeStatus = getQueueStatusById(meshId);
1162
+ const skippedSessions: MeshQueueTriggerResult['skippedSessions'] = [];
1163
+ let localIdleSessionsChecked = 0;
1164
+ let remoteIdleSessionsChecked = 0;
1165
+ let autoLaunchStarted = false;
1166
+ if (!mesh) {
1167
+ return {
1168
+ success: true,
1169
+ meshId,
1170
+ pendingBefore,
1171
+ assignedBefore,
1172
+ pendingAfter: pendingBefore,
1173
+ assignedAfter: assignedBefore,
1174
+ claimed: false,
1175
+ newlyAssignedTasks: [],
1176
+ localIdleSessionsChecked,
1177
+ remoteIdleSessionsChecked,
1178
+ skippedSessions: [{ reason: 'mesh_not_found' }],
1179
+ autoLaunchStarted,
1180
+ noIdleMeshSessionAvailable: true,
1181
+ };
1182
+ }
1183
+
1184
+ // Collect every idle mesh session (local CLI instances + remote idle records)
1185
+ // as drain candidates. The drain ORDER depends on the scheduling strategy:
1186
+ // - 'first_eligible' (default): local-first, then remote, exactly as before.
1187
+ // - otherwise: local + remote merged into one pool and drained in scheduling
1188
+ // order (priority → load → tie-break). This local-first debias is required
1189
+ // because without it the coordinator's own local node is always visited
1190
+ // first and greedily absorbs all untargeted work before any remote idle
1191
+ // session is even considered — the comparator alone can't spread work if
1192
+ // local is always tried first.
1193
+ type IdleCandidate = { nodeId: string; sessionId: string; providerType: string; origin: 'local' | 'remote'; node: any };
1194
+ const strategy = resolveSchedulingStrategy(mesh);
1195
+ const localCandidates: IdleCandidate[] = [];
1196
+
1197
+ const cliInstances = components.instanceManager.getByCategory('cli');
1198
+ for (const inst of cliInstances) {
1199
+ const state = inst.getState();
1200
+ const settings = state.settings as Record<string, unknown> || {};
1201
+
1202
+ const instMeshId = readNonEmptyString(settings.meshNodeFor);
1203
+ if (instMeshId !== meshId) continue;
1204
+
1205
+ const nodeId = readNonEmptyString(settings.meshNodeId) || readNonEmptyString(settings.nodeId);
1206
+ if (!nodeId) continue;
1207
+
1208
+ if (!isIdleSessionState(state)) {
1209
+ const status = readNonEmptyString(state.status).toLowerCase();
1210
+ skippedSessions.push({
1211
+ nodeId,
1212
+ sessionId: readNonEmptyString(state.instanceId),
1213
+ reason: isTerminalSessionStatus(status) ? 'terminal_session' : 'session_not_idle',
1214
+ status: status || undefined,
1215
+ });
1216
+ continue;
1217
+ }
1218
+
1219
+ const sessionId = state.instanceId;
1220
+ const providerType = state.type || readNonEmptyString(settings.providerType);
1221
+
1222
+ if (providerType) {
1223
+ localIdleSessionsChecked += 1;
1224
+ localCandidates.push({ nodeId, sessionId, providerType, origin: 'local', node: mesh.nodes.find((n: any) => readMeshNodeId(n) === nodeId) });
1225
+ } else {
1226
+ skippedSessions.push({
1227
+ nodeId,
1228
+ sessionId,
1229
+ reason: 'provider_type_missing',
1230
+ });
1231
+ }
1232
+ }
1233
+
1234
+ let remoteSessions: Array<{ nodeId: string; sessionId: string; providerType: string }> = [];
1235
+ try {
1236
+ remoteSessions = MeshRuntimeStore.getInstance().getRemoteIdleSessions();
1237
+ } catch { /* best-effort */ }
1238
+
1239
+ const remoteCandidates: IdleCandidate[] = [];
1240
+ for (const idle of remoteSessions) {
1241
+ // Match with the shared 3-form normalizer (id / nodeId / node_id), not raw
1242
+ // `n.id`, so an inline-cached worktree node whose identity arrived under a
1243
+ // different form is not silently dropped — leaving a remote idle session
1244
+ // unable to claim its pending queue task.
1245
+ const node = mesh.nodes.find((n: any) => meshNodeIdMatches(n, idle.nodeId));
1246
+ if (node) {
1247
+ remoteIdleSessionsChecked += 1;
1248
+ remoteCandidates.push({ nodeId: idle.nodeId, sessionId: idle.sessionId, providerType: idle.providerType, origin: 'remote', node });
1249
+ }
1250
+ }
1251
+
1252
+ const assignIdleCandidate = (candidate: IdleCandidate): void => {
1253
+ const assigned = tryAssignQueueTask(components, meshId, candidate.nodeId, candidate.sessionId, candidate.providerType);
1254
+ if (assigned && candidate.origin === 'remote') {
1255
+ try {
1256
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(candidate.nodeId, candidate.sessionId);
1257
+ } catch { /* best-effort */ }
1258
+ }
1259
+ };
1260
+
1261
+ if (strategy === 'first_eligible') {
1262
+ // Strict no-change: drain local idle sessions first (original order), then
1263
+ // remote idle sessions. tryAssignQueueTask is a no-op when nothing matches.
1264
+ for (const candidate of localCandidates) assignIdleCandidate(candidate);
1265
+ for (const candidate of remoteCandidates) assignIdleCandidate(candidate);
1266
+ } else {
1267
+ // Merge local + remote into one pool and drain in scheduling order. Each
1268
+ // assignment mutates a node's active load, and the next pick re-reads it,
1269
+ // so re-ranking after every assignment keeps the spread fair as load shifts.
1270
+ const pool = [...localCandidates, ...remoteCandidates];
1271
+ const baseIndex = new Map<string, number>();
1272
+ pool.forEach((c, i) => { if (!baseIndex.has(c.nodeId)) baseIndex.set(c.nodeId, i); });
1273
+ // Bump the round-robin cursor once for this whole drain pass.
1274
+ const uniqueNodes = [...new Set(pool.map(c => c.nodeId))]
1275
+ .map((nodeId, index) => ({ nodeId, node: pool.find(c => c.nodeId === nodeId)?.node, index }));
1276
+ const ranked = orderEligibleNodes(meshId, strategy, uniqueNodes, { bumpCursor: true });
1277
+ const rankIndex = new Map<string, number>(ranked.map((r, i) => [r.nodeId, i]));
1278
+ const remaining = [...pool];
1279
+ while (remaining.length > 0) {
1280
+ // Re-rank each pass so a node that just took work defers its next session.
1281
+ remaining.sort((a, b) => {
1282
+ const aPrio = resolveNodeSchedulingPriority(a.node?.policy);
1283
+ const bPrio = resolveNodeSchedulingPriority(b.node?.policy);
1284
+ if (aPrio !== bPrio) return bPrio - aPrio;
1285
+ if (strategy === 'least_loaded' || strategy === 'round_robin') {
1286
+ const loadDelta = nodeActiveLoad(meshId, a.nodeId) - nodeActiveLoad(meshId, b.nodeId);
1287
+ if (loadDelta !== 0) return loadDelta;
1288
+ }
1289
+ return (rankIndex.get(a.nodeId) ?? 0) - (rankIndex.get(b.nodeId) ?? 0);
1290
+ });
1291
+ assignIdleCandidate(remaining.shift()!);
1292
+ }
1293
+ }
1294
+
1295
+ autoLaunchStarted = await maybeAutoLaunchOneQueueSession(components, meshId, mesh);
1296
+ const afterQueue = getQueue(meshId);
1297
+ const pendingAfter = afterQueue.filter(task => task.status === 'pending').length;
1298
+ const assignedAfter = afterQueue.filter(task => task.status === 'assigned').length;
1299
+ const newlyAssignedTasks = afterQueue
1300
+ .filter(task => task.status === 'assigned' && beforeStatus.get(task.id) !== 'assigned')
1301
+ .map(task => ({
1302
+ id: task.id,
1303
+ nodeId: task.assignedNodeId,
1304
+ sessionId: task.assignedSessionId,
1305
+ }));
1306
+ return {
1307
+ success: true,
1308
+ meshId,
1309
+ pendingBefore,
1310
+ assignedBefore,
1311
+ pendingAfter,
1312
+ assignedAfter,
1313
+ claimed: newlyAssignedTasks.length > 0,
1314
+ newlyAssignedTasks,
1315
+ localIdleSessionsChecked,
1316
+ remoteIdleSessionsChecked,
1317
+ skippedSessions,
1318
+ autoLaunchStarted,
1319
+ ...(pendingAfter > 0 && newlyAssignedTasks.length === 0 && localIdleSessionsChecked === 0 && remoteIdleSessionsChecked === 0 && !autoLaunchStarted
1320
+ ? { noIdleMeshSessionAvailable: true }
1321
+ : {}),
1322
+ };
1323
+ }
1324
+
1325
+ async function maybeAutoFastForwardIdleNode(components: DaemonComponents, args: {
1326
+ meshId: string;
1327
+ nodeId: string;
1328
+ sessionId?: string;
1329
+ providerType?: string;
1330
+ }): Promise<void> {
1331
+ const mesh = getMeshWithCache(components, args.meshId);
1332
+ const node = mesh?.nodes?.find((candidate: any) => meshNodeIdMatches(candidate, args.nodeId));
1333
+ const workspace = readNonEmptyString(node?.workspace);
1334
+ if (!workspace) return;
1335
+ if (!existsSync(workspace)) return;
1336
+
1337
+ const policy = resolveAutoFastForwardPolicy(mesh);
1338
+ if (!policy.enabled) return;
1339
+ if (nodeHasActiveMeshWork(components, args.meshId, args.nodeId, args.sessionId)) return;
1340
+
1341
+ const throttleKey = `${args.meshId}:${args.nodeId}`;
1342
+ const now = Date.now();
1343
+ const lastAttempt = idleAutoFastForwardLastAttempt.get(throttleKey) || 0;
1344
+ if (now - lastAttempt < IDLE_AUTO_FAST_FORWARD_THROTTLE_MS) return;
1345
+ idleAutoFastForwardLastAttempt.set(throttleKey, now);
1346
+
1347
+ const submoduleIgnorePaths = Array.isArray(node?.policy?.submoduleIgnorePaths)
1348
+ ? node.policy.submoduleIgnorePaths.filter((value: unknown): value is string => typeof value === 'string')
1349
+ : undefined;
1350
+ try {
1351
+ const dryRun = await fastForwardMeshNode({
1352
+ meshId: args.meshId,
1353
+ nodeId: args.nodeId,
1354
+ workspace,
1355
+ execute: false,
1356
+ dryRun: true,
1357
+ updateSubmodules: false,
1358
+ submoduleIgnorePaths,
1359
+ trigger: 'idle_auto',
1360
+ });
1361
+ if (!dryRun || dryRun.code !== 'fast_forward_available' || dryRun.allowed !== true) return;
1362
+ const behind = Number(dryRun.current?.behind);
1363
+ if (policy.maxBehind !== undefined && Number.isFinite(behind) && behind > policy.maxBehind) return;
1364
+ if (policy.requireCleanSubmodules) {
1365
+ const submodules = Array.isArray(dryRun.current?.submodules) ? dryRun.current.submodules : [];
1366
+ if (submodules.some((submodule: any) => submodule?.dirty || submodule?.outOfSync || submodule?.error)) return;
1367
+ }
1368
+ await fastForwardMeshNode({
1369
+ meshId: args.meshId,
1370
+ nodeId: args.nodeId,
1371
+ workspace,
1372
+ execute: true,
1373
+ dryRun: false,
1374
+ updateSubmodules: false,
1375
+ submoduleIgnorePaths,
1376
+ trigger: 'idle_auto',
1377
+ });
1378
+ } catch (e: any) {
1379
+ LOG.warn('MeshFastForward', `Idle auto fast-forward check failed for ${args.nodeId}: ${e?.message || e}`);
1380
+ }
1381
+ }
1382
+
1383
+ function runIdleMaintenanceThenAssignQueue(components: DaemonComponents, args: {
1384
+ meshId: string;
1385
+ nodeId: string;
1386
+ sessionId: string;
1387
+ providerType: string;
1388
+ }): void {
1389
+ setImmediate(() => {
1390
+ maybeAutoFastForwardIdleNode(components, args)
1391
+ .finally(() => {
1392
+ try {
1393
+ tryAssignQueueTask(components, args.meshId, args.nodeId, args.sessionId, args.providerType);
1394
+ } catch (e: any) {
1395
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${args.nodeId}: ${e?.message || e}`);
1396
+ }
1397
+ });
1398
+ });
1399
+ }
1400
+
1401
+ // ---------------------------------------------------------------------------
1402
+ // Core event injection
1403
+ // ---------------------------------------------------------------------------
1404
+
1405
+ const MESH_COORDINATOR_EVENTS = new Set([
1406
+ 'agent:generating_started',
1407
+ 'agent:generating_completed',
1408
+ 'agent:waiting_approval',
1409
+ 'agent:stopped',
1410
+ 'agent:ready',
1411
+ 'monitor:no_progress',
1412
+ 'refine:accepted',
1413
+ 'refine:completed',
1414
+ 'refine:failed',
1415
+ 'worktree_bootstrap_complete',
1416
+ 'worktree_bootstrap_failed',
1417
+ ]);
1418
+
1419
+ const EVENT_TO_LEDGER_KIND: Record<string, MeshLedgerKind> = {
1420
+ 'agent:generating_completed': 'task_completed',
1421
+ 'agent:waiting_approval': 'task_approval_needed',
1422
+ 'agent:stopped': 'task_failed',
1423
+ 'monitor:no_progress': 'task_stalled',
1424
+ };
1425
+
1426
+ export function isMeshCoordinatorEvent(eventName: unknown): eventName is string {
1427
+ return typeof eventName === 'string' && MESH_COORDINATOR_EVENTS.has(eventName);
1428
+ }
1429
+
1430
+ // Terminal events that the coordinator is actively blocked waiting on. When the
1431
+ // coordinator CLI session dispatches a task (e.g. mesh_send_task) it stays in
1432
+ // `generating` until the result arrives — but a generating coordinator queues
1433
+ // incoming send_message calls into its adapter's pendingOutboundQueue, which is
1434
+ // only flushed on the coordinator's OWN idle transition. That transition can't
1435
+ // happen until it receives this very event → deadlock. We force-inject these so
1436
+ // they bypass the busy send-guard and land in the PTY while generating.
1437
+ export const MESH_FORCE_INJECT_EVENTS: ReadonlySet<string> = new Set([
1438
+ 'agent:generating_completed',
1439
+ 'agent:stopped',
1440
+ 'agent:waiting_approval',
1441
+ 'refine:completed',
1442
+ 'refine:failed',
1443
+ 'worktree_bootstrap_complete',
1444
+ 'worktree_bootstrap_failed',
1445
+ ]);
1446
+
1447
+ export function shouldForceInjectMeshEvent(eventName: unknown): boolean {
1448
+ return typeof eventName === 'string' && MESH_FORCE_INJECT_EVENTS.has(eventName);
1449
+ }
1450
+
1451
+ function injectMeshSystemMessage(components: DaemonComponents, args: {
1452
+ meshId: string;
1453
+ sourceInstanceId?: string;
1454
+ nodeId?: string;
1455
+ nodeLabel: string;
1456
+ event: string;
1457
+ metadataEvent: Record<string, unknown>;
1458
+ }) {
1459
+ const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1460
+ const eventNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1461
+
1462
+ const sourceSession = args.sourceInstanceId
1463
+ ? components.instanceManager.getInstance(args.sourceInstanceId)
1464
+ : undefined;
1465
+ const workerCoordinatorDaemonId = readNonEmptyString(
1466
+ (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorDaemonId,
1467
+ );
1468
+ // Session-level routing anchor (multi-coordinator). Prefer the LIVE worker session's
1469
+ // stamp; fall back to a relayed value carried in metadataEvent.meshCoordinatorSessionId
1470
+ // (a remote worker's completion arrives via handleMeshForwardEvent with no local
1471
+ // sourceSession, so the stamp can only ride in the relayed metadata). Empty on legacy /
1472
+ // version-skewed dispatches → the event stays daemon-broadcast (no regression).
1473
+ const workerCoordinatorSessionId = readNonEmptyString(
1474
+ (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorSessionId,
1475
+ ) || readNonEmptyString(args.metadataEvent.meshCoordinatorSessionId);
1476
+
1477
+ // T2: a summary-less completion (and any non-completion status-sync event) carries no
1478
+ // assistant text on the event, so resolveMeshSurfacedSessionPreview had nothing to surface
1479
+ // and the coordinator's inbox mirror stayed stuck on the first dispatched user task. When
1480
+ // THIS daemon hosts the live worker instance (sourceSession present), derive the worker's
1481
+ // latest display message straight from its transcript and attach it to the event as
1482
+ // lastMessagePreview/lastMessageRole/lastMessageAt. resolveMeshSurfacedSessionPreview reads
1483
+ // these as an assistant-only fallback; they also ride the pending-queue + P2P relay
1484
+ // (handleMeshForwardEvent whitelist) so a remote coordinator can surface them. A remote
1485
+ // coordinator has no local instance and keeps relying on the relayed fields — unchanged.
1486
+ const enrichedMetadataEvent = ((): Record<string, unknown> => {
1487
+ const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
1488
+ if (!last || !last.preview) return args.metadataEvent;
1489
+ return {
1490
+ ...args.metadataEvent,
1491
+ lastMessagePreview: last.preview,
1492
+ lastMessageRole: last.role,
1493
+ ...(last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}),
1494
+ };
1495
+ })();
1496
+
1497
+ // R2: cloud P2P dashboard metadata sync. The cloud daemon used to do this from its own
1498
+ // relay listener; now the single core forwarder invokes the injected hook (no-op on
1499
+ // standalone) so the event path stays single-listener and the local code path is identical
1500
+ // across standalone and cloud.
1501
+ if (components.onMeshCoordinatorEventForwarded) {
1502
+ try {
1503
+ // T: the coordinator surfaces a remote worker's session but holds no local
1504
+ // instance for it, so the status snapshot can't derive a preview and the
1505
+ // mirror would stay stuck on the first dispatched user task. Resolve the
1506
+ // worker's latest assistant reply (carried on the completion event's
1507
+ // finalSummary / workerResult) into a preview the mirror can stamp, so the
1508
+ // mobile inbox reflects the assistant response. Completion events carry assistant
1509
+ // text as finalSummary; a summary-less completion / status sync falls back to the
1510
+ // worker's latest assistant display message (enrichedMetadataEvent.lastMessage*).
1511
+ // For a mid-turn user-only event this is undefined and the prior surfaced preview
1512
+ // is preserved downstream (no clobber).
1513
+ const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
1514
+ components.onMeshCoordinatorEventForwarded({
1515
+ event: args.event,
1516
+ meshId: args.meshId,
1517
+ nodeId: eventNodeId || undefined,
1518
+ ...enrichedMetadataEvent,
1519
+ // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
1520
+ // worker provider event only carried `workspaceName`. The merge spread of
1521
+ // metadataEvent above wins when it already has a non-empty `workspace`.
1522
+ workspace: readNonEmptyString(args.metadataEvent.workspace)
1523
+ || readNonEmptyString(args.metadataEvent.workspaceName)
1524
+ || undefined,
1525
+ ...(surfacedPreview ? {
1526
+ meshSessionLastMessagePreview: surfacedPreview.preview,
1527
+ meshSessionLastMessageRole: surfacedPreview.role,
1528
+ meshSessionLastMessageAt: surfacedPreview.receivedAt || undefined,
1529
+ } : {}),
1530
+ });
1531
+ } catch { /* dashboard metadata sync is best-effort */ }
1532
+ }
1533
+
1534
+ const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
1535
+ event: args.event,
1536
+ meshId: args.meshId,
1537
+ metadataEvent: args.metadataEvent,
1538
+ sessionId: eventSessionId || undefined,
1539
+ nodeId: eventNodeId || undefined,
1540
+ });
1541
+ if (intentionalCleanupStop) {
1542
+ if (eventSessionId && eventNodeId) {
1543
+ try {
1544
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(eventNodeId, eventSessionId);
1545
+ } catch { /* best-effort */ }
1546
+ }
1547
+ LOG.info('MeshEvents', `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || '(unknown session)'}`);
1548
+ return { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true };
1549
+ }
1550
+
1551
+ if (args.event === 'monitor:no_progress') {
1552
+ const reconciledCompletion = buildNoProgressCompletionReconciliation({
1553
+ meshId: args.meshId,
1554
+ nodeId: args.nodeId,
1555
+ nodeLabel: args.nodeLabel,
1556
+ metadataEvent: args.metadataEvent,
1557
+ sourceInstanceId: args.sourceInstanceId,
1558
+ });
1559
+ if (reconciledCompletion?.source === 'no_progress_reconciliation') {
1560
+ LOG.info('MeshEvents', `Reconciled no-progress monitor to completion for session ${eventSessionId || '(unknown session)'}`);
1561
+ return injectMeshSystemMessage(components, {
1562
+ ...args,
1563
+ event: 'agent:generating_completed',
1564
+ metadataEvent: reconciledCompletion,
1565
+ });
1566
+ }
1567
+ if (reconciledCompletion?.source === 'no_progress_terminal_ledger_suppression') {
1568
+ LOG.info('MeshEvents', `Suppressed no-progress monitor because terminal ledger evidence already exists for session ${eventSessionId || '(unknown session)'}`);
1569
+ return {
1570
+ success: true,
1571
+ forwarded: 0,
1572
+ suppressed: true,
1573
+ terminalLedgerEvidence: true,
1574
+ terminalLedgerKind: reconciledCompletion.terminalLedgerKind,
1575
+ };
1576
+ }
1577
+ }
1578
+
1579
+ if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
1580
+ LOG.info('MeshEvents', `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
1581
+ return { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true };
1582
+ }
1583
+
1584
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
1585
+ if (args.event === 'agent:waiting_approval' && eventSessionId) {
1586
+ const duplicateApproval = isDuplicateMeshApprovalEvent({
1587
+ meshId: args.meshId,
1588
+ sessionId: eventSessionId,
1589
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1590
+ timestamp: eventTimestamp,
1591
+ modalMessage: readNonEmptyString(args.metadataEvent.modalMessage) || undefined,
1592
+ modalButtons: args.metadataEvent.modalButtons,
1593
+ });
1594
+ if (duplicateApproval) {
1595
+ LOG.info('MeshEvents', `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
1596
+ return { success: true, forwarded: 0, suppressed: true, duplicateApproval: true };
1597
+ }
1598
+ }
1599
+ if (args.event === 'agent:generating_completed' && eventSessionId) {
1600
+ const terminal = findRecentTerminalLedgerEvidence({
1601
+ meshId: args.meshId,
1602
+ sessionId: eventSessionId,
1603
+ nodeId: eventNodeId || undefined,
1604
+ });
1605
+ if (terminal?.kind === 'task_completed' && !sessionHasActiveAssignment(args.meshId, eventSessionId)) {
1606
+ const newDispatchAfterTerminal = hasDispatchAfterTerminal(args.meshId, eventSessionId, terminal.id);
1607
+ // Fix B (re-dispatch 2nd-completion routing): a prior terminal recorded from a FALSE
1608
+ // idle (weak evidence / no confirmed final assistant) must NOT permanently suppress a
1609
+ // later GENUINE completion of the same session. providerSessionId is stable across a
1610
+ // session's turns, so the providerSessionId/finalSummary dedup below would otherwise
1611
+ // swallow the real 2nd-turn completion that a coordinator nudge (direct re-dispatch)
1612
+ // drove — exactly the missed-event bug. When the prior terminal was weak and the new
1613
+ // event carries genuine completion evidence, let it through so it is recorded and
1614
+ // re-attributed to the latest task (the normal task_completed path below).
1615
+ const supersedesWeakTerminal = isWeakTerminalLedgerPayload(terminal.payload)
1616
+ && isGenuineCompletionEvidence(args.metadataEvent);
1617
+ if (!newDispatchAfterTerminal && !supersedesWeakTerminal) {
1618
+ const terminalProviderSessionId = readNonEmptyString(terminal.payload.providerSessionId);
1619
+ const terminalFinalSummary = readNonEmptyString(terminal.payload.finalSummary);
1620
+ const eventProviderSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
1621
+ const eventFinalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
1622
+ if (
1623
+ (terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId)
1624
+ || (terminalFinalSummary && terminalFinalSummary === eventFinalSummary)
1625
+ || args.metadataEvent.source === 'no_progress_reconciliation'
1626
+ ) {
1627
+ LOG.info('MeshEvents', `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
1628
+ return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true };
1629
+ }
1630
+ }
1631
+ }
1632
+ const duplicateCompletion = isDuplicateMeshCompletionEvent({
1633
+ meshId: args.meshId,
1634
+ event: args.event,
1635
+ sessionId: eventSessionId,
1636
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1637
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
1638
+ timestamp: eventTimestamp,
1639
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
1640
+ coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
1641
+ taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
1642
+ nodeId: eventNodeId || undefined,
1643
+ });
1644
+ if (duplicateCompletion) {
1645
+ LOG.info('MeshEvents', `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
1646
+ return { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true };
1647
+ }
1648
+ }
1649
+ if (args.event === 'agent:stopped' && eventSessionId) {
1650
+ const duplicateStopped = isDuplicateMeshCompletionEvent({
1651
+ meshId: args.meshId,
1652
+ event: args.event,
1653
+ sessionId: eventSessionId,
1654
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
1655
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
1656
+ timestamp: eventTimestamp,
1657
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
1658
+ coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
1659
+ taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
1660
+ nodeId: eventNodeId || undefined,
1661
+ });
1662
+ if (duplicateStopped) {
1663
+ LOG.info('MeshEvents', `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
1664
+ return { success: true, forwarded: 0, suppressed: true, duplicateStopped: true };
1665
+ }
1666
+ }
1667
+
1668
+ function markSessionTerminal(sessionId: string, outcome: 'completed' | 'failed', occurredAtMs?: number | null, opts?: { tentativeIfDirect?: boolean }): { id?: string } | null {
1669
+ // C2: prefer an exact taskId match when the completion event carries one —
1670
+ // it's immune to coordinator↔worker clock skew that can hide the assigned row.
1671
+ const eventTaskId = readNonEmptyString(args.metadataEvent.taskId) || undefined;
1672
+ const task = updateSessionTaskStatus(args.meshId, sessionId, outcome, {
1673
+ occurredAt: occurredAtMs != null ? new Date(occurredAtMs).toISOString() : undefined,
1674
+ taskId: eventTaskId,
1675
+ });
1676
+ // Fix A (early-terminal prevention): a false-idle completion (no confirmed final
1677
+ // assistant) for a DIRECT dispatch — i.e. no work-queue row matched — must not flip the
1678
+ // dispatch row terminal. Leaving it active lets the reconcile loop (PHASE 4) re-read the
1679
+ // transcript and record the genuine completion once the worker truly finishes (commonly
1680
+ // after a coordinator nudge / re-dispatch). A matched queue task, or a completion with
1681
+ // genuine evidence, is marked terminal as before.
1682
+ const leaveDirectDispatchActive = !task && opts?.tentativeIfDirect === true;
1683
+ if (!leaveDirectDispatchActive) {
1684
+ updateDirectDispatchStatus(args.meshId, sessionId, outcome);
1685
+ }
1686
+ markSessionDeliveriesTerminal(args.meshId, sessionId, outcome);
1687
+ setImmediate(() => cleanupTerminalDirectDispatches());
1688
+ return task ? { id: task.id } : null;
1689
+ }
1690
+
1691
+ let completedTaskForLedger: { id?: string } | null = null;
1692
+ // Fix B: direct-dispatch taskId used to attribute the terminal ledger entry when no
1693
+ // work-queue row matches (resolved BEFORE markSessionTerminal flips the dispatch terminal).
1694
+ let directDispatchTaskIdForLedger: string | undefined;
1695
+ if (args.event === 'agent:generating_completed') {
1696
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1697
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1698
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
1699
+
1700
+ if (sessionId) {
1701
+ directDispatchTaskIdForLedger = resolveActiveDirectDispatchTaskId(args.meshId, sessionId);
1702
+ // A false-idle completion of a direct dispatch is recorded but kept tentative (the
1703
+ // dispatch row stays active for the reconcile fallback); a genuine completion is terminal.
1704
+ const isFalseIdle = isFalseIdleCompletion(args.metadataEvent);
1705
+ completedTaskForLedger = markSessionTerminal(sessionId, 'completed', eventTimestamp, { tentativeIfDirect: isFalseIdle });
1706
+ if (nodeId && providerType) {
1707
+ runIdleMaintenanceThenAssignQueue(components, { meshId: args.meshId, nodeId, sessionId, providerType });
1708
+ }
1709
+ // M1-3: wake dependents of the completed task. The maintenance path above
1710
+ // only assigns to the completing session; dependents may be claimable by
1711
+ // other idle sessions, so run a full queue trigger when any are waiting.
1712
+ const completedTaskId = completedTaskForLedger?.id;
1713
+ if (completedTaskId && hasPendingDependents(args.meshId, completedTaskId)) {
1714
+ setImmediate(() => {
1715
+ triggerMeshQueue(components, args.meshId).catch((e: any) => {
1716
+ LOG.warn('MeshQueue', `Dependent wake after task ${completedTaskId} failed: ${e?.message || e}`);
1717
+ });
1718
+ });
1719
+ }
1720
+ }
1721
+ } else if (args.event === 'agent:ready') {
1722
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1723
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1724
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
1725
+ const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
1726
+ const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
1727
+ const workerResult = readWorkerResultMetadata(args.metadataEvent);
1728
+ const hasCompletionEvidence = !!finalSummary || !!workerResult;
1729
+ if (sessionId && hasCompletionEvidence) {
1730
+ completedTaskForLedger = markSessionTerminal(sessionId, 'completed');
1731
+ if (completedTaskForLedger) {
1732
+ try {
1733
+ appendLedgerEntry(args.meshId, {
1734
+ kind: 'task_completed',
1735
+ nodeId: nodeId || undefined,
1736
+ sessionId,
1737
+ providerType: providerType || undefined,
1738
+ payload: {
1739
+ event: args.event,
1740
+ nodeLabel: args.nodeLabel,
1741
+ taskId: completedTaskForLedger.id,
1742
+ completedViaReady: true,
1743
+ providerSessionId,
1744
+ finalSummary,
1745
+ workerResult,
1746
+ evidence: buildTaskCompletionEvidence({
1747
+ event: 'agent:ready',
1748
+ nodeId,
1749
+ sessionId,
1750
+ providerType: providerType || undefined,
1751
+ providerSessionId,
1752
+ finalSummary,
1753
+ workerResult,
1754
+ }),
1755
+ },
1756
+ });
1757
+ } catch (e: any) {
1758
+ LOG.warn('MeshLedger', `Failed to record task_completed from ready: ${e?.message || e}`);
1759
+ }
1760
+ }
1761
+ }
1762
+
1763
+ if (sessionId && nodeId && providerType) {
1764
+ sweepExpiredRemoteIdleSessions();
1765
+ try {
1766
+ MeshRuntimeStore.getInstance().setRemoteIdleSession(nodeId, sessionId, providerType, Date.now() + REMOTE_IDLE_SESSION_TTL_MS);
1767
+ } catch { /* best-effort */ }
1768
+ setImmediate(() => {
1769
+ maybeAutoFastForwardIdleNode(components, { meshId: args.meshId, nodeId, sessionId, providerType })
1770
+ .finally(() => {
1771
+ try {
1772
+ const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
1773
+ if (assigned) MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
1774
+ } catch (e: any) {
1775
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${nodeId}: ${e?.message || e}`);
1776
+ }
1777
+ });
1778
+ });
1779
+ }
1780
+ } else if (args.event === 'agent:generating_started') {
1781
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1782
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1783
+ if (sessionId && nodeId) {
1784
+ try {
1785
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
1786
+ } catch { /* best-effort */ }
1787
+ }
1788
+ if (sessionId) {
1789
+ updateDirectDispatchStatus(args.meshId, sessionId, 'acked');
1790
+ const activeDeliveries = ((): { id: string }[] => {
1791
+ try { return MeshRuntimeStore.getInstance().getActiveSessionDeliveries(args.meshId, sessionId); }
1792
+ catch { return []; }
1793
+ })();
1794
+ for (const d of activeDeliveries) {
1795
+ updateSessionDeliveryStatus(d.id, 'acked');
1796
+ }
1797
+ }
1798
+ } else if (args.event === 'agent:stopped') {
1799
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1800
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1801
+ if (sessionId && nodeId) {
1802
+ try {
1803
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(nodeId, sessionId);
1804
+ } catch { /* best-effort */ }
1805
+ }
1806
+ if (sessionId) {
1807
+ directDispatchTaskIdForLedger = resolveActiveDirectDispatchTaskId(args.meshId, sessionId);
1808
+ completedTaskForLedger = markSessionTerminal(sessionId, 'failed');
1809
+ }
1810
+ }
1811
+
1812
+ const ledgerKind = EVENT_TO_LEDGER_KIND[args.event];
1813
+ if (ledgerKind) {
1814
+ try {
1815
+ const ledgerNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined;
1816
+ const ledgerSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined;
1817
+ const ledgerProviderType = readNonEmptyString(args.metadataEvent.providerType) || undefined;
1818
+ const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
1819
+ const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
1820
+ const workerResult = readWorkerResultMetadata(args.metadataEvent);
1821
+ const completionEvidence = ledgerKind === 'task_completed' && ledgerNodeId && ledgerSessionId
1822
+ ? buildTaskCompletionEvidence({
1823
+ event: 'agent:generating_completed',
1824
+ nodeId: ledgerNodeId,
1825
+ sessionId: ledgerSessionId,
1826
+ providerType: ledgerProviderType,
1827
+ providerSessionId,
1828
+ finalSummary,
1829
+ workerResult,
1830
+ })
1831
+ : undefined;
1832
+ appendLedgerEntry(args.meshId, {
1833
+ kind: ledgerKind,
1834
+ nodeId: ledgerNodeId,
1835
+ sessionId: ledgerSessionId,
1836
+ providerType: ledgerProviderType,
1837
+ payload: {
1838
+ event: args.event,
1839
+ nodeLabel: args.nodeLabel,
1840
+ // Fix B: fall back to the direct-dispatch taskId when no work-queue row
1841
+ // matched, so the terminal entry is attributable in mesh task-stats
1842
+ // (otherwise the direct task shows status='unknown' / terminalKind=null).
1843
+ taskId: completedTaskForLedger?.id || directDispatchTaskIdForLedger || undefined,
1844
+ providerSessionId,
1845
+ finalSummary,
1846
+ workerResult,
1847
+ completionDiagnostic: args.metadataEvent.completionDiagnostic && typeof args.metadataEvent.completionDiagnostic === 'object'
1848
+ ? args.metadataEvent.completionDiagnostic
1849
+ : undefined,
1850
+ evidence: completionEvidence,
1851
+ // B2: evidenceLevel lets coordinator know when completion evidence is insufficient.
1852
+ ...(completionEvidence
1853
+ ? completionEvidence.workerResult.source === 'default'
1854
+ ? { evidenceLevel: 'insufficient', reviewRecommended: true }
1855
+ : { evidenceLevel: 'sufficient' }
1856
+ : {}),
1857
+ },
1858
+ });
1859
+ } catch (e: any) {
1860
+ LOG.warn('MeshLedger', `Failed to record ${ledgerKind}: ${e?.message || e}`);
1861
+ }
1862
+ }
1863
+
1864
+ let recoveryContext: SessionRecoveryContext | null = null;
1865
+ if (args.event === 'agent:stopped') {
1866
+ try {
1867
+ const mesh = getMesh(args.meshId);
1868
+ const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
1869
+
1870
+ recoveryContext = getSessionRecoveryContext(args.meshId, {
1871
+ sessionId: resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined,
1872
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined,
1873
+ maxRetries,
1874
+ });
1875
+ recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
1876
+
1877
+ if (recoveryContext.retryRecommended && recoveryContext.consecutiveNodeFailures > 0) {
1878
+ appendLedgerEntry(args.meshId, {
1879
+ kind: 'recovery_attempted',
1880
+ nodeId: recoveryContext.failedNodeId || undefined,
1881
+ sessionId: recoveryContext.failedSessionId || undefined,
1882
+ providerType: recoveryContext.failedProviderType || undefined,
1883
+ payload: {
1884
+ consecutiveFailures: recoveryContext.consecutiveNodeFailures,
1885
+ taskAttemptCount: recoveryContext.taskAttemptCount,
1886
+ retryRecommended: recoveryContext.retryRecommended,
1887
+ advice: recoveryContext.advice,
1888
+ },
1889
+ });
1890
+
1891
+ if (recoveryContext.lastTaskMessage && recoveryContext.failedNodeId && recoveryContext.failedProviderType) {
1892
+ const autoNodeId = recoveryContext.failedNodeId;
1893
+ try {
1894
+ const task = enqueueTask(args.meshId, recoveryContext.lastTaskMessage, {
1895
+ targetNodeId: autoNodeId
1896
+ });
1897
+ LOG.info('MeshRecovery', `Auto-requeued failed task: ${task.id} for node ${autoNodeId}`);
1898
+
1899
+ const node = mesh?.nodes.find((n: any) => n.id === autoNodeId);
1900
+ if (node) {
1901
+ components.cliManager.handleCliCommand('launch_cli', {
1902
+ cliType: recoveryContext.failedProviderType,
1903
+ dir: node.workspace,
1904
+ settings: {
1905
+ role: 'worker',
1906
+ meshNodeFor: args.meshId,
1907
+ meshNodeId: node.id,
1908
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1909
+ // Coordinator-dispatched recovery relaunch: same auto-approve
1910
+ // policy as the primary worker launch path.
1911
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1912
+ launchedByCoordinator: true,
1913
+ }
1914
+ }).catch((e: any) => LOG.error('MeshRecovery', `Failed to auto-relaunch session for ${node.id}: ${e?.message}`));
1915
+ }
1916
+ } catch (e: any) {
1917
+ LOG.warn('MeshRecovery', `Failed to execute auto-recovery: ${e?.message}`);
1918
+ }
1919
+ }
1920
+ }
1921
+
1922
+ LOG.info('MeshRecovery', `Recovery context for ${args.nodeLabel}: ${recoveryContext.advice}`);
1923
+ } catch (e: any) {
1924
+ LOG.warn('MeshRecovery', `Failed to build recovery context: ${e?.message || e}`);
1925
+ }
1926
+ }
1927
+
1928
+ const messageText = buildMeshSystemMessage({
1929
+ event: args.event,
1930
+ nodeLabel: args.nodeLabel,
1931
+ metadataEvent: args.metadataEvent,
1932
+ recoveryContext,
1933
+ });
1934
+ if (!messageText) {
1935
+ // Lifecycle events that carry no coordinator-facing message (agent:ready /
1936
+ // agent:generating_started) still drive the remote-claim state machine: the
1937
+ // coordinator's agent:ready branch above runs setRemoteIdleSession +
1938
+ // tryAssignQueueTask, and agent:generating_started clears the remote-idle entry.
1939
+ // For a LOCAL worker whose coordinator is a REMOTE daemon those side effects ran
1940
+ // on the wrong daemon (this worker's empty queue / store), so the coordinator never
1941
+ // learns the auto-launched session went idle and re-auto-launches it forever
1942
+ // (queue task stuck pending). Queue the silent event so the coordinator pulls it
1943
+ // (PHASE 1 pullRemoteNodeQueues → handleMeshForwardEvent) and re-runs the claim on
1944
+ // the daemon that actually owns the queue. Gate strictly on a present, REMOTE
1945
+ // coordinator daemon id: a co-located worker already ran the claim on the right
1946
+ // daemon, and a coordinator processing a *pulled* event has no sourceSession so
1947
+ // workerCoordinatorDaemonId is empty — neither re-queues, so there is no loop.
1948
+ const isSilentClaimRelevantEvent = args.event === 'agent:ready' || args.event === 'agent:generating_started';
1949
+ const coordinatorIsRemote = !!workerCoordinatorDaemonId
1950
+ && !resolveCoordinatorDrainDaemonIds(components).includes(workerCoordinatorDaemonId);
1951
+ if (!(isSilentClaimRelevantEvent && coordinatorIsRemote)) {
1952
+ return { success: false, error: 'unsupported mesh event' };
1953
+ }
1954
+ }
1955
+
1956
+ // ── Queue-only delivery (single-model: queue + periodic poll) ──────────────
1957
+ // Every mesh coordinator event — terminal or not, local-coordinator or
1958
+ // remote — is persisted to the pending-events queue (SQLite + JSONL) and
1959
+ // NOTHING is pushed here. The old spontaneous-forward paths were removed:
1960
+ // - F1 remote P2P `mesh_forward_event` dispatch (network/stamp-dependent,
1961
+ // silently dropped on P2P failure or missing meshCoordinatorDaemonId)
1962
+ // - F3 live-CLI PTY `send_message` fire-and-forget inject (silently
1963
+ // dropped when the coordinator was generating)
1964
+ // Delivery to a live CLI coordinator now happens via setupMeshReconcileLoop,
1965
+ // which drains this queue on a fixed interval and injects into the coordinator
1966
+ // only when it is idle. A pure stdio MCP (LLM) coordinator — which has no live
1967
+ // CLI session to inject into — drains the queue itself when it calls a mesh
1968
+ // tool (mesh_status / mesh_read_chat). Either way the queue is the single
1969
+ // source of truth and the only thing this function writes to.
1970
+ //
1971
+ // targetCoordinatorDaemonId scopes the event to a specific coordinator daemon
1972
+ // (unicast) when the worker carries one, so the reconcile loop on the right
1973
+ // daemon drains it and other daemons skip it. Absent → broadcast/backfill.
1974
+ const pendingEvent = {
1975
+ event: args.event,
1976
+ meshId: args.meshId,
1977
+ nodeLabel: args.nodeLabel,
1978
+ nodeId: args.nodeId || undefined,
1979
+ workspace: readNonEmptyString(args.metadataEvent.workspace)
1980
+ || readNonEmptyString(args.metadataEvent.workspaceName),
1981
+ metadataEvent: {
1982
+ ...enrichedMetadataEvent,
1983
+ ...(recoveryContext ? { recoveryContext } : {}),
1984
+ // Stash the coordinator session id INSIDE metadataEvent too, so it survives the
1985
+ // P2P relay serialization (buildForwardPayloadFromPending spreads metadata; the
1986
+ // handleMeshForwardEvent whitelist reads it back) — a top-level field alone would
1987
+ // be dropped when the event crosses a machine boundary.
1988
+ ...(workerCoordinatorSessionId ? { meshCoordinatorSessionId: workerCoordinatorSessionId } : {}),
1989
+ },
1990
+ // Silent lifecycle events (agent:ready / agent:generating_started) carry no
1991
+ // coordinator message; they are queued only so the coordinator re-runs the
1992
+ // remote-claim state machine on pull. injectPendingIntoCoordinator skips
1993
+ // entries without a coordinatorMessage, so a live CLI coordinator is not spammed.
1994
+ ...(messageText ? { coordinatorMessage: messageText } : {}),
1995
+ queuedAt: Date.now(),
1996
+ ...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
1997
+ // Top-level session anchor for the local PHASE 2 strict-match on the coordinator
1998
+ // daemon. Absent → daemon-level broadcast (legacy / single-coordinator path).
1999
+ ...(workerCoordinatorSessionId ? { targetCoordinatorSessionId: workerCoordinatorSessionId } : {}),
2000
+ };
2001
+ if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
2002
+ LOG.info('MeshEvents', `Queued ${args.event} for coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ''}${workerCoordinatorSessionId ? `, coordinator session ${workerCoordinatorSessionId}` : ''})`);
2003
+ }
2004
+ return { success: true, forwarded: 0 };
2005
+ }
2006
+
2007
+ export function handleMeshForwardEvent(components: DaemonComponents, payload: Record<string, unknown>) {
2008
+ const eventName = readNonEmptyString(payload.event);
2009
+ if (!isMeshCoordinatorEvent(eventName)) {
2010
+ return { success: false, error: 'unsupported mesh event' };
2011
+ }
2012
+ const nodeId = readNonEmptyString(payload.nodeId);
2013
+ const workspace = readNonEmptyString(payload.workspace);
2014
+
2015
+ // The fallback worker-forward path (forwardUnresolvedDelegateEvent) cannot resolve a
2016
+ // mesh id locally on the remote worker, so it forwards the event with workspace only.
2017
+ // The coordinator hosting the mesh CAN resolve it: recover the mesh id by workspace
2018
+ // when the payload doesn't carry one.
2019
+ const meshId = readNonEmptyString(payload.meshId)
2020
+ || (workspace ? readNonEmptyString(getCachedMeshByWorkspace(workspace)?.id) : '');
2021
+ if (!meshId) return { success: false, error: 'meshId required' };
2022
+ const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : 'Remote agent';
2023
+ const relayModalMessage = readNonEmptyString(payload.modalMessage);
2024
+ const relayModalButtons = Array.isArray(payload.modalButtons)
2025
+ ? (payload.modalButtons as unknown[]).filter((b): b is string => typeof b === 'string' && b.trim().length > 0)
2026
+ : null;
2027
+
2028
+ return injectMeshSystemMessage(components, {
2029
+ meshId,
2030
+ nodeId,
2031
+ nodeLabel,
2032
+ event: eventName,
2033
+ metadataEvent: {
2034
+ targetSessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.instanceId),
2035
+ providerType: readNonEmptyString(payload.providerType),
2036
+ providerSessionId: readNonEmptyString(payload.providerSessionId),
2037
+ // Preserve the originating coordinator SESSION id across the machine boundary so
2038
+ // the completion routes back to the exact coordinator session (multi-coordinator).
2039
+ // buildForwardPayloadFromPending spreads the worker event's metadata, so the id
2040
+ // arrives as payload.meshCoordinatorSessionId; the top-level targetCoordinatorSessionId
2041
+ // is also accepted as a fallback. injectMeshSystemMessage re-derives the routing
2042
+ // anchors from this. Absent → daemon-level fallback (version-skew safe).
2043
+ meshCoordinatorSessionId: readNonEmptyString(payload.meshCoordinatorSessionId) || readNonEmptyString(payload.targetCoordinatorSessionId),
2044
+ // Carry the session identity fields the worker provider event emits so the
2045
+ // coordinator's mirror (updateMeshOwnedSession) gets a real workspace/title/
2046
+ // settings. Without these the remote-relay hop reconstructs metadataEvent with
2047
+ // an empty workspace, and the dashboard flaps to the generic
2048
+ // "Terminal (Mesh Node)" title (and degrades the provider label) between live
2049
+ // events and the periodic get_status_metadata snapshot. The local in-process
2050
+ // forward path (onMeshCoordinatorEventForwarded) already preserves these; this
2051
+ // mirrors them for the remote-only relay path.
2052
+ workspace: readNonEmptyString(payload.workspace) || readNonEmptyString(payload.workspaceName),
2053
+ workspaceName: readNonEmptyString(payload.workspaceName) || readNonEmptyString(payload.workspace),
2054
+ sessionTitle: readNonEmptyString(payload.sessionTitle),
2055
+ sessionStatus: readNonEmptyString(payload.sessionStatus),
2056
+ sessionChatStatus: readNonEmptyString(payload.sessionChatStatus),
2057
+ providerName: readNonEmptyString(payload.providerName),
2058
+ ...(payload.sessionSettings && typeof payload.sessionSettings === 'object' && !Array.isArray(payload.sessionSettings) ? { sessionSettings: payload.sessionSettings } : {}),
2059
+ finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
2060
+ // T2: carry the worker's status-snapshot last-message preview across the machine
2061
+ // boundary so a summary-less completion still surfaces the assistant reply in the
2062
+ // coordinator's inbox mirror. resolveMeshSurfacedSessionPreview reads these
2063
+ // (assistant-role only) when finalSummary is absent.
2064
+ lastMessagePreview: readNonEmptyString(payload.lastMessagePreview),
2065
+ lastMessageRole: readNonEmptyString(payload.lastMessageRole),
2066
+ ...(payload.lastMessageAt !== undefined ? { lastMessageAt: payload.lastMessageAt } : {}),
2067
+ jobId: readNonEmptyString(payload.jobId),
2068
+ interactionId: readNonEmptyString(payload.interactionId),
2069
+ status: readNonEmptyString(payload.status),
2070
+ targetDaemonId: readNonEmptyString(payload.targetDaemonId),
2071
+ startedAt: readNonEmptyString(payload.startedAt),
2072
+ completedAt: readNonEmptyString(payload.completedAt),
2073
+ retryOfJobId: readNonEmptyString(payload.retryOfJobId),
2074
+ ...(relayModalMessage ? { modalMessage: relayModalMessage } : {}),
2075
+ ...(relayModalButtons && relayModalButtons.length > 0 ? { modalButtons: relayModalButtons } : {}),
2076
+ ...(payload.result && typeof payload.result === 'object' && !Array.isArray(payload.result) ? { result: payload.result } : {}),
2077
+ ...(payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic) ? { completionDiagnostic: payload.completionDiagnostic } : {}),
2078
+ ...(payload.workerResult && typeof payload.workerResult === 'object' && !Array.isArray(payload.workerResult) ? { workerResult: payload.workerResult } : {}),
2079
+ ...(payload.meshWorkerResult && typeof payload.meshWorkerResult === 'object' && !Array.isArray(payload.meshWorkerResult) ? { meshWorkerResult: payload.meshWorkerResult } : {}),
2080
+ ...(payload.structuredResult && typeof payload.structuredResult === 'object' && !Array.isArray(payload.structuredResult) ? { structuredResult: payload.structuredResult } : {}),
2081
+ ...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}),
2082
+ intentional: payload.intentional === true,
2083
+ intentionalStop: payload.intentionalStop === true,
2084
+ operatorCleanup: payload.operatorCleanup === true,
2085
+ reason: readNonEmptyString(payload.reason),
2086
+ stopReason: readNonEmptyString(payload.stopReason),
2087
+ cleanupReason: readNonEmptyString(payload.cleanupReason),
2088
+ source: readNonEmptyString(payload.source),
2089
+ },
2090
+ });
2091
+ }
2092
+
2093
+ // ---------------------------------------------------------------------------
2094
+ // Worker-side fallback forward for unresolved-mesh delegates.
2095
+ //
2096
+ // A REMOTE worker daemon that is being P2P-remote-controlled by a coordinator is
2097
+ // NOT a member of the coordinator's mesh — it has no local mesh record. So when its
2098
+ // completion event reaches the forwarder, resolveWorkerDelegateRouting() resolves the
2099
+ // coordinator anchor (meshCoordinatorDaemonId) from the worker envelope but cannot
2100
+ // resolve the mesh id (neither meshNodeFor nor a workspace→mesh lookup yields one) and
2101
+ // returns isDelegate=false / mesh_unresolved. Before this fallback the event was dropped
2102
+ // (delivery_unroutable) and only recovered later when the coordinator happened to pull
2103
+ // the worker's queue — which it can't, because the worker never queued an unroutable
2104
+ // event. Live symptom: `WARN [MeshEvents] delivery_unroutable: ... mesh unresolved`.
2105
+ //
2106
+ // The fix: the routing object still carries coordinatorDaemonId. Forward the raw event
2107
+ // straight to that coordinator daemon over P2P (mesh_forward_event). The coordinator
2108
+ // hosts the mesh, so it recovers the mesh id by workspace in handleMeshForwardEvent and
2109
+ // injects/queues it normally. meshId is intentionally omitted from the payload (the
2110
+ // worker has none); workspace is the routing anchor the coordinator resolves from.
2111
+ //
2112
+ // No loop / no double-delivery:
2113
+ // - This only fires on the WORKER (the coordinator-own session is rejected by the
2114
+ // resolver before reaching here), and the coordinator merely injects — it does not
2115
+ // re-enter this forwarder for the relayed event.
2116
+ // - It fires only when the normal queue path did NOT run (isDelegate=false), so the
2117
+ // event is never both queued locally and forwarded.
2118
+ //
2119
+ // Returns true when the event was durably accepted for delivery to the coordinator
2120
+ // daemon (so the caller skips the delivery_unroutable diagnostic); false when no
2121
+ // fallback was possible (no coordinator anchor / no dispatch transport).
2122
+ //
2123
+ // Durability: the directed push to the coordinator is the ONLY delivery route for an
2124
+ // unresolved-mesh worker (it is in no mesh.node the coordinator can pull). So instead
2125
+ // of a fire-and-forget push that drops on one transient P2P failure, the event is
2126
+ // persisted to the worker-side outbox FIRST and only acked after a successful push.
2127
+ // A best-effort immediate push keeps latency low on the happy path; a failed or
2128
+ // un-acked push leaves the durable row for setupMeshReconcileLoop's PHASE 0 to retry.
2129
+ function forwardUnresolvedDelegateEvent(
2130
+ components: DaemonComponents,
2131
+ routing: ReturnType<typeof resolveWorkerDelegateRouting>,
2132
+ event: Record<string, unknown>,
2133
+ ): boolean {
2134
+ const coordinatorDaemonId = readNonEmptyString(routing.coordinatorDaemonId);
2135
+ if (!coordinatorDaemonId) return false;
2136
+ if (!components.dispatchMeshCommand) return false;
2137
+
2138
+ const eventName = readNonEmptyString(event.event);
2139
+ if (!eventName) return false;
2140
+
2141
+ // Flat payload mirroring buildForwardPayloadFromPending / what handleMeshForwardEvent
2142
+ // reads. meshId is omitted on purpose — the worker can't resolve it; the coordinator
2143
+ // recovers it from workspace. nodeId/workspace come from the worker envelope so the
2144
+ // coordinator can name and locate the node.
2145
+ const payload: Record<string, unknown> = {
2146
+ ...event,
2147
+ event: eventName,
2148
+ nodeId: readNonEmptyString(routing.nodeId) || readNonEmptyString(event.meshNodeId) || undefined,
2149
+ workspace: readNonEmptyString(routing.workspace) || readNonEmptyString(event.workspace) || undefined,
2150
+ };
2151
+
2152
+ // 1) Persist durably FIRST. Idempotent on fingerprint, so a re-fired completion
2153
+ // does not duplicate the outbox row. If persistence fails we still attempt the
2154
+ // push below (degrades to the old at-most-once behaviour rather than dropping
2155
+ // the chance entirely).
2156
+ const persisted = enqueueUnresolvedDelegateForward(coordinatorDaemonId, eventName, payload);
2157
+
2158
+ // 2) Best-effort immediate push for low latency. On success, ack the outbox row so
2159
+ // the retry loop won't re-send it. On failure, leave it queued — PHASE 0 retries.
2160
+ Promise.resolve(components.dispatchMeshCommand(coordinatorDaemonId, 'mesh_forward_event', payload))
2161
+ .then((result: any) => {
2162
+ if (result && result.success === false) {
2163
+ LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} rejected (${readNonEmptyString(result.error) || 'no reason'}) — left queued for retry`);
2164
+ return;
2165
+ }
2166
+ // Acked. Mark the durable copy delivered so the retry loop skips it.
2167
+ if (persisted) ackUnresolvedDelegateForwardByFingerprint(coordinatorDaemonId, eventName, payload);
2168
+ })
2169
+ .catch((e: any) => {
2170
+ // Coordinator momentarily unreachable; the durable row stays queued and the
2171
+ // reconcile loop retries it. Trace so the relay attempt is visible.
2172
+ LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} failed: ${e?.message || e} — left queued for retry`);
2173
+ });
2174
+ LOG.info('MeshEvents', `Durably forwarded ${eventName} for unresolved-mesh worker at ${routing.workspace || '(no workspace)'} to coordinator daemon ${coordinatorDaemonId}`);
2175
+ return true;
2176
+ }
2177
+
2178
+ // Ack a just-pushed outbox entry by re-deriving its row from the same coordinator +
2179
+ // event + payload. We don't thread the row id back from enqueue (the immediate push is
2180
+ // fire-then-ack), so locate it among the undrained entries by matching coordinator and
2181
+ // the flat payload's forward identity. A miss is harmless — the retry loop's own
2182
+ // receiver-side dedup suppresses a duplicate delivery.
2183
+ function ackUnresolvedDelegateForwardByFingerprint(
2184
+ coordinatorDaemonId: string,
2185
+ eventName: string,
2186
+ payload: Record<string, unknown>,
2187
+ ): void {
2188
+ const match = peekUnresolvedDelegateForwards().find(entry =>
2189
+ entry.coordinatorDaemonId === coordinatorDaemonId
2190
+ && readNonEmptyString(entry.payload.event) === eventName
2191
+ && readNonEmptyString(entry.payload.targetSessionId || entry.payload.sessionId || entry.payload.instanceId)
2192
+ === readNonEmptyString(payload.targetSessionId || payload.sessionId || payload.instanceId)
2193
+ && readNonEmptyString(entry.payload.workspace) === readNonEmptyString(payload.workspace),
2194
+ );
2195
+ if (match) ackUnresolvedDelegateForward(match.id);
2196
+ }
2197
+
2198
+ export function setupMeshEventForwarding(components: DaemonComponents) {
2199
+ components.instanceManager.onEvent((event) => {
2200
+ // --- Coordinator idle auto-flush (fast path) ---
2201
+ // When a coordinator session becomes idle, immediately flush any pending
2202
+ // coordinator events that accumulated while it was generating, rather than
2203
+ // waiting up to one reconcile interval for setupMeshReconcileLoop to do it.
2204
+ // Both paths drain the SAME queue via drainPendingMeshCoordinatorEvents,
2205
+ // whose SQLite drained=1 marking is atomic — whichever fires first consumes
2206
+ // the events and the other gets nothing, so there is no double-delivery.
2207
+ // This runs before the delegate routing below so that coordinator-own idle
2208
+ // transitions are handled first.
2209
+ // Exception: a coordinator that is itself a direct-dispatch target still needs
2210
+ // to go through delegate routing so that the dispatching coordinator receives a
2211
+ // pendingCoordinatorEvents entry for the completion.
2212
+ if (event.event === 'agent:ready' || event.event === 'agent:generating_completed') {
2213
+ const flushInstanceId = readNonEmptyString(event.instanceId);
2214
+ if (flushInstanceId) {
2215
+ const flushSource = components.instanceManager.getInstance(flushInstanceId);
2216
+ if (flushSource && flushSource.category === 'cli') {
2217
+ const flushState = flushSource.getState();
2218
+ const flushSettings = flushState.settings && typeof flushState.settings === 'object' ? flushState.settings as Record<string, unknown> : {};
2219
+ const coordinatorMeshId = readNonEmptyString(flushSettings.meshCoordinatorFor);
2220
+ if (coordinatorMeshId) {
2221
+ const status = readNonEmptyString(flushState.status).toLowerCase();
2222
+ if (status === 'idle') {
2223
+ try {
2224
+ // Drain with the daemon's full coordinator-id set (status id + machineId).
2225
+ // The MCP layer stamps the prefixed status id (`standalone_<machineId>` /
2226
+ // `daemon_<machineId>`) as the worker's meshCoordinatorDaemonId; draining
2227
+ // with bare machineId alone would miss those unicast events. Mirrors
2228
+ // resolveCoordinatorDaemonIds in mesh-reconcile-loop.
2229
+ const drainDaemonIds = resolveCoordinatorDrainDaemonIds(components);
2230
+ const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
2231
+ if (pendingEvents.length > 0) {
2232
+ LOG.info('MeshEvents', `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
2233
+ for (const pending of pendingEvents) {
2234
+ if (!pending.coordinatorMessage) continue;
2235
+ const forcePending = shouldForceInjectMeshEvent(pending.event);
2236
+ flushSource.onEvent('send_message', {
2237
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
2238
+ ...(forcePending ? { force: true } : {}),
2239
+ });
2240
+ }
2241
+ }
2242
+ } catch (e: any) {
2243
+ LOG.warn('MeshEvents', `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
2244
+ }
2245
+ }
2246
+ // Skip delegate routing unless this coordinator session is itself
2247
+ // a direct-dispatch target — in that case fall through so the
2248
+ // dispatching coordinator gets a pendingCoordinatorEvents entry.
2249
+ let hasDirectDispatch = false;
2250
+ try {
2251
+ hasDirectDispatch =
2252
+ getActiveDirectDispatches(coordinatorMeshId).some(d => d.sessionId === flushInstanceId)
2253
+ || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
2254
+ } catch { /* best-effort */ }
2255
+ if (!hasDirectDispatch) return;
2256
+ }
2257
+ }
2258
+ }
2259
+ }
2260
+
2261
+ // --- Delegate event routing ---
2262
+ if (!isMeshCoordinatorEvent(event.event)) return;
2263
+
2264
+ const instanceId = readNonEmptyString(event.instanceId);
2265
+ if (!instanceId) return;
2266
+
2267
+ // R1: all session→node→mesh→coordinator interpretation is folded into the single
2268
+ // resolveWorkerDelegateRouting() resolver. No stamp (meshNodeFor / meshNodeId /
2269
+ // meshCoordinatorDaemonId / meshCoordinatorNodeId / launchedByCoordinator) is read
2270
+ // here to make a routing decision — the resolver is the one authority, and the
2271
+ // forwarder consumes its typed result only.
2272
+ const routing = resolveWorkerDelegateRouting(components, instanceId, {
2273
+ getMeshById: (meshId) => getMeshWithCache(components, meshId),
2274
+ getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace),
2275
+ });
2276
+ if (!routing.isDelegate) {
2277
+ // Fallback: a REMOTE worker that isn't a member of the coordinator's mesh can't
2278
+ // resolve a mesh id locally (mesh_unresolved), but it still carries the coordinator
2279
+ // daemon anchor. Forward the event straight to that coordinator over P2P instead of
2280
+ // dropping it — the coordinator hosts the mesh and recovers the id by workspace.
2281
+ if (isUnroutableDelegateRejection(routing)
2282
+ && forwardUnresolvedDelegateEvent(components, routing, event)) {
2283
+ return;
2284
+ }
2285
+ // R4: a worker that presented a valid envelope but resolved to no mesh (and could
2286
+ // not be fallback-forwarded — e.g. no coordinator anchor) used to be dropped
2287
+ // silently. Leave a fail-loud diagnostic so the missing completion is traceable.
2288
+ // Benign non-delegate rejections (not_cli / no_workspace / etc.) are no-ops inside
2289
+ // recordUnroutableDelegateEvent.
2290
+ recordUnroutableDelegateEvent(routing, event.event);
2291
+ return;
2292
+ }
2293
+
2294
+ injectMeshSystemMessage(components, {
2295
+ meshId: routing.meshId,
2296
+ sourceInstanceId: instanceId,
2297
+ nodeId: routing.nodeId,
2298
+ nodeLabel: routing.nodeLabel,
2299
+ event: event.event,
2300
+ metadataEvent: event,
2301
+ });
2302
+ });
2303
+ }