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

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