@adhdev/daemon-core 0.9.82-rc.31 → 0.9.82-rc.311

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