@adhdev/daemon-core 0.9.82-rc.32 → 0.9.82-rc.320

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