@adhdev/daemon-core 0.9.82-rc.48 → 0.9.82-rc.480

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