@adhdev/daemon-core 0.9.82-rc.46 → 0.9.82-rc.460

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 (439) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -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 +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +200 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +7 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +25 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +64 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +48 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +152 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router-refine.d.ts +137 -0
  56. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  57. package/dist/commands/router.d.ts +241 -12
  58. package/dist/commands/upgrade-helper.d.ts +41 -1
  59. package/dist/config/chat-history.d.ts +9 -0
  60. package/dist/config/config.d.ts +19 -0
  61. package/dist/config/mesh-config.d.ts +129 -1
  62. package/dist/config/mesh-json-config.d.ts +199 -0
  63. package/dist/config/registry-resolver.d.ts +54 -0
  64. package/dist/config/repo-settings.d.ts +77 -0
  65. package/dist/daemon/dev-server.d.ts +0 -2
  66. package/dist/detection/ide-detector.d.ts +13 -0
  67. package/dist/detection/win32-ide-version.d.ts +37 -0
  68. package/dist/git/change-impact-config.d.ts +159 -0
  69. package/dist/git/git-commands.d.ts +12 -1
  70. package/dist/git/git-diff.d.ts +6 -0
  71. package/dist/git/git-executor.d.ts +11 -0
  72. package/dist/git/git-status.d.ts +57 -0
  73. package/dist/git/git-types.d.ts +2 -50
  74. package/dist/git/git-worktree.d.ts +71 -1
  75. package/dist/git/index.d.ts +3 -1
  76. package/dist/index.d.ts +67 -15
  77. package/dist/index.js +57943 -25340
  78. package/dist/index.js.map +1 -1
  79. package/dist/index.mjs +57611 -25174
  80. package/dist/index.mjs.map +1 -1
  81. package/dist/installer.d.ts +1 -4
  82. package/dist/ipc/local-ipc-server.d.ts +91 -0
  83. package/dist/launch.d.ts +1 -1
  84. package/dist/logging/async-batch-writer.d.ts +10 -0
  85. package/dist/logging/debug-config.d.ts +16 -0
  86. package/dist/logging/log-redactor.d.ts +24 -0
  87. package/dist/logging/log-tail-reader.d.ts +81 -0
  88. package/dist/logging/logger.d.ts +1 -1
  89. package/dist/mesh/contracts.d.ts +230 -0
  90. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  91. package/dist/mesh/coordinator-registry.d.ts +59 -0
  92. package/dist/mesh/mesh-active-work.d.ts +174 -0
  93. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  94. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  95. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  96. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  97. package/dist/mesh/mesh-event-forwarding.d.ts +41 -0
  98. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  99. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  100. package/dist/mesh/mesh-events-pending.d.ts +113 -0
  101. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  102. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  103. package/dist/mesh/mesh-events.d.ts +6 -49
  104. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  105. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  106. package/dist/mesh/mesh-init.d.ts +128 -0
  107. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  108. package/dist/mesh/mesh-ledger.d.ts +133 -1
  109. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  110. package/dist/mesh/mesh-missions.d.ts +189 -0
  111. package/dist/mesh/mesh-node-identity.d.ts +306 -0
  112. package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
  113. package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
  114. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  115. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  116. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  117. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  118. package/dist/mesh/mesh-routing.d.ts +70 -0
  119. package/dist/mesh/mesh-runtime-store.d.ts +476 -0
  120. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  121. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  122. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  123. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  124. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  125. package/dist/mesh/mesh-work-queue.d.ts +318 -5
  126. package/dist/mesh/preview-freshness.d.ts +28 -0
  127. package/dist/mesh/refine-config.d.ts +216 -0
  128. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  129. package/dist/providers/acp-provider-instance.d.ts +5 -0
  130. package/dist/providers/approval-utils.d.ts +45 -0
  131. package/dist/providers/chat-message-normalization.d.ts +58 -1
  132. package/dist/providers/cli-provider-instance.d.ts +290 -3
  133. package/dist/providers/contracts.d.ts +149 -6
  134. package/dist/providers/external-sources.d.ts +71 -0
  135. package/dist/providers/manual-attendance.d.ts +79 -0
  136. package/dist/providers/native-history/antigravity-claim-registry.d.ts +28 -0
  137. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  138. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  139. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  140. package/dist/providers/native-history/constants.d.ts +12 -0
  141. package/dist/providers/native-history/dispatcher.d.ts +31 -0
  142. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  143. package/dist/providers/native-history/index.d.ts +13 -0
  144. package/dist/providers/provider-instance-manager.d.ts +29 -0
  145. package/dist/providers/provider-instance.d.ts +30 -1
  146. package/dist/providers/provider-loader.d.ts +42 -5
  147. package/dist/providers/provider-trust.d.ts +31 -0
  148. package/dist/providers/read-chat-contract.d.ts +29 -0
  149. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  150. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  151. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  152. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  153. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  154. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  155. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  156. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  157. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  158. package/dist/providers/sdk/v1/index.d.ts +30 -0
  159. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  160. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  161. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  162. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  163. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  164. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  165. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  166. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  167. package/dist/providers/spec/adapter.d.ts +98 -0
  168. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  169. package/dist/providers/spec/evaluator.d.ts +45 -0
  170. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  171. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  172. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  173. package/dist/providers/spec/fsm-types.d.ts +202 -0
  174. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  175. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  176. package/dist/providers/spec/route.d.ts +4 -0
  177. package/dist/providers/spec/types.d.ts +222 -0
  178. package/dist/providers/status-monitor.d.ts +7 -7
  179. package/dist/providers/transcript-v2.d.ts +176 -0
  180. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  181. package/dist/providers/working-dir.d.ts +17 -0
  182. package/dist/repo-mesh-types.d.ts +519 -13
  183. package/dist/runtime-defaults.d.ts +2 -0
  184. package/dist/session-host/managed-host.d.ts +64 -0
  185. package/dist/session-host/runtime-surface.d.ts +10 -16
  186. package/dist/sessions/registry.d.ts +6 -0
  187. package/dist/shared-types-extra.d.ts +2 -4
  188. package/dist/shared-types.d.ts +86 -55
  189. package/dist/status/normalize.d.ts +1 -1
  190. package/dist/status/normalize.js +1 -0
  191. package/dist/status/normalize.js.map +1 -1
  192. package/dist/status/normalize.mjs +1 -0
  193. package/dist/status/normalize.mjs.map +1 -1
  194. package/dist/status/reporter.d.ts +2 -0
  195. package/dist/status/snapshot.d.ts +26 -0
  196. package/dist/system/hash.d.ts +8 -0
  197. package/dist/system/load-better-sqlite3.d.ts +21 -0
  198. package/dist/types.d.ts +5 -0
  199. package/package.json +11 -4
  200. package/src/agent-stream/poller.ts +2 -3
  201. package/src/agent-stream/provider-adapter.ts +1 -1
  202. package/src/boot/daemon-lifecycle.ts +65 -12
  203. package/src/boot/process-hardening.ts +89 -0
  204. package/src/build-info.ts +73 -0
  205. package/src/chat/source-machine.ts +534 -0
  206. package/src/chat/source-resolver.ts +0 -0
  207. package/src/chat/subscription-updates.ts +20 -1
  208. package/src/cli-adapter-types.d.ts +3 -1
  209. package/src/cli-adapter-types.ts +68 -2
  210. package/src/cli-adapters/cli-script-runner.ts +421 -0
  211. package/src/cli-adapters/cli-state-engine.ts +1246 -0
  212. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  213. package/src/cli-adapters/provider-cli-adapter.ts +914 -1144
  214. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  215. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  216. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  217. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  218. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  219. package/src/cli-adapters/pty-transport.ts +2 -1
  220. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  221. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  222. package/src/cli-adapters/resolve-executable.ts +204 -0
  223. package/src/cli-adapters/session-host-transport.ts +2 -1
  224. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  225. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  226. package/src/cli-adapters/terminal-screen.ts +16 -81
  227. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  228. package/src/commands/chat-commands-read.ts +2488 -0
  229. package/src/commands/chat-commands-scope.ts +54 -0
  230. package/src/commands/chat-commands-shared.ts +114 -0
  231. package/src/commands/chat-commands-write.ts +891 -0
  232. package/src/commands/chat-commands.ts +19 -1841
  233. package/src/commands/cli-manager.ts +596 -27
  234. package/src/commands/handler.ts +845 -2
  235. package/src/commands/high-family/index.ts +28 -0
  236. package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
  237. package/src/commands/high-family/mesh-events.ts +89 -0
  238. package/src/commands/high-family/mesh-status.ts +822 -0
  239. package/src/commands/high-family/types.ts +80 -0
  240. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  241. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  242. package/src/commands/low-family/diagnostics.ts +57 -0
  243. package/src/commands/low-family/index.ts +37 -0
  244. package/src/commands/low-family/mesh-ledger.ts +62 -0
  245. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  246. package/src/commands/low-family/notification.ts +116 -0
  247. package/src/commands/low-family/refine-config.ts +106 -0
  248. package/src/commands/low-family/session-host.ts +274 -0
  249. package/src/commands/low-family/spec-providerdev.ts +217 -0
  250. package/src/commands/low-family/status-meta.ts +112 -0
  251. package/src/commands/low-family/types.ts +39 -0
  252. package/src/commands/med-family/cli-agent.ts +241 -0
  253. package/src/commands/med-family/fast-forward.ts +230 -0
  254. package/src/commands/med-family/ide.ts +163 -0
  255. package/src/commands/med-family/index.ts +37 -0
  256. package/src/commands/med-family/mesh-crud.ts +1287 -0
  257. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  258. package/src/commands/med-family/mesh-queue.ts +167 -0
  259. package/src/commands/med-family/mesh-restart.ts +92 -0
  260. package/src/commands/med-family/types.ts +153 -0
  261. package/src/commands/mesh-coordinator.ts +334 -124
  262. package/src/commands/router-refine.ts +1711 -0
  263. package/src/commands/router-worktree-cleanup.ts +870 -0
  264. package/src/commands/router.ts +1025 -4070
  265. package/src/commands/stream-commands.ts +8 -0
  266. package/src/commands/upgrade-helper.ts +310 -45
  267. package/src/config/chat-history.ts +493 -24
  268. package/src/config/config.ts +30 -0
  269. package/src/config/mesh-config.ts +619 -23
  270. package/src/config/mesh-json-config.ts +376 -0
  271. package/src/config/recent-activity.ts +8 -2
  272. package/src/config/registry-resolver.ts +100 -0
  273. package/src/config/repo-settings.ts +111 -0
  274. package/src/daemon/dev-auto-implement.ts +3 -2
  275. package/src/daemon/dev-cli-debug.ts +10 -1
  276. package/src/daemon/dev-server.ts +0 -541
  277. package/src/detection/cli-detector.ts +28 -9
  278. package/src/detection/ide-detector.ts +55 -16
  279. package/src/detection/win32-ide-version.ts +106 -0
  280. package/src/git/change-impact-config.ts +354 -0
  281. package/src/git/git-commands.ts +78 -15
  282. package/src/git/git-diff.ts +81 -11
  283. package/src/git/git-executor.ts +12 -0
  284. package/src/git/git-status.ts +767 -48
  285. package/src/git/git-types.ts +14 -62
  286. package/src/git/git-worktree.ts +261 -4
  287. package/src/git/index.ts +17 -0
  288. package/src/index.ts +200 -12
  289. package/src/installer.d.ts +1 -1
  290. package/src/installer.ts +8 -6
  291. package/src/ipc/local-ipc-server.ts +278 -0
  292. package/src/launch.d.ts +1 -1
  293. package/src/launch.ts +37 -28
  294. package/src/logging/async-batch-writer.ts +55 -0
  295. package/src/logging/command-log.ts +7 -5
  296. package/src/logging/debug-config.ts +25 -0
  297. package/src/logging/debug-trace.ts +7 -2
  298. package/src/logging/log-redactor.ts +100 -0
  299. package/src/logging/log-tail-reader.ts +341 -0
  300. package/src/logging/logger.ts +14 -7
  301. package/src/mesh/contracts.ts +469 -0
  302. package/src/mesh/coordinator-prompt.ts +536 -34
  303. package/src/mesh/coordinator-registry.ts +121 -0
  304. package/src/mesh/mesh-active-work.ts +656 -0
  305. package/src/mesh/mesh-clone-grace.ts +68 -0
  306. package/src/mesh/mesh-coordinator-config.ts +97 -0
  307. package/src/mesh/mesh-delivery-policy.ts +315 -0
  308. package/src/mesh/mesh-event-classify.ts +73 -0
  309. package/src/mesh/mesh-event-forwarding.ts +1932 -0
  310. package/src/mesh/mesh-event-trace.ts +67 -0
  311. package/src/mesh/mesh-events-coordinator.ts +32 -0
  312. package/src/mesh/mesh-events-pending.ts +766 -0
  313. package/src/mesh/mesh-events-stale.ts +440 -0
  314. package/src/mesh/mesh-events-utils.ts +443 -0
  315. package/src/mesh/mesh-events.ts +33 -1035
  316. package/src/mesh/mesh-fast-forward.ts +856 -0
  317. package/src/mesh/mesh-host-ownership.ts +111 -0
  318. package/src/mesh/mesh-init.ts +350 -0
  319. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  320. package/src/mesh/mesh-ledger.ts +873 -102
  321. package/src/mesh/mesh-magi-status.ts +223 -0
  322. package/src/mesh/mesh-missions.ts +449 -0
  323. package/src/mesh/mesh-node-identity.ts +1994 -0
  324. package/src/mesh/mesh-queue-assignment.ts +2233 -0
  325. package/src/mesh/mesh-reconcile-loop.ts +2390 -0
  326. package/src/mesh/mesh-refine-batch.ts +205 -0
  327. package/src/mesh/mesh-refine-gates.ts +1686 -0
  328. package/src/mesh/mesh-refine-status.ts +231 -0
  329. package/src/mesh/mesh-review-inbox.ts +308 -0
  330. package/src/mesh/mesh-routing.ts +291 -0
  331. package/src/mesh/mesh-runtime-store.ts +2026 -0
  332. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  333. package/src/mesh/mesh-task-inflight.ts +70 -0
  334. package/src/mesh/mesh-task-stats.ts +161 -0
  335. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  336. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  337. package/src/mesh/mesh-work-queue.ts +1281 -141
  338. package/src/mesh/preview-freshness.ts +163 -0
  339. package/src/mesh/refine-config.ts +423 -0
  340. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  341. package/src/providers/acp-provider-instance.ts +43 -10
  342. package/src/providers/approval-utils.d.ts +5 -0
  343. package/src/providers/approval-utils.ts +99 -5
  344. package/src/providers/chat-message-normalization.ts +126 -4
  345. package/src/providers/cli-provider-instance.ts +2456 -107
  346. package/src/providers/contracts.d.ts +55 -0
  347. package/src/providers/contracts.ts +160 -6
  348. package/src/providers/extension-provider-instance.ts +12 -7
  349. package/src/providers/external-sources.ts +218 -0
  350. package/src/providers/ide-provider-instance.ts +35 -12
  351. package/src/providers/manual-attendance.ts +105 -0
  352. package/src/providers/native-history/antigravity-claim-registry.ts +131 -0
  353. package/src/providers/native-history/antigravity-cli-transcript.ts +1193 -0
  354. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  355. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  356. package/src/providers/native-history/constants.ts +19 -0
  357. package/src/providers/native-history/dispatcher.ts +503 -0
  358. package/src/providers/native-history/hermes-cli-transcript.ts +260 -0
  359. package/src/providers/native-history/index.ts +30 -0
  360. package/src/providers/provider-instance-manager.ts +71 -0
  361. package/src/providers/provider-instance.ts +24 -1
  362. package/src/providers/provider-loader.ts +700 -55
  363. package/src/providers/provider-schema.ts +87 -14
  364. package/src/providers/provider-trust.ts +114 -0
  365. package/src/providers/read-chat-contract.ts +76 -16
  366. package/src/providers/sdk/README.md +49 -0
  367. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  368. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  369. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  370. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  371. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  372. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  373. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  374. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  375. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  376. package/src/providers/sdk/v1/index.ts +152 -0
  377. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  378. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  379. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  380. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  381. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  382. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  383. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  384. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  385. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  386. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  387. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  388. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  389. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  390. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  391. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  392. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  393. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  394. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  395. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  396. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  397. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  398. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  399. package/src/providers/sdk/v1/validators/index.ts +19 -0
  400. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  401. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  402. package/src/providers/spec/adapter.ts +246 -0
  403. package/src/providers/spec/cli-adapter.ts +1064 -0
  404. package/src/providers/spec/evaluator.ts +407 -0
  405. package/src/providers/spec/fsm-driver.ts +1528 -0
  406. package/src/providers/spec/fsm-evaluator.ts +290 -0
  407. package/src/providers/spec/fsm-loader.ts +128 -0
  408. package/src/providers/spec/fsm-types.ts +301 -0
  409. package/src/providers/spec/native-history-executor.ts +1174 -0
  410. package/src/providers/spec/pre-launch-trust.ts +104 -0
  411. package/src/providers/spec/route.ts +51 -0
  412. package/src/providers/spec/types.ts +262 -0
  413. package/src/providers/status-monitor.d.ts +7 -7
  414. package/src/providers/status-monitor.ts +37 -22
  415. package/src/providers/transcript-v2.ts +567 -0
  416. package/src/providers/types/interactive-prompt.ts +536 -0
  417. package/src/providers/version-archive.ts +64 -24
  418. package/src/providers/working-dir.ts +23 -0
  419. package/src/repo-mesh-types.ts +758 -14
  420. package/src/runtime-defaults.ts +39 -0
  421. package/src/session-host/managed-host.ts +218 -0
  422. package/src/session-host/runtime-surface.ts +20 -80
  423. package/src/sessions/registry.ts +6 -0
  424. package/src/shared-types-extra.ts +2 -4
  425. package/src/shared-types.d.ts +8 -0
  426. package/src/shared-types.ts +124 -55
  427. package/src/status/builders.ts +26 -6
  428. package/src/status/normalize.ts +2 -0
  429. package/src/status/reporter.ts +19 -1
  430. package/src/status/snapshot.ts +95 -26
  431. package/src/system/hash.ts +23 -0
  432. package/src/system/host-memory.ts +29 -12
  433. package/src/system/load-better-sqlite3.ts +68 -0
  434. package/src/types.ts +5 -0
  435. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  436. package/dist/mesh/mesh-sync.d.ts +0 -53
  437. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  438. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  439. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1932 @@
1
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
2
+ import { loadConfig } from '../config/config.js';
3
+ import { getMesh, getMeshByRepo, listMeshes } from '../config/mesh-config.js';
4
+ import { LOG } from '../logging/logger.js';
5
+ import { appendLedgerEntry, buildTaskCompletionEvidence, getSessionRecoveryContext, isIntentionalCleanupStopEntry, readLedgerEntries } from './mesh-ledger.js';
6
+ import type { SessionRecoveryContext } from './mesh-ledger.js';
7
+ import { updateSessionTaskStatus, enqueueTask, updateDirectDispatchStatus, cleanupTerminalDirectDispatches, getActiveDirectDispatches, hasPendingDependents, getQueue } from './mesh-work-queue.js';
8
+ import { markSessionDeliveriesTerminal, updateSessionDeliveryStatus, recordCompletionConflict } from './mesh-delivery-policy.js';
9
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
10
+ import { queuePendingMeshCoordinatorEvent, drainPendingMeshCoordinatorEvents, type PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
11
+ import type { ProviderInstance } from '../providers/provider-instance.js';
12
+ import { resolveWorkerDelegateRouting, recordUnroutableDelegateEvent, isUnroutableDelegateRejection } from './mesh-routing.js';
13
+ import { resolveMeshHostStatus } from './mesh-host-ownership.js';
14
+ import { enqueueUnresolvedDelegateForward, peekUnresolvedDelegateForwards, ackUnresolvedDelegateForward } from './mesh-unresolved-forward-outbox.js';
15
+ import { traceMeshEventStage, traceMeshEventDrop } from './mesh-event-trace.js';
16
+ import { getLastDisplayMessage } from '../status/snapshot.js';
17
+ import { resolveDelegatedWorkerAutoApprove } from '../repo-mesh-types.js';
18
+ import { meshNodeIdMatches, daemonIdsEquivalent, expandDaemonIdForms, sessionIdsEquivalent, type MeshNodeIdentified } from '@adhdev/mesh-shared';
19
+ import {
20
+ findRecentTerminalLedgerEvidence,
21
+ findTerminalLedgerEvidenceForTask,
22
+ hasDispatchAfterTerminal,
23
+ hasUnterminalDirectDispatchLedgerEntry,
24
+ buildNoProgressCompletionReconciliation,
25
+ } from './mesh-events-stale.js';
26
+ import { endTaskDispatchInFlight } from './mesh-task-inflight.js';
27
+ import {
28
+ buildMeshSystemMessage,
29
+ readNonEmptyString,
30
+ resolveEventSessionId,
31
+ readRefineJobId,
32
+ readWorkerResultMetadata,
33
+ resolveMeshSurfacedSessionPreview,
34
+ isFalseIdleCompletion,
35
+ isWeakCompletionEvidence,
36
+ } from './mesh-events-utils.js';
37
+ import { isMeshCoordinatorEvent, shouldForceInjectMeshEvent, EVENT_TO_LEDGER_KIND } from './mesh-event-classify.js';
38
+ import {
39
+ getMeshWithCache,
40
+ tryAssignQueueTask,
41
+ triggerMeshQueue,
42
+ runIdleMaintenanceThenAssignQueue,
43
+ maybeAutoFastForwardIdleNode,
44
+ sessionHasActiveAssignment,
45
+ } from './mesh-queue-assignment.js';
46
+
47
+ // The set of coordinator-daemon ids this daemon answers to when draining the
48
+ // pending-events queue. Mirrors resolveCoordinatorDaemonIds in mesh-reconcile-loop:
49
+ // a unicast event may be stamped with the status id, the bare machineId, OR the
50
+ // config-form node daemonId (`daemon_<machineId>`) depending on which dispatch path
51
+ // created the worker. We expand to EVERY equivalent form so a `daemon_<machineId>`
52
+ // completion matches a coordinator that knows itself as bare `<machineId>` (the
53
+ // base-node completion-surface bug) and vice versa.
54
+ function resolveCoordinatorDrainDaemonIds(components: DaemonComponents): string[] {
55
+ const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
56
+ const machineId = readNonEmptyString(loadConfig().machineId);
57
+ return expandDaemonIdForms([statusInstanceId, machineId]);
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // Remote Node Idle Session Tracking
62
+ // ---------------------------------------------------------------------------
63
+ const REMOTE_IDLE_SESSION_TTL_MS = 5 * 60 * 1000; // 5 minutes
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Workspace-to-mesh lookup cache
67
+ // ---------------------------------------------------------------------------
68
+ const meshByWorkspaceCache = new Map<string, { mesh: any; cachedAt: number }>();
69
+ const MESH_WORKSPACE_CACHE_TTL_MS = 5_000;
70
+
71
+ function getCachedMeshByWorkspace(workspace: string): any {
72
+ const now = Date.now();
73
+ const cached = meshByWorkspaceCache.get(workspace);
74
+ if (cached && now - cached.cachedAt < MESH_WORKSPACE_CACHE_TTL_MS) return cached.mesh;
75
+ const mesh = getMeshByRepo(workspace);
76
+ meshByWorkspaceCache.set(workspace, { mesh, cachedAt: now });
77
+ return mesh;
78
+ }
79
+
80
+ // Deterministic meshId recovery for a forwarded worker event that carries no meshId.
81
+ // An unresolved-mesh worker (forwardUnresolvedDelegateEvent) cannot resolve its own
82
+ // meshId locally, so it pushes the event with nodeId + workspace only and relies on
83
+ // the coordinator — which hosts the mesh — to recover the id. Workspace recovery
84
+ // (getCachedMeshByWorkspace → getMeshByRepo) is the fast path but can miss (a worktree
85
+ // clone whose repoIdentity differs, or a transient cache state), which left the retry
86
+ // permanently rejected with "meshId required". The node-id IS a stable, coordinator-side
87
+ // fact: scan the hosted meshes for the one whose node matches the forwarded nodeId
88
+ // (3-form normalizer). This is timing-independent and never depends on repo lookup.
89
+ function recoverMeshIdByNodeId(nodeId: string): string {
90
+ if (!nodeId) return '';
91
+ for (const mesh of listMeshes()) {
92
+ if (Array.isArray(mesh.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, nodeId))) {
93
+ return readNonEmptyString(mesh.id);
94
+ }
95
+ }
96
+ return '';
97
+ }
98
+
99
+ // MESHID-DROP coordinator-anchor recovery (Fix B): the last-resort meshId recovery for an
100
+ // unresolved-delegate forward whose payload carries the worker's coordinator anchor
101
+ // (meshCoordinatorDaemonId) but no resolvable meshId — neither workspace nor nodeId scan
102
+ // matched (a freshly-cloned worktree node not yet registered under the forwarded id form, or
103
+ // an empty payload nodeId). The receiving daemon IS the coordinator/host, so scope to the
104
+ // meshes IT hosts whose host daemon matches the anchor (daemonIdsEquivalent — never a raw
105
+ // compare, so daemon_mach_/mach_/standalone_ forms all match the same machine). Among those:
106
+ // • a nodeId → the mesh whose nodes contain it (meshNodeIdMatches 3-form) wins;
107
+ // • no nodeId → fall back to the anchor's SINGLE hosted mesh only. Ambiguity (the anchor
108
+ // hosts >1 mesh and no node disambiguates) returns '' rather than guess — a wrong meshId
109
+ // would inject the completion into an unrelated mesh's ledger, worse than the retry-cap drop.
110
+ export function recoverMeshIdByCoordinatorAndNode(coordinatorDaemonId: string, nodeId: string): string {
111
+ if (!coordinatorDaemonId) return '';
112
+ const hosted = listMeshes().filter(mesh => {
113
+ const host = resolveMeshHostStatus(mesh);
114
+ return host.role === 'host'
115
+ && (!host.hostDaemonId || daemonIdsEquivalent(host.hostDaemonId, coordinatorDaemonId));
116
+ });
117
+ if (hosted.length === 0) return '';
118
+ if (nodeId) {
119
+ const byNode = hosted.find(mesh =>
120
+ Array.isArray(mesh.nodes) && mesh.nodes.some((n: any) => meshNodeIdMatches(n, nodeId)));
121
+ if (byNode) return readNonEmptyString(byNode.id);
122
+ // nodeId present but matched no hosted mesh — do NOT fall through to the single-mesh
123
+ // guess; the node belongs to a mesh we don't host (or under a different id), and
124
+ // guessing would misroute. Stay unresolved.
125
+ return '';
126
+ }
127
+ // No nodeId to disambiguate: only safe when the anchor hosts exactly one mesh.
128
+ return hosted.length === 1 ? readNonEmptyString(hosted[0].id) : '';
129
+ }
130
+
131
+ // RECONCILE-MESHID-DROP: WORKER-side meshId resolution for an unresolved-delegate
132
+ // forward payload. forwardUnresolvedDelegateEvent omits meshId by design (the worker
133
+ // "can't resolve it") and relies on the COORDINATOR recovering it from workspace/nodeId.
134
+ // That recovery fails when the no_node_binding session's payload has an empty nodeId AND
135
+ // the coordinator's workspace→mesh lookup misses (a worktree clone whose repoIdentity
136
+ // differs / a cache miss) — leaving the reconcile retry rejected with "meshId required"
137
+ // every 4s forever. The worker actually has MORE context than the stripped payload gives
138
+ // the coordinator: it hosts the node as a member and holds the LIVE session, whose
139
+ // settings.meshNodeFor / meshNodeId are authoritative even when they were not stamped
140
+ // onto the original event. Resolve here (worker side) and stamp meshId onto the payload so
141
+ // the coordinator accepts it. Mirrors the receiver's recovery order, then adds the live-
142
+ // session fallback. Returns '' when even the worker cannot resolve it (truly unresolvable —
143
+ // the retry cap then drops it instead of looping). No side effects; safe to call per retry.
144
+ export function resolveForwardEventMeshId(
145
+ components: DaemonComponents,
146
+ payload: Record<string, unknown>,
147
+ ): string {
148
+ const direct = readNonEmptyString(payload.meshId);
149
+ if (direct) return direct;
150
+ const workspace = readNonEmptyString(payload.workspace);
151
+ const byWorkspace = workspace ? readNonEmptyString(getCachedMeshByWorkspace(workspace)?.id) : '';
152
+ if (byWorkspace) return byWorkspace;
153
+ const byNode = recoverMeshIdByNodeId(readNonEmptyString(payload.nodeId));
154
+ if (byNode) return byNode;
155
+ // Live-session fallback: the worker session may carry meshNodeFor / meshNodeId now even
156
+ // though the original event didn't (a late stamp, or an event that fired before binding).
157
+ const sessionId = readNonEmptyString(payload.targetSessionId)
158
+ || readNonEmptyString(payload.sessionId)
159
+ || readNonEmptyString(payload.instanceId);
160
+ if (sessionId) {
161
+ try {
162
+ const state = components.instanceManager?.getInstance?.(sessionId)?.getState?.();
163
+ const settings = (state?.settings as Record<string, unknown>) || {};
164
+ const meshNodeFor = readNonEmptyString(settings.meshNodeFor);
165
+ if (meshNodeFor) return meshNodeFor;
166
+ const byStamp = recoverMeshIdByNodeId(readNonEmptyString(settings.meshNodeId));
167
+ if (byStamp) return byStamp;
168
+ const sessionWorkspace = readNonEmptyString(state?.workspace);
169
+ const bySessionWorkspace = sessionWorkspace ? readNonEmptyString(getCachedMeshByWorkspace(sessionWorkspace)?.id) : '';
170
+ if (bySessionWorkspace) return bySessionWorkspace;
171
+ } catch { /* best-effort — fall through to unresolved */ }
172
+ }
173
+ return '';
174
+ }
175
+
176
+
177
+ export function __resetMeshWorkspaceCacheForTests(): void {
178
+ meshByWorkspaceCache.clear();
179
+ }
180
+
181
+ function sweepExpiredRemoteIdleSessions(): void {
182
+ try {
183
+ MeshRuntimeStore.getInstance().pruneExpiredRemoteIdleSessions();
184
+ } catch { /* best-effort */ }
185
+ }
186
+
187
+ const INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS = 30 * 60 * 1000;
188
+
189
+ function isIntentionalCleanupStopMetadata(event: Record<string, unknown>): boolean {
190
+ return event.intentional === true
191
+ || event.intentionalStop === true
192
+ || event.operatorCleanup === true
193
+ || event.reason === 'operator_cleanup'
194
+ || event.stopReason === 'operator_cleanup'
195
+ || event.cleanupReason === 'operator_cleanup'
196
+ || event.source === 'mesh_cleanup_sessions'
197
+ || event.source === 'mesh_remove_node';
198
+ }
199
+
200
+ function hasRecentIntentionalCleanupStop(meshId: string, sessionId?: string, nodeId?: string): boolean {
201
+ if (!sessionId && !nodeId) return false;
202
+ const cutoff = Date.now() - INTENTIONAL_CLEANUP_STOP_SUPPRESSION_MS;
203
+ const entries = readLedgerEntries(meshId, { tail: 200 });
204
+ for (let i = entries.length - 1; i >= 0; i--) {
205
+ const entry = entries[i];
206
+ const timestamp = new Date(entry.timestamp).getTime();
207
+ if (!Number.isNaN(timestamp) && timestamp < cutoff) break;
208
+ if (!isIntentionalCleanupStopEntry(entry)) continue;
209
+ // Session ids are single-form; sessionIdsEquivalent is the one canonical
210
+ // exact-match predicate (see its doc for why no form expansion is needed).
211
+ if (sessionId && sessionIdsEquivalent(entry.sessionId, sessionId)) return true;
212
+ // Normalized node-id match (P4): the cleanup-stop entry's node id may be stored as
213
+ // `nodeId` or `node_id` and the `nodeId` arg can be in either form — a raw `===`
214
+ // would miss a genuine intentional-cleanup entry and fail to suppress the stop event.
215
+ if (!sessionId && nodeId && meshNodeIdMatches(entry as unknown as MeshNodeIdentified, nodeId)) return true;
216
+ }
217
+ return false;
218
+ }
219
+
220
+ function shouldSuppressIntentionalCleanupStop(args: {
221
+ event: string;
222
+ meshId: string;
223
+ metadataEvent: Record<string, unknown>;
224
+ sessionId?: string;
225
+ nodeId?: string;
226
+ }): boolean {
227
+ if (args.event !== 'agent:stopped' && args.event !== 'monitor:no_progress') return false;
228
+ if (isIntentionalCleanupStopMetadata(args.metadataEvent)) return true;
229
+ return hasRecentIntentionalCleanupStop(args.meshId, args.sessionId, args.nodeId);
230
+ }
231
+
232
+ const RECENT_COMPLETION_FINGERPRINT_TTL_MS = 10 * 60 * 1000;
233
+
234
+ function hasFingerprintSeen(meshId: string, fingerprint: string): boolean {
235
+ try {
236
+ return MeshRuntimeStore.getInstance().hasCompletionFingerprint(meshId, fingerprint);
237
+ } catch {
238
+ return false;
239
+ }
240
+ }
241
+
242
+ function recordFingerprintSeen(meshId: string, fingerprint: string): void {
243
+ try {
244
+ const db = MeshRuntimeStore.getInstance();
245
+ db.recordCompletionFingerprint(meshId, fingerprint, RECENT_COMPLETION_FINGERPRINT_TTL_MS);
246
+ db.sweepExpiredFingerprints();
247
+ } catch { /* best-effort; duplicate events are preferable to a crash */ }
248
+ }
249
+
250
+ function readEventTimestamp(value: unknown): number | null {
251
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
252
+ if (typeof value === 'string' && value.trim()) {
253
+ const numeric = Number(value);
254
+ if (Number.isFinite(numeric)) return numeric;
255
+ const parsed = Date.parse(value);
256
+ if (Number.isFinite(parsed)) return parsed;
257
+ }
258
+ return null;
259
+ }
260
+
261
+ function buildMeshCompletionFingerprint(args: {
262
+ meshId: string;
263
+ event: string;
264
+ sessionId: string;
265
+ providerType?: string;
266
+ providerSessionId?: string;
267
+ timestamp?: number | null;
268
+ finalSummary?: string;
269
+ coordinatorDaemonId?: string;
270
+ }): string {
271
+ const timestampPart = Number.isFinite(args.timestamp)
272
+ ? String(args.timestamp)
273
+ : readNonEmptyString(args.finalSummary).slice(0, 200);
274
+ return [
275
+ args.meshId,
276
+ args.event,
277
+ args.sessionId,
278
+ args.providerType || '',
279
+ args.providerSessionId || '',
280
+ timestampPart,
281
+ args.coordinatorDaemonId || '',
282
+ ].join('::');
283
+ }
284
+
285
+ function isDuplicateMeshCompletionEvent(args: {
286
+ meshId: string;
287
+ event: string;
288
+ sessionId: string;
289
+ providerType?: string;
290
+ providerSessionId?: string;
291
+ timestamp?: number | null;
292
+ finalSummary?: string;
293
+ coordinatorDaemonId?: string;
294
+ taskId?: string;
295
+ nodeId?: string;
296
+ }): boolean {
297
+ const fingerprint = buildMeshCompletionFingerprint(args);
298
+ if (!fingerprint) return false;
299
+ if (hasFingerprintSeen(args.meshId, fingerprint)) {
300
+ if (args.taskId) {
301
+ recordCompletionConflict({
302
+ meshId: args.meshId,
303
+ fingerprint,
304
+ conflictingTaskId: args.taskId,
305
+ conflictingSessionId: args.sessionId,
306
+ event: args.event,
307
+ });
308
+ }
309
+ return true;
310
+ }
311
+ recordFingerprintSeen(args.meshId, fingerprint);
312
+ return false;
313
+ }
314
+
315
+ function isDuplicateMeshApprovalEvent(args: {
316
+ meshId: string;
317
+ sessionId: string;
318
+ providerType?: string;
319
+ timestamp?: number | null;
320
+ modalMessage?: string;
321
+ modalButtons?: unknown;
322
+ }): boolean {
323
+ const modalButtons = Array.isArray(args.modalButtons)
324
+ ? args.modalButtons.map(button => String(button).trim()).filter(Boolean)
325
+ : [];
326
+ const approvalIdentity = Number.isFinite(args.timestamp)
327
+ ? String(args.timestamp)
328
+ : JSON.stringify({ message: args.modalMessage || '', buttons: modalButtons });
329
+ if (!approvalIdentity || approvalIdentity === '{"message":"","buttons":[]}') return false;
330
+ const fingerprint = [
331
+ args.meshId,
332
+ 'agent:waiting_approval',
333
+ args.sessionId,
334
+ args.providerType || '',
335
+ approvalIdentity,
336
+ ].join('::');
337
+ if (hasFingerprintSeen(args.meshId, fingerprint)) return true;
338
+ recordFingerprintSeen(args.meshId, fingerprint);
339
+ return false;
340
+ }
341
+
342
+ function isDuplicateRefineTerminalEvent(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): boolean {
343
+ const jobId = readRefineJobId({ metadataEvent });
344
+ const fingerprint = jobId && new Set(['refine:completed', 'refine:failed']).has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
345
+ if (!fingerprint) return false;
346
+ if (hasFingerprintSeen(meshId, fingerprint)) return true;
347
+ recordFingerprintSeen(meshId, fingerprint);
348
+ return false;
349
+ }
350
+
351
+ // NOTIF-MISS (FIX 2): the set of `source` tags the transcript-reconcile synthesis path stamps
352
+ // onto the terminal ledger entry it writes (mesh-events-stale.reconcileDirectDispatchCompletion
353
+ // FromTranscript). A terminal carrying one of these was NOT produced by an actual provider
354
+ // agent_status_event — it is a coordinator-side reconstruction from the worker's transcript. The
355
+ // authoritative real completion must never be permanently masked by such a synthesized record.
356
+ const RECONCILED_COMPLETION_SOURCES = new Set([
357
+ 'direct_task_transcript_reconciliation',
358
+ 'daemon_reconcile_transcript_completion',
359
+ 'mcp_mesh_status_transcript_reconciliation',
360
+ 'no_progress_reconciliation',
361
+ ]);
362
+
363
+ // True when the recorded terminal ledger entry was SYNTHESIZED by transcript reconciliation
364
+ // rather than emitted by the real provider event. The reconcile path tags its ledger payload
365
+ // with a reconcile `source`; a genuine provider completion carries no such tag (or a normal
366
+ // completionDiagnostic.reason). Both the explicit source AND the diagnostic reason are checked so
367
+ // either carrier identifies the synthesized record.
368
+ function isSynthesizedReconciledTerminal(terminalPayload: Record<string, unknown>): boolean {
369
+ const source = readNonEmptyString(terminalPayload.source);
370
+ if (source && RECONCILED_COMPLETION_SOURCES.has(source)) return true;
371
+ const diagnostic = terminalPayload.completionDiagnostic;
372
+ if (diagnostic && typeof diagnostic === 'object' && !Array.isArray(diagnostic)) {
373
+ const reason = readNonEmptyString((diagnostic as Record<string, unknown>).reason);
374
+ if (reason && RECONCILED_COMPLETION_SOURCES.has(reason)) return true;
375
+ }
376
+ return false;
377
+ }
378
+
379
+ // True when the INCOMING completion event is a REAL provider agent_status_event (an actual
380
+ // agent:generating_completed from the live session) rather than itself a synthesized/reconciled
381
+ // re-injection. We must only let a real event override a synthesized terminal — a second
382
+ // synthesized re-arrival should still dedup normally. A real provider event carries no reconcile
383
+ // `source` tag; a re-injected reconciliation does.
384
+ function isRealProviderCompletionEvent(metadataEvent: Record<string, unknown>): boolean {
385
+ const source = readNonEmptyString(metadataEvent.source);
386
+ return !source || !RECONCILED_COMPLETION_SOURCES.has(source);
387
+ }
388
+
389
+ // The genuine-completion counterpart: a real final summary / worker result is present and
390
+ // the completion is not flagged as a missing-final-assistant false idle. Used to decide
391
+ // whether a new completion may supersede a prior WEAK (false-idle) terminal. NOTE this gates
392
+ // only on isFalseIdleCompletion (the completionDiagnostic subset), NOT the broader
393
+ // isWeakCompletionEvidence — preserving the original semantics where a self-declared
394
+ // weak/insufficient event still counts as genuine if it carries a real final summary.
395
+ function isGenuineCompletionEvidence(metadataEvent: Record<string, unknown>): boolean {
396
+ if (isFalseIdleCompletion(metadataEvent)) return false;
397
+ return !!readWorkerResultMetadata(metadataEvent) || !!readNonEmptyString(metadataEvent.finalSummary);
398
+ }
399
+
400
+ // (FALSEIDLE-BGCHILD-b) A later genuine completion of the SAME task that carries a
401
+ // substantively different — and fuller — final summary than the recorded terminal is the REAL
402
+ // final that an earlier (false-idle) completion pre-empted, not a duplicate. The background-child
403
+ // false idle is the nasty case the plain isWeakCompletionEvidence supersession misses: the
404
+ // early completion's screen parser DID see a prior/intermediate standard assistant, so it is
405
+ // recorded as a STRONG terminal with a non-empty (but truncated) finalSummary. Without this the
406
+ // providerSessionId/finalSummary dedup below swallows the genuine final and the coordinator is
407
+ // stuck with the truncated mid-turn text forever (the one-shot-consumption symptom). Same-task,
408
+ // new event is genuine, prior terminal summary is a strict prefix of (or otherwise shorter than)
409
+ // the new one → treat as the corrected final and let it through. Conservative: requires the new
410
+ // summary to be genuine evidence AND meaningfully longer, so an identical re-arrival or a SHORTER
411
+ // later summary is still deduped.
412
+ function supersedesTruncatedTerminalSummary(args: {
413
+ terminalPayload: Record<string, unknown>;
414
+ metadataEvent: Record<string, unknown>;
415
+ terminalTaskId: string;
416
+ eventTaskId: string;
417
+ }): boolean {
418
+ // Only applies when both name the SAME task (a distinct task is handled by distinctTaskCompletion).
419
+ if (!args.terminalTaskId || !args.eventTaskId || args.terminalTaskId !== args.eventTaskId) return false;
420
+ if (!isGenuineCompletionEvidence(args.metadataEvent)) return false;
421
+ const terminalSummary = readNonEmptyString(args.terminalPayload.finalSummary);
422
+ const eventSummary = readNonEmptyString(args.metadataEvent.finalSummary);
423
+ if (!eventSummary) return false;
424
+ // Identical text → genuine duplicate, keep deduping.
425
+ if (terminalSummary === eventSummary) return false;
426
+ // The recorded terminal was a known-weak (false-idle) one → already handled by the weak
427
+ // supersession path; nothing extra to do here.
428
+ if (isWeakCompletionEvidence(args.terminalPayload)) return false;
429
+ // No prior summary at all, or the new summary strictly extends / is meaningfully longer than
430
+ // the recorded one → the recorded terminal was the truncated pre-emption; supersede it.
431
+ if (!terminalSummary) return true;
432
+ if (eventSummary.startsWith(terminalSummary)) return true;
433
+ return eventSummary.length > terminalSummary.length + 32;
434
+ }
435
+
436
+ // The latest still-active direct-dispatch taskId for a session, resolved BEFORE the
437
+ // completion flips the dispatch row terminal. Direct dispatches (mesh_send_task) have no
438
+ // work-queue row, so this is the only taskId available to attribute the terminal ledger
439
+ // entry (and thus mesh task-stats) to — without it the terminal carries no taskId and the
440
+ // task surfaces as status='unknown' / terminalKind=null in computeMeshTaskStats.
441
+ function resolveActiveDirectDispatchTaskId(meshId: string, sessionId: string): string | undefined {
442
+ try {
443
+ // Session ids are single-form; sessionIdsEquivalent is the one canonical
444
+ // exact-match predicate — no node-id-style form normalization needed.
445
+ const matches = getActiveDirectDispatches(meshId).filter(d => sessionIdsEquivalent(d.sessionId, sessionId));
446
+ if (!matches.length) return undefined;
447
+ // getActiveDirectDispatches returns rows ordered by dispatched_at ASC; the last is
448
+ // the most recent dispatch (the re-dispatch / nudge whose completion this is).
449
+ return readNonEmptyString(matches[matches.length - 1].taskId) || undefined;
450
+ } catch {
451
+ return undefined;
452
+ }
453
+ }
454
+
455
+ // Coordinator-side suppression/reconcile gate for an incoming mesh event. Each clause is a
456
+ // closed dedup/suppression concern that only inspects the event + already-resolved context and
457
+ // either (a) returns a `suppress` result the caller forwards verbatim, (b) returns a `reconcile`
458
+ // signal carrying the rewritten metadataEvent for the caller to re-inject as
459
+ // agent:generating_completed, or (c) returns null to let the event fall through to the
460
+ // terminal/ledger machinery. Extracted verbatim from injectMeshSystemMessage — no behavior
461
+ // change; the only side effects (best-effort remote-idle cleanup, LOG, trace) fire on the same
462
+ // paths as before.
463
+ function evaluateMeshEventSuppression(
464
+ args: {
465
+ meshId: string;
466
+ sourceInstanceId?: string;
467
+ nodeId?: string;
468
+ nodeLabel: string;
469
+ event: string;
470
+ metadataEvent: Record<string, unknown>;
471
+ },
472
+ ctx: {
473
+ traceCtx: Parameters<typeof traceMeshEventDrop>[1];
474
+ eventSessionId: string;
475
+ eventNodeId: string;
476
+ eventTimestamp: number | null;
477
+ workerCoordinatorDaemonId: string | undefined;
478
+ },
479
+ ):
480
+ | { kind: 'suppress'; result: { success: true; forwarded: 0; suppressed: true; [extra: string]: unknown } }
481
+ | { kind: 'reconcile'; metadataEvent: Record<string, unknown> }
482
+ | null {
483
+ const { traceCtx, eventSessionId, eventNodeId, eventTimestamp, workerCoordinatorDaemonId } = ctx;
484
+
485
+ const intentionalCleanupStop = shouldSuppressIntentionalCleanupStop({
486
+ event: args.event,
487
+ meshId: args.meshId,
488
+ metadataEvent: args.metadataEvent,
489
+ sessionId: eventSessionId || undefined,
490
+ nodeId: eventNodeId || undefined,
491
+ });
492
+ if (intentionalCleanupStop) {
493
+ if (eventSessionId && eventNodeId) {
494
+ try {
495
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(args.meshId, eventNodeId, eventSessionId);
496
+ } catch { /* best-effort */ }
497
+ }
498
+ LOG.info('MeshEvents', `Suppressed ${args.event} for intentionally cleanup-stopped session ${eventSessionId || '(unknown session)'}`);
499
+ traceMeshEventDrop('intentional_cleanup_stop', traceCtx);
500
+ return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, intentionalCleanupStop: true } };
501
+ }
502
+
503
+ if (args.event === 'monitor:no_progress') {
504
+ const reconciledCompletion = buildNoProgressCompletionReconciliation({
505
+ meshId: args.meshId,
506
+ nodeId: args.nodeId,
507
+ nodeLabel: args.nodeLabel,
508
+ metadataEvent: args.metadataEvent,
509
+ sourceInstanceId: args.sourceInstanceId,
510
+ });
511
+ if (reconciledCompletion?.source === 'no_progress_reconciliation') {
512
+ LOG.info('MeshEvents', `Reconciled no-progress monitor to completion for session ${eventSessionId || '(unknown session)'}`);
513
+ return { kind: 'reconcile', metadataEvent: reconciledCompletion };
514
+ }
515
+ if (reconciledCompletion?.source === 'no_progress_terminal_ledger_suppression') {
516
+ LOG.info('MeshEvents', `Suppressed no-progress monitor because terminal ledger evidence already exists for session ${eventSessionId || '(unknown session)'}`);
517
+ traceMeshEventDrop('no_progress_terminal_ledger_suppression', traceCtx, `terminalKind=${reconciledCompletion.terminalLedgerKind}`);
518
+ return {
519
+ kind: 'suppress',
520
+ result: {
521
+ success: true,
522
+ forwarded: 0,
523
+ suppressed: true,
524
+ terminalLedgerEvidence: true,
525
+ terminalLedgerKind: reconciledCompletion.terminalLedgerKind,
526
+ },
527
+ };
528
+ }
529
+ }
530
+
531
+ if (isDuplicateRefineTerminalEvent(args.meshId, args.event, args.metadataEvent)) {
532
+ LOG.info('MeshEvents', `Suppressed duplicate ${args.event} for refine job ${readRefineJobId({ metadataEvent: args.metadataEvent })}`);
533
+ traceMeshEventDrop('duplicate_refine_terminal', traceCtx);
534
+ return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateRefineTerminalEvent: true } };
535
+ }
536
+
537
+ if (args.event === 'agent:waiting_approval' && eventSessionId) {
538
+ const duplicateApproval = isDuplicateMeshApprovalEvent({
539
+ meshId: args.meshId,
540
+ sessionId: eventSessionId,
541
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
542
+ timestamp: eventTimestamp,
543
+ modalMessage: readNonEmptyString(args.metadataEvent.modalMessage) || undefined,
544
+ modalButtons: args.metadataEvent.modalButtons,
545
+ });
546
+ if (duplicateApproval) {
547
+ LOG.info('MeshEvents', `Suppressed duplicate approval event for mesh ${args.meshId} session ${eventSessionId}`);
548
+ traceMeshEventDrop('duplicate_approval', traceCtx);
549
+ return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateApproval: true } };
550
+ }
551
+ }
552
+ if (args.event === 'agent:generating_completed' && eventSessionId) {
553
+ const terminal = findRecentTerminalLedgerEvidence({
554
+ meshId: args.meshId,
555
+ sessionId: eventSessionId,
556
+ nodeId: eventNodeId || undefined,
557
+ });
558
+ if (terminal?.kind === 'task_completed' && !sessionHasActiveAssignment(args.meshId, eventSessionId)) {
559
+ const newDispatchAfterTerminal = hasDispatchAfterTerminal(args.meshId, eventSessionId, terminal.id);
560
+ // Fix B (re-dispatch 2nd-completion routing): a prior terminal recorded from a FALSE
561
+ // idle (weak evidence / no confirmed final assistant) must NOT permanently suppress a
562
+ // later GENUINE completion of the same session. providerSessionId is stable across a
563
+ // session's turns, so the providerSessionId/finalSummary dedup below would otherwise
564
+ // swallow the real 2nd-turn completion that a coordinator nudge (direct re-dispatch)
565
+ // drove — exactly the missed-event bug. When the prior terminal was weak and the new
566
+ // event carries genuine completion evidence, let it through so it is recorded and
567
+ // re-attributed to the latest task (the normal task_completed path below).
568
+ const supersedesWeakTerminal = isWeakCompletionEvidence(terminal.payload)
569
+ && isGenuineCompletionEvidence(args.metadataEvent);
570
+ // CANON-B (direct-dispatch completion race): a FAST direct dispatch (mesh_send_task)
571
+ // to an already-idle, previously-used session can have its genuine completion reach
572
+ // this coordinator handler BEFORE the dispatching side records the new task's dispatch
573
+ // row / task_dispatched ledger entry — insertDirectDispatch + appendLedgerEntry both run
574
+ // AFTER the agent_command await resolves, while the worker may already be done. In that
575
+ // window sessionHasActiveAssignment is false (no active dispatch row, no unterminal
576
+ // ledger entry yet), so this prior-terminal dedup engages; and because providerSessionId
577
+ // is STABLE across a reused session's turns, the providerSessionId/finalSummary match
578
+ // below would suppress the NEW task's completion as a duplicate of the PRIOR task —
579
+ // silently losing it (the observed intermittent miss; fresh enqueue/autoLaunch is immune
580
+ // because a fresh session has no prior same-providerSessionId terminal and the queue row
581
+ // is claimed atomically before dispatch). The echoed taskId is the authoritative
582
+ // discriminator: when the completion names a DIFFERENT task than the recorded terminal,
583
+ // it is a genuinely new task's completion, never a duplicate — let it through so it is
584
+ // attributed to its own taskId. A same-task re-arrival (taskId equal) or a taskId-less
585
+ // legacy event still falls through to the providerSessionId/finalSummary dedup.
586
+ const terminalTaskId = readNonEmptyString(terminal.payload.taskId);
587
+ const eventTaskId = readNonEmptyString(args.metadataEvent.taskId);
588
+ const distinctTaskCompletion = !!eventTaskId && !!terminalTaskId && eventTaskId !== terminalTaskId;
589
+ // (FALSEIDLE-BGCHILD-b) Same-task genuine completion carrying a fuller summary than the
590
+ // recorded (truncated, false-idle-pre-empted) terminal supersedes it — see helper.
591
+ const supersedesTruncatedTerminal = supersedesTruncatedTerminalSummary({
592
+ terminalPayload: terminal.payload,
593
+ metadataEvent: args.metadataEvent,
594
+ terminalTaskId,
595
+ eventTaskId,
596
+ });
597
+ // NOTIF-MISS (FIX 2): the recorded terminal was SYNTHESIZED by transcript reconciliation
598
+ // (no real provider event), and THIS incoming event is the authoritative REAL provider
599
+ // completion. The reconcile path may fire ~1s after a direct dispatch from a reused
600
+ // session's stale transcript tail, writing a synthesized terminal whose providerSessionId
601
+ // (stable across a session's turns) and/or finalSummary then match the real completion —
602
+ // so the providerSessionId/finalSummary dedup below would drop the genuine event and the
603
+ // coordinator would never learn the task finished. A synthesized record must NEVER
604
+ // permanently mask the real completion: let the real event through (it is re-recorded by
605
+ // the normal task_completed path, superseding the synthesized one). A second SYNTHESIZED
606
+ // re-arrival is NOT a real event and still dedups normally.
607
+ // RECONCILE-SYNTH-PREEMPTS-COMPLETION: the bar here is deliberately LOWER than the
608
+ // weak/truncated supersessions above — a synthesized terminal is a coordinator-side
609
+ // reconstruction, never a real provider event, so ANY genuine real provider completion
610
+ // for the session must win over it. Requiring the full isGenuineCompletionEvidence
611
+ // (finalSummary OR workerResult present) dropped the real event whenever the relay did
612
+ // not re-populate finalSummary at this layer — exactly the observed 71s task whose real
613
+ // generating_completed hit drop:duplicate_completion_terminal_ledger after a premature
614
+ // synth. We require only that the incoming event is a REAL provider completion that is
615
+ // not itself a false idle (missing-final-assistant); a real-but-false-idle event still
616
+ // does not supersede (it is not trustworthy terminal evidence either).
617
+ const supersedesSynthesizedTerminal = isSynthesizedReconciledTerminal(terminal.payload)
618
+ && isRealProviderCompletionEvent(args.metadataEvent)
619
+ && !isFalseIdleCompletion(args.metadataEvent);
620
+ if (!newDispatchAfterTerminal && !supersedesWeakTerminal && !distinctTaskCompletion && !supersedesTruncatedTerminal && !supersedesSynthesizedTerminal) {
621
+ const terminalProviderSessionId = readNonEmptyString(terminal.payload.providerSessionId);
622
+ const terminalFinalSummary = readNonEmptyString(terminal.payload.finalSummary);
623
+ const eventProviderSessionId = readNonEmptyString(args.metadataEvent.providerSessionId);
624
+ const eventFinalSummary = readNonEmptyString(args.metadataEvent.finalSummary);
625
+ if (
626
+ (terminalProviderSessionId && terminalProviderSessionId === eventProviderSessionId)
627
+ || (terminalFinalSummary && terminalFinalSummary === eventFinalSummary)
628
+ || args.metadataEvent.source === 'no_progress_reconciliation'
629
+ ) {
630
+ LOG.info('MeshEvents', `Suppressed duplicate completion with existing terminal ledger evidence for mesh ${args.meshId} session ${eventSessionId}`);
631
+ traceMeshEventDrop('duplicate_completion_terminal_ledger', traceCtx);
632
+ return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true, terminalLedgerEvidence: true } };
633
+ }
634
+ }
635
+ }
636
+ const duplicateCompletion = isDuplicateMeshCompletionEvent({
637
+ meshId: args.meshId,
638
+ event: args.event,
639
+ sessionId: eventSessionId,
640
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
641
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
642
+ timestamp: eventTimestamp,
643
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
644
+ coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
645
+ taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
646
+ nodeId: eventNodeId || undefined,
647
+ });
648
+ if (duplicateCompletion) {
649
+ LOG.info('MeshEvents', `Suppressed duplicate completion for mesh ${args.meshId} session ${eventSessionId}`);
650
+ traceMeshEventDrop('duplicate_completion', traceCtx);
651
+ return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateCompletion: true } };
652
+ }
653
+ }
654
+ if (args.event === 'agent:stopped' && eventSessionId) {
655
+ const duplicateStopped = isDuplicateMeshCompletionEvent({
656
+ meshId: args.meshId,
657
+ event: args.event,
658
+ sessionId: eventSessionId,
659
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
660
+ providerSessionId: readNonEmptyString(args.metadataEvent.providerSessionId) || undefined,
661
+ timestamp: eventTimestamp,
662
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
663
+ coordinatorDaemonId: workerCoordinatorDaemonId || undefined,
664
+ taskId: readNonEmptyString(args.metadataEvent.taskId) || undefined,
665
+ nodeId: eventNodeId || undefined,
666
+ });
667
+ if (duplicateStopped) {
668
+ LOG.info('MeshEvents', `Suppressed duplicate stopped event for mesh ${args.meshId} session ${eventSessionId}`);
669
+ traceMeshEventDrop('duplicate_stopped', traceCtx);
670
+ return { kind: 'suppress', result: { success: true, forwarded: 0, suppressed: true, duplicateStopped: true } };
671
+ }
672
+ }
673
+
674
+ return null;
675
+ }
676
+
677
+ function injectMeshSystemMessage(components: DaemonComponents, args: {
678
+ meshId: string;
679
+ sourceInstanceId?: string;
680
+ nodeId?: string;
681
+ nodeLabel: string;
682
+ event: string;
683
+ metadataEvent: Record<string, unknown>;
684
+ }) {
685
+ const eventSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
686
+ const eventNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
687
+
688
+ // EVTTRACE correlation context for this event's coordinator-side lifecycle (queue /
689
+ // dedup / suppress). Observation only — never read by any decision below.
690
+ const traceCtx = {
691
+ taskId: args.metadataEvent.taskId,
692
+ sessionId: eventSessionId,
693
+ nodeId: eventNodeId,
694
+ meshId: args.meshId,
695
+ event: args.event,
696
+ };
697
+
698
+ const sourceSession = args.sourceInstanceId
699
+ ? components.instanceManager.getInstance(args.sourceInstanceId)
700
+ : undefined;
701
+ const workerCoordinatorDaemonId = readNonEmptyString(
702
+ (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorDaemonId,
703
+ );
704
+ // Session-level routing anchor (multi-coordinator). Prefer the LIVE worker session's
705
+ // stamp; fall back to a relayed value carried in metadataEvent.meshCoordinatorSessionId
706
+ // (a remote worker's completion arrives via handleMeshForwardEvent with no local
707
+ // sourceSession, so the stamp can only ride in the relayed metadata). Empty on legacy /
708
+ // version-skewed dispatches → the event stays daemon-broadcast (no regression).
709
+ const workerCoordinatorSessionId = readNonEmptyString(
710
+ (sourceSession?.getState()?.settings as Record<string, unknown>)?.meshCoordinatorSessionId,
711
+ ) || readNonEmptyString(args.metadataEvent.meshCoordinatorSessionId);
712
+
713
+ // T2: a summary-less completion (and any non-completion status-sync event) carries no
714
+ // assistant text on the event, so resolveMeshSurfacedSessionPreview had nothing to surface
715
+ // and the coordinator's inbox mirror stayed stuck on the first dispatched user task. When
716
+ // THIS daemon hosts the live worker instance (sourceSession present), derive the worker's
717
+ // latest display message straight from its transcript and attach it to the event as
718
+ // lastMessagePreview/lastMessageRole/lastMessageAt. resolveMeshSurfacedSessionPreview reads
719
+ // these as an assistant-only fallback; they also ride the pending-queue + P2P relay
720
+ // (handleMeshForwardEvent whitelist) so a remote coordinator can surface them. A remote
721
+ // coordinator has no local instance and keeps relying on the relayed fields — unchanged.
722
+ const enrichedMetadataEvent = ((): Record<string, unknown> => {
723
+ const last = sourceSession ? getLastDisplayMessage(sourceSession.getState()) : null;
724
+ const base = (!last || !last.preview)
725
+ ? args.metadataEvent
726
+ : {
727
+ ...args.metadataEvent,
728
+ lastMessagePreview: last.preview,
729
+ lastMessageRole: last.role,
730
+ ...(last.receivedAt > 0 ? { lastMessageAt: last.receivedAt } : {}),
731
+ };
732
+ // MAGI: stamp the queue task's consensusGroupId onto the completion metadata
733
+ // so the intentional-fan-out dedup exemption (buildPendingEventFingerprint)
734
+ // can see it. The work queue is owned by THIS host/coordinator daemon — where
735
+ // both the lookup and the dedup run — so the local lookup covers local and
736
+ // relayed workers alike. Best-effort: never fail the event path on a miss, and
737
+ // never clobber a consensusGroupId the worker already relayed.
738
+ if (readNonEmptyString((base as Record<string, unknown>).consensusGroupId)) return base;
739
+ const eventTaskId = readNonEmptyString(args.metadataEvent.taskId);
740
+ if (!eventTaskId) return base;
741
+ try {
742
+ const entry = MeshRuntimeStore.getInstance().findQueueEntryById(args.meshId, eventTaskId);
743
+ const consensusGroupId = readNonEmptyString((entry as { consensusGroupId?: unknown } | null)?.consensusGroupId);
744
+ if (consensusGroupId) return { ...base, consensusGroupId };
745
+ } catch { /* queue lookup is best-effort; absence just falls back to the generic fingerprint */ }
746
+ return base;
747
+ })();
748
+
749
+ // R2: cloud P2P dashboard metadata sync. The cloud daemon used to do this from its own
750
+ // relay listener; now the single core forwarder invokes the injected hook (no-op on
751
+ // standalone) so the event path stays single-listener and the local code path is identical
752
+ // across standalone and cloud.
753
+ if (components.onMeshCoordinatorEventForwarded) {
754
+ try {
755
+ // T: the coordinator surfaces a remote worker's session but holds no local
756
+ // instance for it, so the status snapshot can't derive a preview and the
757
+ // mirror would stay stuck on the first dispatched user task. Resolve the
758
+ // worker's latest assistant reply (carried on the completion event's
759
+ // finalSummary / workerResult) into a preview the mirror can stamp, so the
760
+ // mobile inbox reflects the assistant response. Completion events carry assistant
761
+ // text as finalSummary; a summary-less completion / status sync falls back to the
762
+ // worker's latest assistant display message (enrichedMetadataEvent.lastMessage*).
763
+ // For a mid-turn user-only event this is undefined and the prior surfaced preview
764
+ // is preserved downstream (no clobber).
765
+ const surfacedPreview = resolveMeshSurfacedSessionPreview(enrichedMetadataEvent);
766
+ components.onMeshCoordinatorEventForwarded({
767
+ event: args.event,
768
+ meshId: args.meshId,
769
+ nodeId: eventNodeId || undefined,
770
+ ...enrichedMetadataEvent,
771
+ // Ensure a `workspace` field reaches updateMeshOwnedSession even when the
772
+ // worker provider event only carried `workspaceName`. The merge spread of
773
+ // metadataEvent above wins when it already has a non-empty `workspace`.
774
+ workspace: readNonEmptyString(args.metadataEvent.workspace)
775
+ || readNonEmptyString(args.metadataEvent.workspaceName)
776
+ || undefined,
777
+ ...(surfacedPreview ? {
778
+ meshSessionLastMessagePreview: surfacedPreview.preview,
779
+ meshSessionLastMessageRole: surfacedPreview.role,
780
+ meshSessionLastMessageAt: surfacedPreview.receivedAt || undefined,
781
+ } : {}),
782
+ });
783
+ } catch { /* dashboard metadata sync is best-effort */ }
784
+ }
785
+
786
+ const eventTimestamp = readEventTimestamp(args.metadataEvent.timestamp);
787
+ // Coordinator-side dedup/suppression gate (extracted, behavior-preserving). A non-null
788
+ // outcome either short-circuits with a forwarded result or signals a no-progress→completion
789
+ // reconciliation that we re-inject; null lets the event fall through to the ledger machinery.
790
+ const suppression = evaluateMeshEventSuppression(args, {
791
+ traceCtx,
792
+ eventSessionId,
793
+ eventNodeId,
794
+ eventTimestamp,
795
+ workerCoordinatorDaemonId,
796
+ });
797
+ if (suppression) {
798
+ if (suppression.kind === 'reconcile') {
799
+ return injectMeshSystemMessage(components, {
800
+ ...args,
801
+ event: 'agent:generating_completed',
802
+ metadataEvent: suppression.metadataEvent,
803
+ });
804
+ }
805
+ return suppression.result;
806
+ }
807
+
808
+ function markSessionTerminal(sessionId: string, outcome: 'completed' | 'failed', occurredAtMs?: number | null, opts?: { tentativeIfDirect?: boolean }): { id?: string } | null {
809
+ // C2: prefer an exact taskId match when the completion event carries one —
810
+ // it's immune to coordinator↔worker clock skew that can hide the assigned row.
811
+ const eventTaskId = readNonEmptyString(args.metadataEvent.taskId) || undefined;
812
+ const task = updateSessionTaskStatus(args.meshId, sessionId, outcome, {
813
+ occurredAt: occurredAtMs != null ? new Date(occurredAtMs).toISOString() : undefined,
814
+ taskId: eventTaskId,
815
+ });
816
+ // Fix A (early-terminal prevention): a false-idle completion (no confirmed final
817
+ // assistant) for a DIRECT dispatch — i.e. no work-queue row matched — must not flip the
818
+ // dispatch row terminal. Leaving it active lets the reconcile loop (PHASE 4) re-read the
819
+ // transcript and record the genuine completion once the worker truly finishes (commonly
820
+ // after a coordinator nudge / re-dispatch). A matched queue task, or a completion with
821
+ // genuine evidence, is marked terminal as before.
822
+ // WARMUPGAP: a no-taskId completion from a session that holds no active assignment is a
823
+ // pre-assignment warmup / ghost event (a worker spawns, idles, and emits idle→generating→
824
+ // completed before any task is dispatched, with meshActiveTaskId unset so the event carries
825
+ // no taskId). Letting it through would hit the session_id fallback in updateDirectDispatchStatus
826
+ // and flip a sibling/stale dispatch row this event does not own — the real task later lands on
827
+ // a corrupted row and never reaches completed. Skip the dispatch update for that case. A
828
+ // taskId-carrying completion (real task), or any completion whose session currently holds an
829
+ // active assignment (legacy/relayed worker), still flips as before.
830
+ const leaveDirectDispatchActive = (!task && opts?.tentativeIfDirect === true)
831
+ || (!eventTaskId && !sessionHasActiveAssignment(args.meshId, sessionId));
832
+ if (!leaveDirectDispatchActive) {
833
+ // CANON-B: flip the exact dispatch row the completion echoed its taskId for; the
834
+ // session_id fallback (no echoed taskId) still covers legacy/relayed workers.
835
+ updateDirectDispatchStatus(args.meshId, sessionId, outcome, eventTaskId);
836
+ }
837
+ markSessionDeliveriesTerminal(args.meshId, sessionId, outcome);
838
+ // COMPLETION-PROPAGATION F2 (double safety net): the flip found no matching assigned
839
+ // row (task === null) but the completion echoed a taskId AND a queue row for that id is
840
+ // STILL 'assigned'. This is the stranded flip-miss case F1's equivalence match is meant
841
+ // to reconcile — NOT a direct dispatch (which legitimately has no queue row and is
842
+ // covered by updateDirectDispatchStatus above). Record a terminal ledger entry keyed by
843
+ // the echoed taskId and release the single-flight lock, so the reconcile PHASE 2.5
844
+ // terminal-ledger branch (findTerminalLedgerEvidenceForTask by row.id) has a taskId-based
845
+ // path to flip the stranded row terminal even if the direct SQL flip could not resolve
846
+ // it, and a subsequent reclaim/requeue is not blocked by a stale in-flight mark. Gated
847
+ // to GENUINE terminals (a weak / false-idle completion is left for the transcript
848
+ // reconcile, matching the leaveDirectDispatchActive philosophy above).
849
+ const genuineTerminal = outcome === 'failed' || !isWeakCompletionEvidence(args.metadataEvent);
850
+ if (!task && eventTaskId && genuineTerminal) {
851
+ try {
852
+ const strandedRow = MeshRuntimeStore.getInstance().findQueueEntryById(args.meshId, eventTaskId);
853
+ if (strandedRow && strandedRow.status === 'assigned') {
854
+ endTaskDispatchInFlight(args.meshId, eventTaskId);
855
+ if (!findTerminalLedgerEvidenceForTask({ meshId: args.meshId, taskId: eventTaskId })) {
856
+ appendLedgerEntry(args.meshId, {
857
+ kind: outcome === 'completed' ? 'task_completed' : 'task_failed',
858
+ sessionId,
859
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined,
860
+ providerType: readNonEmptyString(args.metadataEvent.providerType) || undefined,
861
+ payload: {
862
+ taskId: eventTaskId,
863
+ event: args.event,
864
+ source: 'flip_miss_safety_net',
865
+ finalSummary: readNonEmptyString(args.metadataEvent.finalSummary) || undefined,
866
+ },
867
+ });
868
+ }
869
+ }
870
+ } catch { /* best-effort safety net — never fail the completion path */ }
871
+ }
872
+ setImmediate(() => cleanupTerminalDirectDispatches());
873
+ return task ? { id: task.id } : null;
874
+ }
875
+
876
+ let completedTaskForLedger: { id?: string } | null = null;
877
+ // Fix B: direct-dispatch taskId used to attribute the terminal ledger entry when no
878
+ // work-queue row matches (resolved BEFORE markSessionTerminal flips the dispatch terminal).
879
+ let directDispatchTaskIdForLedger: string | undefined;
880
+ // BOOTSTRAP-MSG: whether a queued task already targets this node, so the
881
+ // worktree_bootstrap_complete [System] message reflects the auto-claim instead of
882
+ // advising a manual mesh_launch_session (which would spawn a duplicate session).
883
+ let worktreeHasQueuedTask = false;
884
+ if (args.event === 'agent:generating_completed') {
885
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
886
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
887
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
888
+
889
+ if (sessionId) {
890
+ // CANON-B / ARCH-REFACTOR R1: trust the taskId the completion echoed. With R1's
891
+ // per-turn identity binding the worker stamps the COMPLETING turn's own taskId
892
+ // (not the racy session scalar), so the echoed id is authoritative and this is
893
+ // the path that should always be taken for an R1+ worker. The most-recent-by-
894
+ // session heuristic (resolveActiveDirectDispatchTaskId) is retained ONLY as a
895
+ // backward-compat fallback for legacy / version-skewed workers that carry no
896
+ // taskId — it is the very re-derive R1 exists to make unnecessary, and must not
897
+ // override a present echoed id, hence the `||` short-circuit order.
898
+ directDispatchTaskIdForLedger = readNonEmptyString(args.metadataEvent.taskId)
899
+ || resolveActiveDirectDispatchTaskId(args.meshId, sessionId);
900
+ // A false-idle completion of a direct dispatch is recorded but kept tentative (the
901
+ // dispatch row stays active for the reconcile fallback); a genuine completion is terminal.
902
+ const isFalseIdle = isFalseIdleCompletion(args.metadataEvent);
903
+ completedTaskForLedger = markSessionTerminal(sessionId, 'completed', eventTimestamp, { tentativeIfDirect: isFalseIdle });
904
+ if (nodeId && providerType) {
905
+ // OVEREAGER-REMOTE-IDLE (Defect A+B): re-register the now-idle remote session into
906
+ // the remote-idle store, symmetric with the agent:ready branch. Previously
907
+ // setRemoteIdleSession ran ONLY on agent:ready, while agent:generating_started
908
+ // DELETES the entry — so the FIRST turn a remote worker runs permanently evicts it
909
+ // from the store, and generating_completed never re-added it. A later
910
+ // mesh_enqueue_task's triggerMeshQueue then read getRemoteIdleSessions() == 0
911
+ // (remoteIdleSessionsChecked:0) for a session that is genuinely live-idle, needlessly
912
+ // auto-launching a second worker (Defect A). Worse, the two idle-session sources then
913
+ // disagreed: the enqueue drain saw 0 (store empty) and auto-launched + left the queue
914
+ // task pending, while THIS completing session's runIdleMaintenanceThenAssignQueue
915
+ // claimed the same still-pending row straight from SQL — so the task body injected into
916
+ // BOTH the reused idle session and the auto-launched one (Defect B). Re-registering here
917
+ // unifies the source: the next triggerMeshQueue drain sees the live idle session, reuses
918
+ // it (claimed:true, no auto-launch), and injects exactly once. Skip a false-idle
919
+ // (mid-turn / no-final-assistant) completion — that session is NOT genuinely idle.
920
+ if (!isFalseIdle) {
921
+ sweepExpiredRemoteIdleSessions();
922
+ try {
923
+ MeshRuntimeStore.getInstance().setRemoteIdleSession(args.meshId, nodeId, sessionId, providerType, Date.now() + REMOTE_IDLE_SESSION_TTL_MS);
924
+ } catch { /* best-effort */ }
925
+ setImmediate(() => {
926
+ maybeAutoFastForwardIdleNode(components, { meshId: args.meshId, nodeId, sessionId, providerType })
927
+ .finally(() => {
928
+ try {
929
+ // Claim for THIS session first; on success drop the just-registered
930
+ // idle entry so the enqueue drain doesn't re-pick an already-busy session.
931
+ const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
932
+ if (assigned) MeshRuntimeStore.getInstance().deleteRemoteIdleSession(args.meshId, nodeId, sessionId);
933
+ } catch (e: any) {
934
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after completion for ${nodeId}: ${e?.message || e}`);
935
+ }
936
+ });
937
+ });
938
+ } else {
939
+ runIdleMaintenanceThenAssignQueue(components, { meshId: args.meshId, nodeId, sessionId, providerType });
940
+ }
941
+ }
942
+ // M1-3: wake dependents of the completed task. The maintenance path above
943
+ // only assigns to the completing session; dependents may be claimable by
944
+ // other idle sessions, so run a full queue trigger when any are waiting.
945
+ const completedTaskId = completedTaskForLedger?.id;
946
+ if (completedTaskId && hasPendingDependents(args.meshId, completedTaskId)) {
947
+ setImmediate(() => {
948
+ triggerMeshQueue(components, args.meshId).catch((e: any) => {
949
+ LOG.warn('MeshQueue', `Dependent wake after task ${completedTaskId} failed: ${e?.message || e}`);
950
+ });
951
+ });
952
+ }
953
+ }
954
+ } else if (args.event === 'agent:ready') {
955
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
956
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
957
+ const providerType = readNonEmptyString(args.metadataEvent.providerType);
958
+ const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
959
+ const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
960
+ const workerResult = readWorkerResultMetadata(args.metadataEvent);
961
+ const hasCompletionEvidence = !!finalSummary || !!workerResult;
962
+ if (sessionId && hasCompletionEvidence) {
963
+ completedTaskForLedger = markSessionTerminal(sessionId, 'completed');
964
+ if (completedTaskForLedger) {
965
+ try {
966
+ appendLedgerEntry(args.meshId, {
967
+ kind: 'task_completed',
968
+ nodeId: nodeId || undefined,
969
+ sessionId,
970
+ providerType: providerType || undefined,
971
+ payload: {
972
+ event: args.event,
973
+ nodeLabel: args.nodeLabel,
974
+ taskId: completedTaskForLedger.id,
975
+ completedViaReady: true,
976
+ providerSessionId,
977
+ finalSummary,
978
+ workerResult,
979
+ evidence: buildTaskCompletionEvidence({
980
+ event: 'agent:ready',
981
+ nodeId,
982
+ sessionId,
983
+ providerType: providerType || undefined,
984
+ providerSessionId,
985
+ finalSummary,
986
+ workerResult,
987
+ }),
988
+ },
989
+ });
990
+ } catch (e: any) {
991
+ LOG.warn('MeshLedger', `Failed to record task_completed from ready: ${e?.message || e}`);
992
+ }
993
+ }
994
+ }
995
+
996
+ if (sessionId && nodeId && providerType) {
997
+ // WORKTREE-BOOTSTRAP-DISPATCH-RACE: a freshly cloned worktree session emits
998
+ // agent:ready as soon as the CLI process reaches its idle prompt — which happens
999
+ // BEFORE the worktree bootstrap (npm install + native-addon repair: node-datachannel,
1000
+ // better-sqlite3, ghostty-vt-node) has finished. Claiming a queued task on that early
1001
+ // ready dispatches work into a session whose runtime is half-built: the child daemon
1002
+ // dies loading the absent native addon → the worker session boots empty (no task ever
1003
+ // injected), the queue row reports assigned-but-dead, and the work silently leaks to /
1004
+ // gets re-routed onto the base node. Live evidence (the OPSRULES dispatch): node
1005
+ // node_6df455dd emitted agent:ready at 10:36:28 but worktree_bootstrap_complete only at
1006
+ // 10:36:56 — a 28s window in which a claim produced an empty session.
1007
+ //
1008
+ // Gate the claim on bootstrap state: if this node is a worktree whose bootstrap is still
1009
+ // 'running', register the idle session (so it stays a claim candidate) but DEFER the
1010
+ // claim. The claim re-fires on the next agent:ready / reconcile drain tick once bootstrap
1011
+ // reaches a terminal state. 'failed' is left to flow through unchanged — a failed
1012
+ // bootstrap surfaces its own coordinator event and a dispatch there fails loudly rather
1013
+ // than silently, which is the correct, visible behavior (deferring forever would hide it).
1014
+ let worktreeBootstrapPending = false;
1015
+ try {
1016
+ const mesh = getMeshWithCache(components, args.meshId);
1017
+ const node = mesh?.nodes?.find((n: any) => meshNodeIdMatches(n, nodeId)) as { worktreeBootstrap?: { status?: string } } | undefined;
1018
+ worktreeBootstrapPending = node?.worktreeBootstrap?.status === 'running';
1019
+ } catch { /* best-effort: unknown bootstrap state → do not defer (prior behavior) */ }
1020
+
1021
+ sweepExpiredRemoteIdleSessions();
1022
+ try {
1023
+ MeshRuntimeStore.getInstance().setRemoteIdleSession(args.meshId, nodeId, sessionId, providerType, Date.now() + REMOTE_IDLE_SESSION_TTL_MS);
1024
+ } catch { /* best-effort */ }
1025
+ if (worktreeBootstrapPending) {
1026
+ LOG.info('MeshQueue', `Deferring queue claim for worktree node ${nodeId} (${sessionId}): worktree bootstrap still running — early agent:ready precedes bootstrap completion; the idle session is registered and the claim will re-fire once bootstrap finishes (guards against dispatching into a half-built worktree → empty session / work leaking to the base node)`);
1027
+ } else {
1028
+ setImmediate(() => {
1029
+ maybeAutoFastForwardIdleNode(components, { meshId: args.meshId, nodeId, sessionId, providerType })
1030
+ .finally(() => {
1031
+ try {
1032
+ const assigned = tryAssignQueueTask(components, args.meshId, nodeId, sessionId, providerType);
1033
+ if (assigned) MeshRuntimeStore.getInstance().deleteRemoteIdleSession(args.meshId, nodeId, sessionId);
1034
+ } catch (e: any) {
1035
+ LOG.warn('MeshQueue', `Failed to assign idle queue task after maintenance for ${nodeId}: ${e?.message || e}`);
1036
+ }
1037
+ });
1038
+ });
1039
+ }
1040
+ }
1041
+ } else if (args.event === 'agent:generating_started') {
1042
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1043
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1044
+ if (sessionId && nodeId) {
1045
+ try {
1046
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(args.meshId, nodeId, sessionId);
1047
+ } catch { /* best-effort */ }
1048
+ }
1049
+ if (sessionId) {
1050
+ // CANON-B: a generating_started that echoes its taskId acks exactly the dispatch
1051
+ // and the delivery for THAT task — not every in-flight dispatch/delivery on the
1052
+ // session. A session that already holds a freshly-dispatched (still 'dispatched')
1053
+ // sibling must keep that row 'dispatched' so its own confirm can match it; acking
1054
+ // by session would mark it 'acked' prematurely and hide a genuine non-delivery.
1055
+ const startedTaskId = readNonEmptyString(args.metadataEvent.taskId) || undefined;
1056
+ // WARMUPGAP: only ack a dispatch row when the event names its task, or the session
1057
+ // currently holds an active assignment. A no-taskId generating_started from an
1058
+ // unassigned session is a pre-assignment warmup — the session_id fallback would ack a
1059
+ // sibling/stale dispatch row this event does not own, marking it 'acked' prematurely and
1060
+ // hiding a genuine non-delivery. Skip the dispatch ack for that ghost case (the delivery
1061
+ // acks below are bound to actual deliveries and stay a no-op for a warmup session).
1062
+ //
1063
+ // MESH-DISPATCH-MISROUTE (fix 3, consumer residual): when the event carries no taskId
1064
+ // (a legacy/relayed worker whose producer never stamped meshActiveTaskId) but the
1065
+ // session owns EXACTLY ONE active dispatch, resolve that row's taskId and flip it by PK
1066
+ // instead of the session_id sweep — the sweep flips every non-terminal row for the
1067
+ // session ("may flip a sibling dispatch row"). With ≥2 active rows the owner is
1068
+ // ambiguous, so resolvedAckTaskId stays undefined and we DROP the ack rather than
1069
+ // mis-flip a sibling (the genuine ack arrives once the producer/reconcile names a task).
1070
+ if (startedTaskId) {
1071
+ updateDirectDispatchStatus(args.meshId, sessionId, 'acked', startedTaskId);
1072
+ } else if (sessionHasActiveAssignment(args.meshId, sessionId)) {
1073
+ const soleTaskId = (() => {
1074
+ try { return MeshRuntimeStore.getInstance().getSoleActiveDirectDispatchTaskId(args.meshId, sessionId); }
1075
+ catch { return null; }
1076
+ })();
1077
+ if (soleTaskId) {
1078
+ updateDirectDispatchStatus(args.meshId, sessionId, 'acked', soleTaskId);
1079
+ }
1080
+ }
1081
+ const activeDeliveries = ((): { id: string; taskId: string | null }[] => {
1082
+ try { return MeshRuntimeStore.getInstance().getActiveSessionDeliveries(args.meshId, sessionId); }
1083
+ catch { return []; }
1084
+ })();
1085
+ const deliveriesToAck = startedTaskId
1086
+ ? activeDeliveries.filter(d => d.taskId === startedTaskId)
1087
+ : activeDeliveries;
1088
+ for (const d of deliveriesToAck) {
1089
+ updateSessionDeliveryStatus(d.id, 'acked');
1090
+ }
1091
+ }
1092
+ } else if (args.event === 'agent:stopped') {
1093
+ const sessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId);
1094
+ const nodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1095
+ if (sessionId && nodeId) {
1096
+ try {
1097
+ MeshRuntimeStore.getInstance().deleteRemoteIdleSession(args.meshId, nodeId, sessionId);
1098
+ } catch { /* best-effort */ }
1099
+ }
1100
+ if (sessionId) {
1101
+ // CANON-B: prefer the echoed taskId; session heuristic is the fallback.
1102
+ directDispatchTaskIdForLedger = readNonEmptyString(args.metadataEvent.taskId)
1103
+ || resolveActiveDirectDispatchTaskId(args.meshId, sessionId);
1104
+ completedTaskForLedger = markSessionTerminal(sessionId, 'failed');
1105
+ }
1106
+ } else if (args.event === 'worktree_bootstrap_complete' || args.event === 'worktree_bootstrap_failed') {
1107
+ // WORKTREE-BOOTSTRAP-REFIRE: the agent:ready branch above DEFERS the queue claim while
1108
+ // worktreeBootstrap.status === 'running' — a freshly cloned worktree emits agent:ready at
1109
+ // its idle prompt BEFORE bootstrap finishes, and dispatching then produces a half-built
1110
+ // session. The defer registers the idle session (setRemoteIdleSession) but schedules NO
1111
+ // retry; it relies on "the next agent:ready / reconcile drain tick" to re-fire. But
1112
+ // agent:ready is a one-shot (emitAgentReadyOnce, guarded by agentReadyEmitted) and the
1113
+ // session stays idle→idle after bootstrap, so no new agent:ready edge ever fires → the
1114
+ // deferred claim is stranded → the worker session boots empty (totalMessages=0) and the
1115
+ // coordinator relaunch/stop-loops. Re-fire the queue drain on the terminal bootstrap
1116
+ // transition: the idle session registered at defer time is now claimable (tryAssignQueueTask
1117
+ // has no bootstrap gate of its own). This runs on whichever daemon processes the event —
1118
+ // the local worker (when it co-hosts the coordinator) at emit time, or the remote
1119
+ // coordinator after it pulls the queued event — so the registered local/remote idle session
1120
+ // is drained in every topology. 'failed' is re-fired too so a deferred-then-failed bootstrap
1121
+ // dispatches and fails loudly/visibly rather than stranding silently. Falls through to the
1122
+ // coordinator broadcast below — the bootstrap event is still delivered to the coordinator.
1123
+ // WORKTREE-BOOTSTRAP-COORD-STATE: stamp the terminal bootstrap status onto the
1124
+ // COORDINATOR's mesh view BEFORE re-firing the queue. The clone+bootstrap ran on
1125
+ // the worker daemon (clone_mesh_node forwards to the source node's machine), so
1126
+ // persistWorktreeSetupState only flipped status→'complete' on the worker's mesh
1127
+ // object — the coordinator still holds the 'running' state it stamped from the
1128
+ // forwarded clone reply. Without this, the claim gate (agent:ready defer above +
1129
+ // mesh-queue-assignment) reads getMeshWithCache, sees 'running' forever, and
1130
+ // defers every claim — so this very re-fire loops against a gate that never opens
1131
+ // (claim never lands; idle session re-registered each tick; auto-launch spawns a
1132
+ // fresh session every cycle → runaway worktree-session multiplication). Stamping
1133
+ // the terminal state opens the gate so the deferred claim lands on this re-fire.
1134
+ const bootstrapNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId);
1135
+ if (bootstrapNodeId) {
1136
+ try {
1137
+ // Fix (3): pass the worktree path so a hydrate-on-miss upsert (when this
1138
+ // coordinator never received the clone reply) can seed an addressable node.
1139
+ const bootstrapWorkspace = readNonEmptyString(args.metadataEvent.worktreePath)
1140
+ || readNonEmptyString(args.metadataEvent.workspace);
1141
+ (components.router as any)?.markWorktreeBootstrapTerminalState?.(
1142
+ args.meshId,
1143
+ bootstrapNodeId,
1144
+ args.event === 'worktree_bootstrap_failed' ? 'failed' : 'complete',
1145
+ bootstrapWorkspace ? { workspace: bootstrapWorkspace } : undefined,
1146
+ );
1147
+ } catch (e: any) {
1148
+ LOG.warn('MeshQueue', `Failed to stamp terminal bootstrap state for ${bootstrapNodeId} (mesh ${args.meshId}): ${e?.message || e}`);
1149
+ }
1150
+ }
1151
+ // BOOTSTRAP-MSG: detect whether the queue re-fire below has a task to auto-claim for
1152
+ // this node BEFORE setImmediate(triggerMeshQueue) runs — at this point a deferred task
1153
+ // is still 'pending' (it has not been claimed yet); 'assigned' covers a task already
1154
+ // claimed by an earlier tick. Either case means a session is being/has been spun up by
1155
+ // the queue, so the completion message must NOT advise a manual mesh_launch_session.
1156
+ // Only meaningful for the 'complete' transition (a failed bootstrap claims nothing).
1157
+ if (args.event === 'worktree_bootstrap_complete' && bootstrapNodeId) {
1158
+ try {
1159
+ worktreeHasQueuedTask = getQueue(args.meshId, { status: ['pending', 'assigned'] })
1160
+ .some((task) => meshNodeIdMatches({ id: task.targetNodeId } as MeshNodeIdentified, bootstrapNodeId));
1161
+ } catch (e: any) {
1162
+ LOG.warn('MeshQueue', `Failed to check queued task for ${bootstrapNodeId} (mesh ${args.meshId}): ${e?.message || e}`);
1163
+ }
1164
+ }
1165
+ setImmediate(() => {
1166
+ triggerMeshQueue(components, args.meshId).catch((e: any) => {
1167
+ LOG.warn('MeshQueue', `Queue re-fire after ${args.event} failed (mesh ${args.meshId}): ${e?.message || e}`);
1168
+ });
1169
+ });
1170
+ }
1171
+
1172
+ const ledgerKind = EVENT_TO_LEDGER_KIND[args.event];
1173
+ if (ledgerKind) {
1174
+ try {
1175
+ const ledgerNodeId = readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined;
1176
+ const ledgerSessionId = resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined;
1177
+ const ledgerProviderType = readNonEmptyString(args.metadataEvent.providerType) || undefined;
1178
+ const providerSessionId = readNonEmptyString(args.metadataEvent.providerSessionId) || undefined;
1179
+ const finalSummary = readNonEmptyString(args.metadataEvent.finalSummary) || undefined;
1180
+ const workerResult = readWorkerResultMetadata(args.metadataEvent);
1181
+ const completionEvidence = ledgerKind === 'task_completed' && ledgerNodeId && ledgerSessionId
1182
+ ? buildTaskCompletionEvidence({
1183
+ event: 'agent:generating_completed',
1184
+ nodeId: ledgerNodeId,
1185
+ sessionId: ledgerSessionId,
1186
+ providerType: ledgerProviderType,
1187
+ providerSessionId,
1188
+ finalSummary,
1189
+ workerResult,
1190
+ })
1191
+ : undefined;
1192
+ appendLedgerEntry(args.meshId, {
1193
+ kind: ledgerKind,
1194
+ nodeId: ledgerNodeId,
1195
+ sessionId: ledgerSessionId,
1196
+ providerType: ledgerProviderType,
1197
+ payload: {
1198
+ event: args.event,
1199
+ nodeLabel: args.nodeLabel,
1200
+ // Fix B: fall back to the direct-dispatch taskId when no work-queue row
1201
+ // matched, so the terminal entry is attributable in mesh task-stats
1202
+ // (otherwise the direct task shows status='unknown' / terminalKind=null).
1203
+ taskId: completedTaskForLedger?.id || directDispatchTaskIdForLedger || undefined,
1204
+ providerSessionId,
1205
+ finalSummary,
1206
+ workerResult,
1207
+ completionDiagnostic: args.metadataEvent.completionDiagnostic && typeof args.metadataEvent.completionDiagnostic === 'object'
1208
+ ? args.metadataEvent.completionDiagnostic
1209
+ : undefined,
1210
+ evidence: completionEvidence,
1211
+ // B2: evidenceLevel lets coordinator know when completion evidence is insufficient.
1212
+ // NOTIF Defect-2b: ONLY source==='default' (no parseable answer at all) is
1213
+ // 'insufficient'. 'parseable_answer' (a real JSON answer that just isn't
1214
+ // worker-result-shaped, e.g. a MAGI envelope) is concrete evidence and must
1215
+ // resolve to 'sufficient' — resolveWorkerResult now upgrades that case so a
1216
+ // complete, valid answer is no longer mislabelled insufficient/reviewRecommended.
1217
+ ...(completionEvidence
1218
+ ? completionEvidence.workerResult.source === 'default'
1219
+ ? { evidenceLevel: 'insufficient', reviewRecommended: true }
1220
+ : { evidenceLevel: 'sufficient' }
1221
+ : {}),
1222
+ },
1223
+ });
1224
+ } catch (e: any) {
1225
+ LOG.warn('MeshLedger', `Failed to record ${ledgerKind}: ${e?.message || e}`);
1226
+ }
1227
+ }
1228
+
1229
+ let recoveryContext: SessionRecoveryContext | null = null;
1230
+ if (args.event === 'agent:stopped') {
1231
+ try {
1232
+ const mesh = getMesh(args.meshId);
1233
+ const maxRetries = mesh?.policy?.maxTaskRetries ?? 1;
1234
+
1235
+ recoveryContext = getSessionRecoveryContext(args.meshId, {
1236
+ sessionId: resolveEventSessionId(args.metadataEvent, args.sourceInstanceId) || undefined,
1237
+ nodeId: readNonEmptyString(args.nodeId) || readNonEmptyString(args.metadataEvent.meshNodeId) || undefined,
1238
+ maxRetries,
1239
+ });
1240
+ recoveryContext.failedProviderType = readNonEmptyString(args.metadataEvent.providerType) || null;
1241
+
1242
+ if (recoveryContext.retryRecommended && recoveryContext.consecutiveNodeFailures > 0) {
1243
+ appendLedgerEntry(args.meshId, {
1244
+ kind: 'recovery_attempted',
1245
+ nodeId: recoveryContext.failedNodeId || undefined,
1246
+ sessionId: recoveryContext.failedSessionId || undefined,
1247
+ providerType: recoveryContext.failedProviderType || undefined,
1248
+ payload: {
1249
+ consecutiveFailures: recoveryContext.consecutiveNodeFailures,
1250
+ taskAttemptCount: recoveryContext.taskAttemptCount,
1251
+ retryRecommended: recoveryContext.retryRecommended,
1252
+ advice: recoveryContext.advice,
1253
+ },
1254
+ });
1255
+
1256
+ if (recoveryContext.lastTaskMessage && recoveryContext.failedNodeId && recoveryContext.failedProviderType) {
1257
+ const autoNodeId = recoveryContext.failedNodeId;
1258
+ try {
1259
+ const task = enqueueTask(args.meshId, recoveryContext.lastTaskMessage, {
1260
+ targetNodeId: autoNodeId
1261
+ });
1262
+ LOG.info('MeshRecovery', `Auto-requeued failed task: ${task.id} for node ${autoNodeId}`);
1263
+
1264
+ const node = mesh?.nodes.find((n: any) => meshNodeIdMatches(n, autoNodeId));
1265
+ if (node) {
1266
+ components.cliManager.handleCliCommand('launch_cli', {
1267
+ cliType: recoveryContext.failedProviderType,
1268
+ dir: node.workspace,
1269
+ settings: {
1270
+ role: 'worker',
1271
+ meshNodeFor: args.meshId,
1272
+ meshNodeId: node.id,
1273
+ spawnedSessionVisibility: mesh?.policy?.spawnedSessionVisibility || 'hidden',
1274
+ // Coordinator-dispatched recovery relaunch: same auto-approve
1275
+ // policy as the primary worker launch path.
1276
+ autoApprove: resolveDelegatedWorkerAutoApprove(mesh?.policy, node?.policy),
1277
+ launchedByCoordinator: true,
1278
+ }
1279
+ }).catch((e: any) => LOG.error('MeshRecovery', `Failed to auto-relaunch session for ${node.id}: ${e?.message}`));
1280
+ }
1281
+ } catch (e: any) {
1282
+ LOG.warn('MeshRecovery', `Failed to execute auto-recovery: ${e?.message}`);
1283
+ }
1284
+ }
1285
+ }
1286
+
1287
+ LOG.info('MeshRecovery', `Recovery context for ${args.nodeLabel}: ${recoveryContext.advice}`);
1288
+ } catch (e: any) {
1289
+ LOG.warn('MeshRecovery', `Failed to build recovery context: ${e?.message || e}`);
1290
+ }
1291
+ }
1292
+
1293
+ const messageText = buildMeshSystemMessage({
1294
+ event: args.event,
1295
+ nodeLabel: args.nodeLabel,
1296
+ metadataEvent: args.metadataEvent,
1297
+ recoveryContext,
1298
+ worktreeHasQueuedTask,
1299
+ });
1300
+ if (!messageText) {
1301
+ // Lifecycle events that carry no coordinator-facing message (agent:ready /
1302
+ // agent:generating_started) still drive the remote-claim state machine: the
1303
+ // coordinator's agent:ready branch above runs setRemoteIdleSession +
1304
+ // tryAssignQueueTask, and agent:generating_started clears the remote-idle entry.
1305
+ // For a LOCAL worker whose coordinator is a REMOTE daemon those side effects ran
1306
+ // on the wrong daemon (this worker's empty queue / store), so the coordinator never
1307
+ // learns the auto-launched session went idle and re-auto-launches it forever
1308
+ // (queue task stuck pending). Queue the silent event so the coordinator pulls it
1309
+ // (PHASE 1 pullRemoteNodeQueues → handleMeshForwardEvent) and re-runs the claim on
1310
+ // the daemon that actually owns the queue. Gate strictly on a present, REMOTE
1311
+ // coordinator daemon id: a co-located worker already ran the claim on the right
1312
+ // daemon, and a coordinator processing a *pulled* event has no sourceSession so
1313
+ // workerCoordinatorDaemonId is empty — neither re-queues, so there is no loop.
1314
+ const isSilentClaimRelevantEvent = args.event === 'agent:ready' || args.event === 'agent:generating_started';
1315
+ const coordinatorIsRemote = !!workerCoordinatorDaemonId
1316
+ && !resolveCoordinatorDrainDaemonIds(components).includes(workerCoordinatorDaemonId);
1317
+ if (!(isSilentClaimRelevantEvent && coordinatorIsRemote)) {
1318
+ return { success: false, error: 'unsupported mesh event' };
1319
+ }
1320
+ }
1321
+
1322
+ // ── Queue-only delivery (single-model: queue + periodic poll) ──────────────
1323
+ // Every mesh coordinator event — terminal or not, local-coordinator or
1324
+ // remote — is persisted to the pending-events queue (SQLite + JSONL) and
1325
+ // NOTHING is pushed here. The old spontaneous-forward paths were removed:
1326
+ // - F1 remote P2P `mesh_forward_event` dispatch (network/stamp-dependent,
1327
+ // silently dropped on P2P failure or missing meshCoordinatorDaemonId)
1328
+ // - F3 live-CLI PTY `send_message` fire-and-forget inject (silently
1329
+ // dropped when the coordinator was generating)
1330
+ // Delivery to a live CLI coordinator now happens via setupMeshReconcileLoop,
1331
+ // which drains this queue on a fixed interval and injects into the coordinator
1332
+ // only when it is idle. A pure stdio MCP (LLM) coordinator — which has no live
1333
+ // CLI session to inject into — drains the queue itself when it calls a mesh
1334
+ // tool (mesh_status / mesh_read_chat). Either way the queue is the single
1335
+ // source of truth and the only thing this function writes to.
1336
+ //
1337
+ // targetCoordinatorDaemonId scopes the event to a specific coordinator daemon
1338
+ // (unicast) when the worker carries one, so the reconcile loop on the right
1339
+ // daemon drains it and other daemons skip it. Absent → broadcast/backfill.
1340
+ const pendingEvent = {
1341
+ event: args.event,
1342
+ meshId: args.meshId,
1343
+ nodeLabel: args.nodeLabel,
1344
+ nodeId: args.nodeId || undefined,
1345
+ workspace: readNonEmptyString(args.metadataEvent.workspace)
1346
+ || readNonEmptyString(args.metadataEvent.workspaceName),
1347
+ metadataEvent: {
1348
+ ...enrichedMetadataEvent,
1349
+ ...(recoveryContext ? { recoveryContext } : {}),
1350
+ // Stash the coordinator session id INSIDE metadataEvent too, so it survives the
1351
+ // P2P relay serialization (buildForwardPayloadFromPending spreads metadata; the
1352
+ // handleMeshForwardEvent whitelist reads it back) — a top-level field alone would
1353
+ // be dropped when the event crosses a machine boundary.
1354
+ ...(workerCoordinatorSessionId ? { meshCoordinatorSessionId: workerCoordinatorSessionId } : {}),
1355
+ },
1356
+ // Silent lifecycle events (agent:ready / agent:generating_started) carry no
1357
+ // coordinator message; they are queued only so the coordinator re-runs the
1358
+ // remote-claim state machine on pull. injectPendingIntoCoordinator skips
1359
+ // entries without a coordinatorMessage, so a live CLI coordinator is not spammed.
1360
+ ...(messageText ? { coordinatorMessage: messageText } : {}),
1361
+ queuedAt: Date.now(),
1362
+ ...(workerCoordinatorDaemonId ? { targetCoordinatorDaemonId: workerCoordinatorDaemonId } : {}),
1363
+ // Top-level session anchor for the local PHASE 2 strict-match on the coordinator
1364
+ // daemon. Absent → daemon-level broadcast (legacy / single-coordinator path).
1365
+ ...(workerCoordinatorSessionId ? { targetCoordinatorSessionId: workerCoordinatorSessionId } : {}),
1366
+ };
1367
+ if (queuePendingMeshCoordinatorEvent(pendingEvent)) {
1368
+ LOG.info('MeshEvents', `Queued ${args.event} for coordinator (mesh ${args.meshId}${workerCoordinatorDaemonId ? `, coordinator daemon ${workerCoordinatorDaemonId}` : ''}${workerCoordinatorSessionId ? `, coordinator session ${workerCoordinatorSessionId}` : ''})`);
1369
+ // EVTTRACE: event persisted to the coordinator pending queue (awaiting reconcile drain).
1370
+ traceMeshEventStage('queued', traceCtx, workerCoordinatorDaemonId ? `coordinatorDaemon=${workerCoordinatorDaemonId}` : 'broadcast');
1371
+ } else {
1372
+ // EVTTRACE: queue rejected the event (dedup at queue time / persistence guard).
1373
+ traceMeshEventDrop('queue_dedup', traceCtx);
1374
+ }
1375
+ return { success: true, forwarded: 0 };
1376
+ }
1377
+
1378
+ // Reconstruct the metadataEvent that injectMeshSystemMessage consumes from a forwarded
1379
+ // (cross-machine) mesh event. The remote relay hop arrives as a flat payload, NOT the
1380
+ // original provider event object, so this whitelists the fields the coordinator-side
1381
+ // pipeline reads and re-projects them. Kept pure + exported so the relay-path field
1382
+ // preservation (esp. taskId) is unit-testable without driving injectMeshSystemMessage.
1383
+ //
1384
+ // IMPORTANT asymmetry: the LOCAL in-process forward path (onMeshCoordinatorEventForwarded)
1385
+ // passes the whole event through as metadataEvent, so every field on the event survives
1386
+ // there for free. This remote-only path must explicitly mirror each field it needs.
1387
+ export function buildRelayMetadataEvent(payload: Record<string, unknown>): Record<string, unknown> {
1388
+ const relayModalMessage = readNonEmptyString(payload.modalMessage);
1389
+ const relayModalButtons = Array.isArray(payload.modalButtons)
1390
+ ? (payload.modalButtons as unknown[]).filter((b): b is string => typeof b === 'string' && b.trim().length > 0)
1391
+ : null;
1392
+ return {
1393
+ // Preserve the dispatch task id across the machine boundary. The `received` trace
1394
+ // stage reads payload.taskId; without mirroring it here the rebuilt metadataEvent
1395
+ // loses it, so injectMeshSystemMessage's traceCtx.taskId and the
1396
+ // updateDirectDispatchStatus(eventTaskId) call go undefined — the EvtTrace
1397
+ // queued/surfaced stages show task=- and the direct-dispatch ledger falls back to a
1398
+ // session_id match (which can flip a sibling row). The local in-process forward path
1399
+ // keeps event.taskId/meshActiveTaskId for free; this mirrors it for the remote relay.
1400
+ // Same taskId/meshActiveTaskId ordering the local unroutable trace uses.
1401
+ taskId: readNonEmptyString(payload.taskId) || readNonEmptyString(payload.meshActiveTaskId),
1402
+ targetSessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId) || readNonEmptyString(payload.instanceId),
1403
+ providerType: readNonEmptyString(payload.providerType),
1404
+ providerSessionId: readNonEmptyString(payload.providerSessionId),
1405
+ // Preserve the originating coordinator SESSION id across the machine boundary so
1406
+ // the completion routes back to the exact coordinator session (multi-coordinator).
1407
+ // buildForwardPayloadFromPending spreads the worker event's metadata, so the id
1408
+ // arrives as payload.meshCoordinatorSessionId; the top-level targetCoordinatorSessionId
1409
+ // is also accepted as a fallback. injectMeshSystemMessage re-derives the routing
1410
+ // anchors from this. Absent → daemon-level fallback (version-skew safe).
1411
+ meshCoordinatorSessionId: readNonEmptyString(payload.meshCoordinatorSessionId) || readNonEmptyString(payload.targetCoordinatorSessionId),
1412
+ // Carry the session identity fields the worker provider event emits so the
1413
+ // coordinator's mirror (updateMeshOwnedSession) gets a real workspace/title/
1414
+ // settings. Without these the remote-relay hop reconstructs metadataEvent with
1415
+ // an empty workspace, and the dashboard flaps to the generic
1416
+ // "Terminal (Mesh Node)" title (and degrades the provider label) between live
1417
+ // events and the periodic get_status_metadata snapshot. The local in-process
1418
+ // forward path (onMeshCoordinatorEventForwarded) already preserves these; this
1419
+ // mirrors them for the remote-only relay path.
1420
+ workspace: readNonEmptyString(payload.workspace) || readNonEmptyString(payload.workspaceName),
1421
+ workspaceName: readNonEmptyString(payload.workspaceName) || readNonEmptyString(payload.workspace),
1422
+ sessionTitle: readNonEmptyString(payload.sessionTitle),
1423
+ sessionStatus: readNonEmptyString(payload.sessionStatus),
1424
+ sessionChatStatus: readNonEmptyString(payload.sessionChatStatus),
1425
+ providerName: readNonEmptyString(payload.providerName),
1426
+ ...(payload.sessionSettings && typeof payload.sessionSettings === 'object' && !Array.isArray(payload.sessionSettings) ? { sessionSettings: payload.sessionSettings } : {}),
1427
+ finalSummary: readNonEmptyString(payload.finalSummary) || readNonEmptyString(payload.summary),
1428
+ // T2: carry the worker's status-snapshot last-message preview across the machine
1429
+ // boundary so a summary-less completion still surfaces the assistant reply in the
1430
+ // coordinator's inbox mirror. resolveMeshSurfacedSessionPreview reads these
1431
+ // (assistant-role only) when finalSummary is absent.
1432
+ lastMessagePreview: readNonEmptyString(payload.lastMessagePreview),
1433
+ lastMessageRole: readNonEmptyString(payload.lastMessageRole),
1434
+ ...(payload.lastMessageAt !== undefined ? { lastMessageAt: payload.lastMessageAt } : {}),
1435
+ jobId: readNonEmptyString(payload.jobId),
1436
+ interactionId: readNonEmptyString(payload.interactionId),
1437
+ status: readNonEmptyString(payload.status),
1438
+ targetDaemonId: readNonEmptyString(payload.targetDaemonId),
1439
+ startedAt: readNonEmptyString(payload.startedAt),
1440
+ completedAt: readNonEmptyString(payload.completedAt),
1441
+ retryOfJobId: readNonEmptyString(payload.retryOfJobId),
1442
+ ...(relayModalMessage ? { modalMessage: relayModalMessage } : {}),
1443
+ ...(relayModalButtons && relayModalButtons.length > 0 ? { modalButtons: relayModalButtons } : {}),
1444
+ ...(payload.result && typeof payload.result === 'object' && !Array.isArray(payload.result) ? { result: payload.result } : {}),
1445
+ ...(payload.completionDiagnostic && typeof payload.completionDiagnostic === 'object' && !Array.isArray(payload.completionDiagnostic) ? { completionDiagnostic: payload.completionDiagnostic } : {}),
1446
+ ...(payload.workerResult && typeof payload.workerResult === 'object' && !Array.isArray(payload.workerResult) ? { workerResult: payload.workerResult } : {}),
1447
+ ...(payload.meshWorkerResult && typeof payload.meshWorkerResult === 'object' && !Array.isArray(payload.meshWorkerResult) ? { meshWorkerResult: payload.meshWorkerResult } : {}),
1448
+ ...(payload.structuredResult && typeof payload.structuredResult === 'object' && !Array.isArray(payload.structuredResult) ? { structuredResult: payload.structuredResult } : {}),
1449
+ ...(payload.timestamp !== undefined ? { timestamp: payload.timestamp } : {}),
1450
+ intentional: payload.intentional === true,
1451
+ intentionalStop: payload.intentionalStop === true,
1452
+ operatorCleanup: payload.operatorCleanup === true,
1453
+ reason: readNonEmptyString(payload.reason),
1454
+ stopReason: readNonEmptyString(payload.stopReason),
1455
+ cleanupReason: readNonEmptyString(payload.cleanupReason),
1456
+ source: readNonEmptyString(payload.source),
1457
+ };
1458
+ }
1459
+
1460
+ export function handleMeshForwardEvent(components: DaemonComponents, payload: Record<string, unknown>) {
1461
+ const eventName = readNonEmptyString(payload.event);
1462
+ if (!isMeshCoordinatorEvent(eventName)) {
1463
+ return { success: false, error: 'unsupported mesh event' };
1464
+ }
1465
+ const nodeId = readNonEmptyString(payload.nodeId);
1466
+ const workspace = readNonEmptyString(payload.workspace);
1467
+
1468
+ // The fallback worker-forward path (forwardUnresolvedDelegateEvent) cannot resolve a
1469
+ // mesh id locally on the remote worker, so it forwards the event with nodeId +
1470
+ // workspace only. The coordinator hosting the mesh CAN resolve it. Two recovery
1471
+ // paths, in order:
1472
+ // 1) workspace → mesh (fast path; cached repoIdentity lookup), then
1473
+ // 2) nodeId → mesh (deterministic backstop; scans hosted meshes for the node).
1474
+ // Workspace recovery alone was unreliable — a worktree clone whose repoIdentity
1475
+ // differs, or a transient cache miss, left the reconcile retry permanently rejected
1476
+ // ("meshId required") so the worker's completion never surfaced to the coordinator.
1477
+ // The nodeId is a stable coordinator-side fact and resolves timing-independently.
1478
+ const meshId = readNonEmptyString(payload.meshId)
1479
+ || (workspace ? readNonEmptyString(getCachedMeshByWorkspace(workspace)?.id) : '')
1480
+ || recoverMeshIdByNodeId(nodeId)
1481
+ // Fix B last resort: workspace + nodeId scan both missed, but the worker stamped
1482
+ // its coordinator anchor onto the forward (forwardUnresolvedDelegateEvent). Recover
1483
+ // via the hosted mesh that anchor owns (+ node disambiguation), guarding ambiguity.
1484
+ || recoverMeshIdByCoordinatorAndNode(
1485
+ readNonEmptyString(payload.meshCoordinatorDaemonId) || readNonEmptyString(payload.coordinatorDaemonId),
1486
+ nodeId,
1487
+ );
1488
+ if (!meshId) {
1489
+ // EVTTRACE: forwarded event rejected at receive — no meshId could be resolved
1490
+ // (no payload.meshId, no workspace→mesh, no nodeId→mesh). Observation only.
1491
+ traceMeshEventDrop('meshId_required', {
1492
+ taskId: payload.taskId,
1493
+ sessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId),
1494
+ nodeId,
1495
+ event: eventName,
1496
+ }, workspace ? `workspace=${workspace} unresolved` : 'no workspace/nodeId');
1497
+ return { success: false, error: 'meshId required' };
1498
+ }
1499
+ // EVTTRACE: forwarded event accepted at receive (meshId resolved).
1500
+ // NOTIF-MISS (FIX 3): mirror buildRelayMetadataEvent's taskId fallback. A worker provider
1501
+ // completion stamps its task id as `meshActiveTaskId` (settings → event), not always the
1502
+ // top-level `taskId`, so reading payload.taskId alone rendered `task=-` at the received stage
1503
+ // (the [stage:queued] task=<id> → [stage:received] task=- loss). Falling back to
1504
+ // meshActiveTaskId keeps the trace task-scoped end-to-end so same-task redelivery is
1505
+ // distinguishable from a different task's real completion.
1506
+ traceMeshEventStage('received', {
1507
+ taskId: readNonEmptyString(payload.taskId) || readNonEmptyString(payload.meshActiveTaskId),
1508
+ sessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId),
1509
+ nodeId,
1510
+ meshId,
1511
+ event: eventName,
1512
+ });
1513
+ const nodeLabel = nodeId ? `Node '${nodeId}'` : workspace ? `Agent at ${workspace}` : 'Remote agent';
1514
+
1515
+ return injectMeshSystemMessage(components, {
1516
+ meshId,
1517
+ nodeId,
1518
+ nodeLabel,
1519
+ event: eventName,
1520
+ metadataEvent: buildRelayMetadataEvent(payload),
1521
+ });
1522
+ }
1523
+
1524
+ // ---------------------------------------------------------------------------
1525
+ // Per-coordinator forward serialization (P2P send-backpressure relief).
1526
+ //
1527
+ // When several workers finish at once, each completion runs forwardUnresolvedDelegate
1528
+ // Event and fires its own `mesh_forward_event` push. Firing the whole burst
1529
+ // concurrently dumps it into the single per-peer P2P DataChannel buffer in one tick,
1530
+ // which starves the rpc_ack/rpc_res replies the same channel must carry — a
1531
+ // coordinator's inbound `git_status` then times out even though the worker's own
1532
+ // forward acks return in ~1s. To cap the concurrent burst we serialize the immediate
1533
+ // pushes per coordinator: at most one push is in flight to a given coordinator at a
1534
+ // time, the rest run in arrival order behind it. A lone event (idle lane) still
1535
+ // dispatches immediately — only a genuine burst is paced. Durability is unchanged:
1536
+ // every event is already persisted to the outbox before the push runs, so serializing
1537
+ // only delays the best-effort fast path; PHASE 0 retry still covers any gap. This pairs
1538
+ // with the DataChannel send-buffer gate in daemon-cloud's mesh manager (writeRequest),
1539
+ // which is the hard guarantee; this throttle keeps the burst from piling up there.
1540
+ interface CoordinatorForwardLane { tail: Promise<unknown>; depth: number; }
1541
+ const coordinatorForwardLanes = new Map<string, CoordinatorForwardLane>();
1542
+ function enqueueCoordinatorForwardPush(coordinatorDaemonId: string, run: () => Promise<unknown>): void {
1543
+ let lane = coordinatorForwardLanes.get(coordinatorDaemonId);
1544
+ if (!lane) { lane = { tail: Promise.resolve(), depth: 0 }; coordinatorForwardLanes.set(coordinatorDaemonId, lane); }
1545
+ const wasIdle = lane.depth === 0;
1546
+ lane.depth += 1;
1547
+ const dec = (): void => { lane!.depth -= 1; };
1548
+ if (wasIdle) {
1549
+ // Idle lane → dispatch synchronously, so a lone completion (the common case) has
1550
+ // ZERO added latency and the push call happens in-line. Only a genuine burst —
1551
+ // events arriving while a push is still in flight — is paced (else branch).
1552
+ lane.tail = Promise.resolve(run()).catch(() => {}).then(dec, dec);
1553
+ } else {
1554
+ // Burst: queue behind the in-flight push(es) in arrival order so the whole burst
1555
+ // is not dumped into the shared DataChannel buffer at once. The tail is guarded
1556
+ // so one rejecting push never wedges the lane for the next.
1557
+ lane.tail = lane.tail.then(() => run()).catch(() => {}).then(dec, dec);
1558
+ }
1559
+ }
1560
+
1561
+ // ---------------------------------------------------------------------------
1562
+ // Worker-side fallback forward for unresolved-mesh delegates.
1563
+ //
1564
+ // A REMOTE worker daemon that is being P2P-remote-controlled by a coordinator is
1565
+ // NOT a member of the coordinator's mesh — it has no local mesh record. So when its
1566
+ // completion event reaches the forwarder, resolveWorkerDelegateRouting() resolves the
1567
+ // coordinator anchor (meshCoordinatorDaemonId) from the worker envelope but cannot
1568
+ // resolve the mesh id (neither meshNodeFor nor a workspace→mesh lookup yields one) and
1569
+ // returns isDelegate=false / mesh_unresolved. Before this fallback the event was dropped
1570
+ // (delivery_unroutable) and only recovered later when the coordinator happened to pull
1571
+ // the worker's queue — which it can't, because the worker never queued an unroutable
1572
+ // event. Live symptom: `WARN [MeshEvents] delivery_unroutable: ... mesh unresolved`.
1573
+ //
1574
+ // The fix: the routing object still carries coordinatorDaemonId. Forward the raw event
1575
+ // straight to that coordinator daemon over P2P (mesh_forward_event). The coordinator
1576
+ // hosts the mesh, so it recovers the mesh id by workspace in handleMeshForwardEvent and
1577
+ // injects/queues it normally. meshId is intentionally omitted from the payload (the
1578
+ // worker has none); workspace is the routing anchor the coordinator resolves from.
1579
+ //
1580
+ // No loop / no double-delivery:
1581
+ // - This only fires on the WORKER (the coordinator-own session is rejected by the
1582
+ // resolver before reaching here), and the coordinator merely injects — it does not
1583
+ // re-enter this forwarder for the relayed event.
1584
+ // - It fires only when the normal queue path did NOT run (isDelegate=false), so the
1585
+ // event is never both queued locally and forwarded.
1586
+ //
1587
+ // Returns true when the event was durably accepted for delivery to the coordinator
1588
+ // daemon (so the caller skips the delivery_unroutable diagnostic); false when no
1589
+ // fallback was possible (no coordinator anchor / no dispatch transport).
1590
+ //
1591
+ // Durability: the directed push to the coordinator is the ONLY delivery route for an
1592
+ // unresolved-mesh worker (it is in no mesh.node the coordinator can pull). So instead
1593
+ // of a fire-and-forget push that drops on one transient P2P failure, the event is
1594
+ // persisted to the worker-side outbox FIRST and only acked after a successful push.
1595
+ // A best-effort immediate push keeps latency low on the happy path; a failed or
1596
+ // un-acked push leaves the durable row for setupMeshReconcileLoop's PHASE 0 to retry.
1597
+ function forwardUnresolvedDelegateEvent(
1598
+ components: DaemonComponents,
1599
+ routing: ReturnType<typeof resolveWorkerDelegateRouting>,
1600
+ event: Record<string, unknown>,
1601
+ ): boolean {
1602
+ const coordinatorDaemonId = readNonEmptyString(routing.coordinatorDaemonId);
1603
+ if (!coordinatorDaemonId) return false;
1604
+ if (!components.dispatchMeshCommand) return false;
1605
+
1606
+ const eventName = readNonEmptyString(event.event);
1607
+ if (!eventName) return false;
1608
+
1609
+ // Flat payload mirroring buildForwardPayloadFromPending / what handleMeshForwardEvent
1610
+ // reads. nodeId/workspace come from the worker envelope so the coordinator can name and
1611
+ // locate the node.
1612
+ const payload: Record<string, unknown> = {
1613
+ ...event,
1614
+ event: eventName,
1615
+ nodeId: readNonEmptyString(routing.nodeId) || readNonEmptyString(event.meshNodeId) || undefined,
1616
+ workspace: readNonEmptyString(routing.workspace) || readNonEmptyString(event.workspace) || undefined,
1617
+ // Fix B: carry the resolved coordinator anchor so the coordinator's receive-side
1618
+ // recovery (recoverMeshIdByCoordinatorAndNode) can match this forward to one of the
1619
+ // meshes it hosts when workspace + nodeId both miss. routing.coordinatorDaemonId is
1620
+ // the same anchor this forward is addressed to (coordinatorDaemonId below).
1621
+ meshCoordinatorDaemonId: coordinatorDaemonId,
1622
+ };
1623
+ // RECONCILE-MESHID-DROP: stamp meshId when the WORKER can resolve it (member node /
1624
+ // live-session meshNodeFor). Historically omitted "because the worker can't resolve
1625
+ // it", but for a member-hosted node a no_node_binding session's coordinator-side
1626
+ // recovery (empty payload nodeId + workspace cache miss) fails and the retry is
1627
+ // rejected "meshId required" forever. Resolving here makes the forward self-sufficient;
1628
+ // when unresolvable even here it stays absent and the coordinator's own workspace/nodeId
1629
+ // recovery still runs (unchanged), with the retry cap as the loop backstop.
1630
+ const resolvedMeshId = resolveForwardEventMeshId(components, payload);
1631
+ if (resolvedMeshId) payload.meshId = resolvedMeshId;
1632
+
1633
+ // Self-addressed fallback: the resolved coordinator IS this daemon (a self-
1634
+ // coordinating / single-node mesh, or a delegate whose coordinator anchor resolved
1635
+ // to our own id). A cross-daemon mesh_forward_event to our own id is REFUSED by the
1636
+ // dispatch self-dial guard ("route via the local router instead"), so persisting it
1637
+ // to the outbox would only loop forever in PHASE 0's retry, never acked. Honour the
1638
+ // guard's advice: route the event straight through the local receiver — the exact
1639
+ // path the coordinator runs on receiving a remote push — and skip the outbox entirely.
1640
+ const selfDaemonIds = resolveCoordinatorDrainDaemonIds(components);
1641
+ if (selfDaemonIds.some(self => daemonIdsEquivalent(self, coordinatorDaemonId))) {
1642
+ try {
1643
+ handleMeshForwardEvent(components, payload);
1644
+ LOG.info('MeshEvents', `Self-addressed unresolved-delegate ${eventName} routed via local router (coordinator ${coordinatorDaemonId} is self) — outbox skipped`);
1645
+ } catch (e: any) {
1646
+ LOG.warn('MeshEvents', `Local route of self-addressed unresolved-delegate ${eventName} failed: ${e?.message || e}`);
1647
+ }
1648
+ return true;
1649
+ }
1650
+
1651
+ // 1) Persist durably FIRST. Idempotent on fingerprint, so a re-fired completion
1652
+ // does not duplicate the outbox row. If persistence fails we still attempt the
1653
+ // push below (degrades to the old at-most-once behaviour rather than dropping
1654
+ // the chance entirely).
1655
+ const persisted = enqueueUnresolvedDelegateForward(coordinatorDaemonId, eventName, payload);
1656
+ // EVTTRACE: unresolved-mesh worker persisted its completion to the outbox (no meshId
1657
+ // available locally; coordinator will recover it on receive).
1658
+ const fwdTraceCtx = {
1659
+ taskId: (payload as Record<string, unknown>).taskId,
1660
+ sessionId: readNonEmptyString(payload.targetSessionId) || readNonEmptyString(payload.sessionId),
1661
+ nodeId: readNonEmptyString(routing.nodeId) || readNonEmptyString(event.meshNodeId),
1662
+ event: eventName,
1663
+ };
1664
+ traceMeshEventStage('outbox_enqueue', fwdTraceCtx, `coordinatorDaemon=${coordinatorDaemonId} meshId=absent`);
1665
+
1666
+ // 2) Best-effort immediate push for low latency. On success, ack the outbox row so
1667
+ // the retry loop won't re-send it. On failure, leave it queued — PHASE 0 retries.
1668
+ traceMeshEventStage('forward_send', fwdTraceCtx, 'immediate push');
1669
+ // Serialize per coordinator so a multi-worker completion burst is paced rather than
1670
+ // dumped concurrently into the shared P2P DataChannel buffer (see coordinator
1671
+ // ForwardLanes). dispatchMeshCommand was null-checked above; capture it for the
1672
+ // deferred closure.
1673
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1674
+ enqueueCoordinatorForwardPush(coordinatorDaemonId, () =>
1675
+ Promise.resolve(dispatchMeshCommand(coordinatorDaemonId, 'mesh_forward_event', payload))
1676
+ .then((result: any) => {
1677
+ if (result && result.success === false) {
1678
+ LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} rejected (${readNonEmptyString(result.error) || 'no reason'}) — left queued for retry`);
1679
+ traceMeshEventDrop('immediate_forward_rejected', fwdTraceCtx, readNonEmptyString(result.error) || 'no reason');
1680
+ return;
1681
+ }
1682
+ // Acked. Mark the durable copy delivered so the retry loop skips it.
1683
+ if (persisted) ackUnresolvedDelegateForwardByFingerprint(coordinatorDaemonId, eventName, payload);
1684
+ })
1685
+ .catch((e: any) => {
1686
+ // Coordinator momentarily unreachable; the durable row stays queued and the
1687
+ // reconcile loop retries it. Trace so the relay attempt is visible.
1688
+ LOG.warn('MeshEvents', `Immediate forward of ${eventName} to coordinator ${coordinatorDaemonId} failed: ${e?.message || e} — left queued for retry`);
1689
+ }));
1690
+ LOG.info('MeshEvents', `Durably forwarded ${eventName} for unresolved-mesh worker at ${routing.workspace || '(no workspace)'} to coordinator daemon ${coordinatorDaemonId}`);
1691
+ return true;
1692
+ }
1693
+
1694
+ // Ack a just-pushed outbox entry by re-deriving its row from the same coordinator +
1695
+ // event + payload. We don't thread the row id back from enqueue (the immediate push is
1696
+ // fire-then-ack), so locate it among the undrained entries by matching coordinator and
1697
+ // the flat payload's forward identity. A miss is harmless — the retry loop's own
1698
+ // receiver-side dedup suppresses a duplicate delivery.
1699
+ function ackUnresolvedDelegateForwardByFingerprint(
1700
+ coordinatorDaemonId: string,
1701
+ eventName: string,
1702
+ payload: Record<string, unknown>,
1703
+ ): void {
1704
+ const match = peekUnresolvedDelegateForwards().find(entry =>
1705
+ daemonIdsEquivalent(entry.coordinatorDaemonId, coordinatorDaemonId)
1706
+ && readNonEmptyString(entry.payload.event) === eventName
1707
+ && readNonEmptyString(entry.payload.targetSessionId || entry.payload.sessionId || entry.payload.instanceId)
1708
+ === readNonEmptyString(payload.targetSessionId || payload.sessionId || payload.instanceId)
1709
+ && readNonEmptyString(entry.payload.workspace) === readNonEmptyString(payload.workspace),
1710
+ );
1711
+ if (match) ackUnresolvedDelegateForward(match.id);
1712
+ }
1713
+
1714
+ /**
1715
+ * NOTIF-HELD-DRAIN (Fix 2): event-driven coordinator drain. The reconcile loop delivers a
1716
+ * worker's queued completion to an IDLE local coordinator only on its periodic poll. When a
1717
+ * coordinator is sitting idle awaiting exactly that completion, waiting up to a full poll
1718
+ * interval is the avoidable delivery latency the RCA flags — and combined with the (now-fixed)
1719
+ * modal-park false-positive it stretched into the multi-minute notification stall. So the
1720
+ * MOMENT a worker delegate event is persisted for a mesh, attempt the same idle-coordinator
1721
+ * drain immediately, mirroring the event-driven worker-claim path (agent:ready /
1722
+ * agent:generating_completed → triggerMeshQueue).
1723
+ *
1724
+ * Safety:
1725
+ * - drainPendingMeshCoordinatorEvents marks rows drained=1 atomically, so this races the
1726
+ * reconcile poll and the coordinator's own idle auto-flush harmlessly — exactly one consumes
1727
+ * each row.
1728
+ * - Only IDLE, non-modal-parked coordinators are delivery targets (never a generating /
1729
+ * consent-modal PTY).
1730
+ * - Strict session routing is honoured: an event naming an originating coordinator session is
1731
+ * delivered only to that live idle session; anything not currently deliverable here
1732
+ * (wrong/absent session, or a message-less lifecycle event) is RE-QUEUED — never dropped —
1733
+ * so the reconcile loop's strict hold/expire path remains the single authority for it.
1734
+ */
1735
+ export function flushPendingForMeshIdleCoordinators(components: DaemonComponents, meshId: string): void {
1736
+ // O(1) gate: skip the (relatively expensive) per-instance getState scan when the queue is
1737
+ // empty for this mesh.
1738
+ try {
1739
+ const store = MeshRuntimeStore.getInstance();
1740
+ if (store.pendingEventCount(meshId) === 0) return;
1741
+ } catch { /* store unavailable — fall through and let the drain decide */ }
1742
+
1743
+ const idleCoordinators: { instance: ProviderInstance; sessionId: string }[] = [];
1744
+ try {
1745
+ for (const inst of components.instanceManager.getByCategory('cli')) {
1746
+ const state = inst.getState();
1747
+ const settings = state.settings && typeof state.settings === 'object'
1748
+ ? state.settings as Record<string, unknown>
1749
+ : {};
1750
+ if (readNonEmptyString(settings.meshCoordinatorFor) !== meshId) continue;
1751
+ const status = readNonEmptyString(state.status).toLowerCase();
1752
+ const modalParked = typeof (inst as any).isModalParked === 'function'
1753
+ ? (inst as any).isModalParked() === true
1754
+ : (status === 'waiting_choice' || status === 'waiting_approval');
1755
+ // PTY-OVERTRUST-DRAIN (Defect B): decide idle on the RAW adapter turn-state
1756
+ // (getDrainStatus, mask-stripped) to match the reconcile loop — getState().status
1757
+ // overlays the auto-approve hold-idle mask that paints a genuinely-idle coordinator
1758
+ // `generating`, which would make this opportunistic flush skip a real drain target.
1759
+ // Fall back to the masked literal for any instance without getDrainStatus().
1760
+ const drainStatus: string | null = typeof (inst as any).getDrainStatus === 'function'
1761
+ ? (inst as any).getDrainStatus()
1762
+ : null;
1763
+ const idle = drainStatus !== null ? drainStatus === 'idle' : (status === 'idle');
1764
+ if (idle && !modalParked) {
1765
+ idleCoordinators.push({ instance: inst, sessionId: readNonEmptyString(state.instanceId) });
1766
+ }
1767
+ }
1768
+ } catch { return; }
1769
+ if (idleCoordinators.length === 0) return; // no idle target now → leave for the reconcile poll
1770
+
1771
+ const drainDaemonIds = resolveCoordinatorDrainDaemonIds(components);
1772
+ let pendingEvents: PendingMeshCoordinatorEvent[];
1773
+ try {
1774
+ pendingEvents = drainPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
1775
+ } catch (e: any) {
1776
+ LOG.warn('MeshEvents', `Event-driven coordinator drain failed for mesh ${meshId}: ${e?.message || e}`);
1777
+ return;
1778
+ }
1779
+ if (pendingEvents.length === 0) return;
1780
+
1781
+ let delivered = 0;
1782
+ for (const pending of pendingEvents) {
1783
+ const wantSession = readNonEmptyString(pending.targetCoordinatorSessionId);
1784
+ const targets = wantSession
1785
+ ? idleCoordinators.filter(c => sessionIdsEquivalent(c.sessionId, wantSession))
1786
+ : idleCoordinators;
1787
+ // Not deliverable into an idle target here (wrong/absent session), or a message-less
1788
+ // lifecycle event (agent:ready / generating_started carry no coordinatorMessage and
1789
+ // must not be injected): re-queue so the reconcile loop owns it (lazy-synth / strict
1790
+ // hold/expire). Re-queue preserves queuedAt so the strict TTL measures true age.
1791
+ if (targets.length === 0 || !pending.coordinatorMessage) {
1792
+ try { queuePendingMeshCoordinatorEvent(pending); } catch { /* best-effort re-queue */ }
1793
+ continue;
1794
+ }
1795
+ const message = pending.coordinatorMessage;
1796
+ const force = shouldForceInjectMeshEvent(pending.event);
1797
+ for (const c of targets) {
1798
+ c.instance.onEvent('send_message', {
1799
+ input: { text: message, textFallback: message },
1800
+ ...(force ? { force: true } : {}),
1801
+ });
1802
+ delivered++;
1803
+ }
1804
+ }
1805
+ if (delivered > 0) {
1806
+ LOG.info('MeshEvents', `Event-driven drain delivered ${delivered} pending event(s) to ${idleCoordinators.length} idle coordinator(s) for mesh ${meshId}`);
1807
+ }
1808
+ }
1809
+
1810
+ export function setupMeshEventForwarding(components: DaemonComponents) {
1811
+ components.instanceManager.onEvent((event) => {
1812
+ // --- Coordinator idle auto-flush (fast path) ---
1813
+ // When a coordinator session becomes idle, immediately flush any pending
1814
+ // coordinator events that accumulated while it was generating, rather than
1815
+ // waiting up to one reconcile interval for setupMeshReconcileLoop to do it.
1816
+ // Both paths drain the SAME queue via drainPendingMeshCoordinatorEvents,
1817
+ // whose SQLite drained=1 marking is atomic — whichever fires first consumes
1818
+ // the events and the other gets nothing, so there is no double-delivery.
1819
+ // This runs before the delegate routing below so that coordinator-own idle
1820
+ // transitions are handled first.
1821
+ // Exception: a coordinator that is itself a direct-dispatch target still needs
1822
+ // to go through delegate routing so that the dispatching coordinator receives a
1823
+ // pendingCoordinatorEvents entry for the completion.
1824
+ if (event.event === 'agent:ready' || event.event === 'agent:generating_completed') {
1825
+ const flushInstanceId = readNonEmptyString(event.instanceId);
1826
+ if (flushInstanceId) {
1827
+ const flushSource = components.instanceManager.getInstance(flushInstanceId);
1828
+ if (flushSource && flushSource.category === 'cli') {
1829
+ const flushState = flushSource.getState();
1830
+ const flushSettings = flushState.settings && typeof flushState.settings === 'object' ? flushState.settings as Record<string, unknown> : {};
1831
+ const coordinatorMeshId = readNonEmptyString(flushSettings.meshCoordinatorFor);
1832
+ if (coordinatorMeshId) {
1833
+ const status = readNonEmptyString(flushState.status).toLowerCase();
1834
+ if (status === 'idle') {
1835
+ try {
1836
+ // Drain with the daemon's full coordinator-id set (status id + machineId).
1837
+ // The MCP layer stamps the prefixed status id (`standalone_<machineId>` /
1838
+ // `daemon_<machineId>`) as the worker's meshCoordinatorDaemonId; draining
1839
+ // with bare machineId alone would miss those unicast events. Mirrors
1840
+ // resolveCoordinatorDaemonIds in mesh-reconcile-loop.
1841
+ const drainDaemonIds = resolveCoordinatorDrainDaemonIds(components);
1842
+ const pendingEvents = drainPendingMeshCoordinatorEvents(coordinatorMeshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
1843
+ if (pendingEvents.length > 0) {
1844
+ LOG.info('MeshEvents', `Auto-flushing ${pendingEvents.length} pending coordinator event(s) for mesh ${coordinatorMeshId} on coordinator idle`);
1845
+ for (const pending of pendingEvents) {
1846
+ if (!pending.coordinatorMessage) continue;
1847
+ const forcePending = shouldForceInjectMeshEvent(pending.event);
1848
+ flushSource.onEvent('send_message', {
1849
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
1850
+ ...(forcePending ? { force: true } : {}),
1851
+ });
1852
+ }
1853
+ }
1854
+ } catch (e: any) {
1855
+ LOG.warn('MeshEvents', `Failed to auto-flush pending coordinator events: ${e?.message || e}`);
1856
+ }
1857
+ }
1858
+ // Skip delegate routing unless this coordinator session is itself
1859
+ // a direct-dispatch target — in that case fall through so the
1860
+ // dispatching coordinator gets a pendingCoordinatorEvents entry.
1861
+ let hasDirectDispatch = false;
1862
+ try {
1863
+ hasDirectDispatch =
1864
+ getActiveDirectDispatches(coordinatorMeshId).some(d => sessionIdsEquivalent(d.sessionId, flushInstanceId))
1865
+ || hasUnterminalDirectDispatchLedgerEntry(coordinatorMeshId, flushInstanceId);
1866
+ } catch { /* best-effort */ }
1867
+ if (!hasDirectDispatch) return;
1868
+ }
1869
+ }
1870
+ }
1871
+ }
1872
+
1873
+ // --- Delegate event routing ---
1874
+ if (!isMeshCoordinatorEvent(event.event)) return;
1875
+
1876
+ const instanceId = readNonEmptyString(event.instanceId);
1877
+ if (!instanceId) return;
1878
+
1879
+ // R1: all session→node→mesh→coordinator interpretation is folded into the single
1880
+ // resolveWorkerDelegateRouting() resolver. No stamp (meshNodeFor / meshNodeId /
1881
+ // meshCoordinatorDaemonId / meshCoordinatorNodeId / launchedByCoordinator) is read
1882
+ // here to make a routing decision — the resolver is the one authority, and the
1883
+ // forwarder consumes its typed result only.
1884
+ const routing = resolveWorkerDelegateRouting(components, instanceId, {
1885
+ getMeshById: (meshId) => getMeshWithCache(components, meshId),
1886
+ getMeshByWorkspace: (workspace) => getCachedMeshByWorkspace(workspace),
1887
+ });
1888
+ if (!routing.isDelegate) {
1889
+ // Fallback: a REMOTE worker that isn't a member of the coordinator's mesh can't
1890
+ // resolve a mesh id locally (mesh_unresolved), but it still carries the coordinator
1891
+ // daemon anchor. Forward the event straight to that coordinator over P2P instead of
1892
+ // dropping it — the coordinator hosts the mesh and recovers the id by workspace.
1893
+ if (isUnroutableDelegateRejection(routing)
1894
+ && forwardUnresolvedDelegateEvent(components, routing, event)) {
1895
+ return;
1896
+ }
1897
+ // R4: a worker that presented a valid envelope but resolved to no mesh (and could
1898
+ // not be fallback-forwarded — e.g. no coordinator anchor) used to be dropped
1899
+ // silently. Leave a fail-loud diagnostic so the missing completion is traceable.
1900
+ // Benign non-delegate rejections (not_cli / no_workspace / etc.) are no-ops inside
1901
+ // recordUnroutableDelegateEvent.
1902
+ // EVTTRACE: a delegate event that could not be routed AND could not be
1903
+ // fallback-forwarded (no coordinator anchor). Only mesh_unresolved is a real
1904
+ // drop; the benign non-delegate rejections are ordinary non-mesh traffic.
1905
+ if (isUnroutableDelegateRejection(routing)) {
1906
+ traceMeshEventDrop('unroutable', {
1907
+ taskId: (event as Record<string, unknown>).meshActiveTaskId ?? (event as Record<string, unknown>).taskId,
1908
+ sessionId: routing.sessionId,
1909
+ nodeId: routing.nodeId,
1910
+ event: event.event,
1911
+ }, 'no coordinator anchor / mesh_unresolved');
1912
+ }
1913
+ recordUnroutableDelegateEvent(routing, event.event);
1914
+ return;
1915
+ }
1916
+
1917
+ injectMeshSystemMessage(components, {
1918
+ meshId: routing.meshId,
1919
+ sourceInstanceId: instanceId,
1920
+ nodeId: routing.nodeId,
1921
+ nodeLabel: routing.nodeLabel,
1922
+ event: event.event,
1923
+ metadataEvent: event,
1924
+ });
1925
+
1926
+ // NOTIF-HELD-DRAIN (Fix 2): the worker's event is now persisted in the pending queue.
1927
+ // If a local coordinator for this mesh is sitting idle awaiting it, deliver immediately
1928
+ // instead of waiting up to a full reconcile interval (event-driven, mirrors the
1929
+ // worker-claim path). No-op when no idle coordinator is present (held for reconcile).
1930
+ flushPendingForMeshIdleCoordinators(components, routing.meshId);
1931
+ });
1932
+ }