@adhdev/daemon-core 0.9.82-rc.36 → 0.9.82-rc.360

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