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

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