@adhdev/daemon-core 0.9.82-rc.38 → 0.9.82-rc.381

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