@adhdev/daemon-core 0.9.82-rc.39 → 0.9.82-rc.390

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 (415) 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 +67 -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 +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +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 +237 -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/git-worktree.d.ts +22 -0
  70. package/dist/git/index.d.ts +2 -0
  71. package/dist/index.d.ts +57 -13
  72. package/dist/index.js +46306 -18259
  73. package/dist/index.js.map +1 -1
  74. package/dist/index.mjs +46439 -18533
  75. package/dist/index.mjs.map +1 -1
  76. package/dist/installer.d.ts +1 -4
  77. package/dist/ipc/local-ipc-server.d.ts +91 -0
  78. package/dist/launch.d.ts +1 -1
  79. package/dist/logging/async-batch-writer.d.ts +10 -0
  80. package/dist/logging/log-redactor.d.ts +24 -0
  81. package/dist/logging/log-tail-reader.d.ts +81 -0
  82. package/dist/logging/logger.d.ts +1 -1
  83. package/dist/mesh/contracts.d.ts +164 -0
  84. package/dist/mesh/coordinator-prompt.d.ts +89 -0
  85. package/dist/mesh/coordinator-registry.d.ts +59 -0
  86. package/dist/mesh/mesh-active-work.d.ts +174 -0
  87. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  88. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  89. package/dist/mesh/mesh-event-classify.d.ts +5 -0
  90. package/dist/mesh/mesh-event-forwarding.d.ts +19 -0
  91. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  92. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  93. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  94. package/dist/mesh/mesh-events-stale.d.ts +52 -0
  95. package/dist/mesh/mesh-events-utils.d.ts +64 -0
  96. package/dist/mesh/mesh-events.d.ts +6 -49
  97. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  98. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  99. package/dist/mesh/mesh-init.d.ts +86 -0
  100. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  101. package/dist/mesh/mesh-ledger.d.ts +77 -1
  102. package/dist/mesh/mesh-missions.d.ts +164 -0
  103. package/dist/mesh/mesh-node-identity.d.ts +289 -0
  104. package/dist/mesh/mesh-queue-assignment.d.ts +86 -0
  105. package/dist/mesh/mesh-reconcile-loop.d.ts +65 -0
  106. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  107. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  108. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  109. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  110. package/dist/mesh/mesh-routing.d.ts +70 -0
  111. package/dist/mesh/mesh-runtime-store.d.ts +447 -0
  112. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  113. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  114. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  115. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  116. package/dist/mesh/mesh-work-queue.d.ts +247 -5
  117. package/dist/mesh/preview-freshness.d.ts +18 -0
  118. package/dist/mesh/refine-config.d.ts +216 -0
  119. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  120. package/dist/providers/acp-provider-instance.d.ts +5 -0
  121. package/dist/providers/approval-utils.d.ts +20 -0
  122. package/dist/providers/chat-message-normalization.d.ts +13 -1
  123. package/dist/providers/cli-provider-instance.d.ts +157 -3
  124. package/dist/providers/contracts.d.ts +139 -6
  125. package/dist/providers/external-sources.d.ts +71 -0
  126. package/dist/providers/manual-attendance.d.ts +63 -0
  127. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  128. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  129. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  130. package/dist/providers/native-history/constants.d.ts +12 -0
  131. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  132. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  133. package/dist/providers/native-history/index.d.ts +13 -0
  134. package/dist/providers/provider-instance-manager.d.ts +14 -0
  135. package/dist/providers/provider-instance.d.ts +23 -1
  136. package/dist/providers/provider-loader.d.ts +26 -4
  137. package/dist/providers/provider-trust.d.ts +31 -0
  138. package/dist/providers/read-chat-contract.d.ts +29 -0
  139. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  140. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  141. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  142. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  143. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  144. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  145. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  146. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  147. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  148. package/dist/providers/sdk/v1/index.d.ts +30 -0
  149. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  150. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  151. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  152. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  153. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  154. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  155. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  156. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  157. package/dist/providers/spec/adapter.d.ts +91 -0
  158. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  159. package/dist/providers/spec/evaluator.d.ts +45 -0
  160. package/dist/providers/spec/fsm-driver.d.ts +407 -0
  161. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  162. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  163. package/dist/providers/spec/fsm-types.d.ts +174 -0
  164. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  165. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  166. package/dist/providers/spec/route.d.ts +4 -0
  167. package/dist/providers/spec/types.d.ts +222 -0
  168. package/dist/providers/status-monitor.d.ts +7 -7
  169. package/dist/providers/transcript-v2.d.ts +176 -0
  170. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  171. package/dist/providers/working-dir.d.ts +17 -0
  172. package/dist/repo-mesh-types.d.ts +376 -13
  173. package/dist/runtime-defaults.d.ts +2 -0
  174. package/dist/sessions/registry.d.ts +6 -0
  175. package/dist/shared-types-extra.d.ts +2 -4
  176. package/dist/shared-types.d.ts +59 -2
  177. package/dist/status/normalize.d.ts +1 -1
  178. package/dist/status/normalize.js +1 -0
  179. package/dist/status/normalize.js.map +1 -1
  180. package/dist/status/normalize.mjs +1 -0
  181. package/dist/status/normalize.mjs.map +1 -1
  182. package/dist/status/reporter.d.ts +2 -0
  183. package/dist/status/snapshot.d.ts +26 -0
  184. package/dist/system/hash.d.ts +8 -0
  185. package/dist/system/load-better-sqlite3.d.ts +21 -0
  186. package/dist/types.d.ts +5 -0
  187. package/package.json +7 -3
  188. package/src/agent-stream/poller.ts +2 -3
  189. package/src/agent-stream/provider-adapter.ts +1 -1
  190. package/src/boot/daemon-lifecycle.ts +63 -12
  191. package/src/boot/process-hardening.ts +89 -0
  192. package/src/build-info.ts +73 -0
  193. package/src/chat/source-machine.ts +534 -0
  194. package/src/chat/source-resolver.ts +0 -0
  195. package/src/chat/subscription-updates.ts +20 -1
  196. package/src/cli-adapter-types.d.ts +1 -0
  197. package/src/cli-adapter-types.ts +68 -2
  198. package/src/cli-adapters/cli-script-runner.ts +421 -0
  199. package/src/cli-adapters/cli-state-engine.ts +1221 -0
  200. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  201. package/src/cli-adapters/provider-cli-adapter.ts +836 -1141
  202. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  203. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  204. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  205. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  206. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  207. package/src/cli-adapters/pty-transport.ts +2 -1
  208. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  209. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  210. package/src/cli-adapters/resolve-executable.ts +90 -0
  211. package/src/cli-adapters/session-host-transport.ts +2 -1
  212. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  213. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  214. package/src/cli-adapters/terminal-screen.ts +16 -81
  215. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  216. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  217. package/src/commands/chat-commands-read.ts +2327 -0
  218. package/src/commands/chat-commands-scope.ts +54 -0
  219. package/src/commands/chat-commands-shared.ts +114 -0
  220. package/src/commands/chat-commands-write.ts +880 -0
  221. package/src/commands/chat-commands.ts +19 -1841
  222. package/src/commands/cli-manager.ts +513 -26
  223. package/src/commands/handler.ts +841 -2
  224. package/src/commands/high-family/index.ts +28 -0
  225. package/src/commands/high-family/mesh-coordinator-launch.ts +657 -0
  226. package/src/commands/high-family/mesh-events.ts +80 -0
  227. package/src/commands/high-family/mesh-status.ts +678 -0
  228. package/src/commands/high-family/types.ts +76 -0
  229. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  230. package/src/commands/low-family/daemon-lifecycle.ts +107 -0
  231. package/src/commands/low-family/diagnostics.ts +57 -0
  232. package/src/commands/low-family/index.ts +37 -0
  233. package/src/commands/low-family/mesh-ledger.ts +62 -0
  234. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  235. package/src/commands/low-family/notification.ts +116 -0
  236. package/src/commands/low-family/refine-config.ts +106 -0
  237. package/src/commands/low-family/session-host.ts +274 -0
  238. package/src/commands/low-family/spec-providerdev.ts +217 -0
  239. package/src/commands/low-family/status-meta.ts +112 -0
  240. package/src/commands/low-family/types.ts +39 -0
  241. package/src/commands/med-family/cli-agent.ts +230 -0
  242. package/src/commands/med-family/fast-forward.ts +230 -0
  243. package/src/commands/med-family/ide.ts +163 -0
  244. package/src/commands/med-family/index.ts +37 -0
  245. package/src/commands/med-family/mesh-crud.ts +836 -0
  246. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  247. package/src/commands/med-family/mesh-queue.ts +131 -0
  248. package/src/commands/med-family/mesh-restart.ts +92 -0
  249. package/src/commands/med-family/types.ts +120 -0
  250. package/src/commands/mesh-coordinator.ts +334 -124
  251. package/src/commands/router.ts +2476 -3207
  252. package/src/commands/stream-commands.ts +8 -0
  253. package/src/commands/upgrade-helper.ts +310 -45
  254. package/src/config/chat-history.ts +483 -24
  255. package/src/config/config.ts +12 -0
  256. package/src/config/mesh-config.ts +353 -22
  257. package/src/config/recent-activity.ts +8 -2
  258. package/src/daemon/dev-auto-implement.ts +3 -2
  259. package/src/daemon/dev-cli-debug.ts +10 -1
  260. package/src/daemon/dev-server.ts +0 -541
  261. package/src/detection/cli-detector.ts +28 -9
  262. package/src/detection/ide-detector.ts +55 -16
  263. package/src/detection/win32-ide-version.ts +106 -0
  264. package/src/git/change-impact-config.ts +354 -0
  265. package/src/git/git-commands.ts +55 -14
  266. package/src/git/git-diff.ts +81 -11
  267. package/src/git/git-executor.ts +12 -0
  268. package/src/git/git-status.ts +574 -43
  269. package/src/git/git-types.ts +14 -62
  270. package/src/git/git-worktree.ts +76 -1
  271. package/src/git/index.ts +16 -0
  272. package/src/index.ts +171 -12
  273. package/src/installer.d.ts +1 -1
  274. package/src/installer.ts +8 -6
  275. package/src/ipc/local-ipc-server.ts +278 -0
  276. package/src/launch.d.ts +1 -1
  277. package/src/launch.ts +37 -28
  278. package/src/logging/async-batch-writer.ts +55 -0
  279. package/src/logging/command-log.ts +7 -5
  280. package/src/logging/log-redactor.ts +100 -0
  281. package/src/logging/log-tail-reader.ts +341 -0
  282. package/src/logging/logger.ts +14 -7
  283. package/src/mesh/contracts.ts +338 -0
  284. package/src/mesh/coordinator-prompt.ts +381 -33
  285. package/src/mesh/coordinator-registry.ts +121 -0
  286. package/src/mesh/mesh-active-work.ts +645 -0
  287. package/src/mesh/mesh-coordinator-config.ts +97 -0
  288. package/src/mesh/mesh-delivery-policy.ts +315 -0
  289. package/src/mesh/mesh-event-classify.ts +51 -0
  290. package/src/mesh/mesh-event-forwarding.ts +1665 -0
  291. package/src/mesh/mesh-event-trace.ts +67 -0
  292. package/src/mesh/mesh-events-coordinator.ts +30 -0
  293. package/src/mesh/mesh-events-pending.ts +590 -0
  294. package/src/mesh/mesh-events-stale.ts +363 -0
  295. package/src/mesh/mesh-events-utils.ts +425 -0
  296. package/src/mesh/mesh-events.ts +32 -1035
  297. package/src/mesh/mesh-fast-forward.ts +839 -0
  298. package/src/mesh/mesh-host-ownership.ts +73 -0
  299. package/src/mesh/mesh-init.ts +260 -0
  300. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  301. package/src/mesh/mesh-ledger.ts +596 -102
  302. package/src/mesh/mesh-missions.ts +322 -0
  303. package/src/mesh/mesh-node-identity.ts +1887 -0
  304. package/src/mesh/mesh-queue-assignment.ts +1491 -0
  305. package/src/mesh/mesh-reconcile-loop.ts +1527 -0
  306. package/src/mesh/mesh-refine-batch.ts +197 -0
  307. package/src/mesh/mesh-refine-gates.ts +1652 -0
  308. package/src/mesh/mesh-refine-status.ts +231 -0
  309. package/src/mesh/mesh-review-inbox.ts +307 -0
  310. package/src/mesh/mesh-routing.ts +291 -0
  311. package/src/mesh/mesh-runtime-store.ts +1795 -0
  312. package/src/mesh/mesh-scheduling-runtime.ts +199 -0
  313. package/src/mesh/mesh-task-stats.ts +161 -0
  314. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  315. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  316. package/src/mesh/mesh-work-queue.ts +1141 -141
  317. package/src/mesh/preview-freshness.ts +118 -0
  318. package/src/mesh/refine-config.ts +423 -0
  319. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  320. package/src/providers/acp-provider-instance.ts +43 -10
  321. package/src/providers/approval-utils.d.ts +5 -0
  322. package/src/providers/approval-utils.ts +57 -5
  323. package/src/providers/chat-message-normalization.ts +46 -6
  324. package/src/providers/cli-provider-instance.ts +1552 -102
  325. package/src/providers/contracts.d.ts +55 -0
  326. package/src/providers/contracts.ts +150 -6
  327. package/src/providers/extension-provider-instance.ts +12 -7
  328. package/src/providers/external-sources.ts +218 -0
  329. package/src/providers/ide-provider-instance.ts +35 -12
  330. package/src/providers/manual-attendance.ts +85 -0
  331. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  332. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  333. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  334. package/src/providers/native-history/constants.ts +19 -0
  335. package/src/providers/native-history/dispatcher.ts +339 -0
  336. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  337. package/src/providers/native-history/index.ts +30 -0
  338. package/src/providers/provider-instance-manager.ts +30 -0
  339. package/src/providers/provider-instance.ts +19 -1
  340. package/src/providers/provider-loader.ts +668 -50
  341. package/src/providers/provider-schema.ts +87 -14
  342. package/src/providers/provider-trust.ts +114 -0
  343. package/src/providers/read-chat-contract.ts +76 -16
  344. package/src/providers/sdk/README.md +49 -0
  345. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  346. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  347. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  348. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  349. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  350. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  351. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  352. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  353. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  354. package/src/providers/sdk/v1/index.ts +152 -0
  355. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  356. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  357. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  358. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  359. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  360. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  361. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  362. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  363. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  364. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  365. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  366. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  367. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  368. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  369. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  370. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  371. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  372. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  373. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  374. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  375. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  376. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  377. package/src/providers/sdk/v1/validators/index.ts +19 -0
  378. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  379. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  380. package/src/providers/spec/adapter.ts +235 -0
  381. package/src/providers/spec/cli-adapter.ts +1056 -0
  382. package/src/providers/spec/evaluator.ts +407 -0
  383. package/src/providers/spec/fsm-driver.ts +1304 -0
  384. package/src/providers/spec/fsm-evaluator.ts +272 -0
  385. package/src/providers/spec/fsm-loader.ts +120 -0
  386. package/src/providers/spec/fsm-types.ts +273 -0
  387. package/src/providers/spec/native-history-executor.ts +1128 -0
  388. package/src/providers/spec/pre-launch-trust.ts +104 -0
  389. package/src/providers/spec/route.ts +51 -0
  390. package/src/providers/spec/types.ts +262 -0
  391. package/src/providers/status-monitor.d.ts +7 -7
  392. package/src/providers/status-monitor.ts +37 -22
  393. package/src/providers/transcript-v2.ts +567 -0
  394. package/src/providers/types/interactive-prompt.ts +536 -0
  395. package/src/providers/version-archive.ts +64 -24
  396. package/src/providers/working-dir.ts +23 -0
  397. package/src/repo-mesh-types.ts +542 -14
  398. package/src/runtime-defaults.ts +39 -0
  399. package/src/sessions/registry.ts +6 -0
  400. package/src/shared-types-extra.ts +2 -4
  401. package/src/shared-types.d.ts +8 -0
  402. package/src/shared-types.ts +64 -1
  403. package/src/status/builders.ts +26 -6
  404. package/src/status/normalize.ts +2 -0
  405. package/src/status/reporter.ts +19 -1
  406. package/src/status/snapshot.ts +95 -26
  407. package/src/system/hash.ts +23 -0
  408. package/src/system/host-memory.ts +29 -12
  409. package/src/system/load-better-sqlite3.ts +68 -0
  410. package/src/types.ts +5 -0
  411. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  412. package/dist/mesh/mesh-sync.d.ts +0 -53
  413. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  414. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  415. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1527 @@
1
+ // ---------------------------------------------------------------------------
2
+ // mesh-reconcile-loop — periodic queue → live coordinator reconciliation
3
+ // ---------------------------------------------------------------------------
4
+ // Single-model replacement for the old event-based "spontaneous forward" paths
5
+ // (remote P2P mesh_forward_event dispatch + live-CLI PTY fire-and-forget inject).
6
+ // Those pushed events at the moment a worker transitioned state, and silently
7
+ // dropped on the network (P2P) or when the coordinator was generating.
8
+ //
9
+ // The reliable backbone has always been the pending-events queue (SQLite +
10
+ // JSONL): every mesh coordinator event is persisted there before anything else
11
+ // (see injectMeshSystemMessage). What was missing was an *active* drainer that
12
+ // runs on a schedule rather than only when the coordinator (an LLM) happens to
13
+ // call a mesh tool.
14
+ //
15
+ // This loop is that drainer. On a fixed interval it:
16
+ // 1. Finds live CLI coordinator sessions on THIS daemon (meshCoordinatorFor
17
+ // stamp). For each mesh, drains the local queue scoped to this daemon and
18
+ // injects pending events into the coordinator. When a coordinator is idle it
19
+ // receives every queued event. When ONLY generating coordinators exist (the
20
+ // common case while the coordinator is blocked awaiting a worker result), the
21
+ // loop force-drains ONLY the force-inject events (completion / approval / stop /
22
+ // refine·bootstrap terminal) and force-writes them into the generating PTY —
23
+ // the same busy-bypass send-guard escape the live-CLI inject used to use.
24
+ // Non-force progress events stay queued for the next idle tick (injecting them
25
+ // mid-generation would be noise). This is what makes a coordinator parked in
26
+ // `generating` while awaiting a worker's completion actually receive it.
27
+ // 2. In cloud mode (dispatchMeshCommand present), pulls each remote worker
28
+ // node daemon's queue over P2P (get_pending_mesh_events) and re-injects via
29
+ // handleMeshForwardEvent — the same pull the MCP drainCoordinatorPendingEvents
30
+ // already does, now driven by the daemon timer instead of an LLM tool call.
31
+ //
32
+ // IMPORTANT — limits of this loop:
33
+ // - It only delivers to *live CLI coordinator instances* on this daemon. A
34
+ // pure stdio MCP coordinator (an LLM with no live CLI session to inject
35
+ // into) has no inject target here; that case stays pull-driven — the LLM
36
+ // drains the queue when it calls mesh_status / mesh_read_chat. We do NOT try
37
+ // to "wake" an LLM from the daemon; that is structurally impossible over a
38
+ // stdio request/response transport. See docs/refactoring/2026-06-15-mesh-event-to-queue-polling.md §4.7.
39
+ // - Queue persistence (queuePendingMeshCoordinatorEvent) and the SQLite
40
+ // drained=1 idempotency are the trust backbone and are untouched by this loop.
41
+ // ---------------------------------------------------------------------------
42
+
43
+ import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
44
+ import type { LocalMeshEntry } from '../repo-mesh-types.js';
45
+ import { loadConfig } from '../config/config.js';
46
+ import { listMeshes } from '../config/mesh-config.js';
47
+ import { LOG } from '../logging/logger.js';
48
+ import { drainPendingMeshCoordinatorEvents, getPendingMeshCoordinatorEvents, buildPendingEventFingerprint, queuePendingMeshCoordinatorEvent } from './mesh-events-pending.js';
49
+ import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
50
+ import { appendLedgerEntry } from './mesh-ledger.js';
51
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
52
+ import { handleMeshForwardEvent, shouldForceInjectMeshEvent, triggerMeshQueue, resolveForwardEventMeshId } from './mesh-events-coordinator.js';
53
+ import {
54
+ peekUnresolvedDelegateForwards,
55
+ ackUnresolvedDelegateForward,
56
+ expireStaleUnresolvedDelegateForwards,
57
+ } from './mesh-unresolved-forward-outbox.js';
58
+ import { readNonEmptyString, readMeshCompletionSummary } from './mesh-events-utils.js';
59
+ import { traceMeshEventStage, traceMeshEventDrop } from './mesh-event-trace.js';
60
+ import { expandDaemonIdForms, daemonIdsEquivalent } from '@adhdev/mesh-shared';
61
+ import { getActiveDirectDispatches, getQueue, reclaimStrandedAssignedTask, updateTaskStatus } from './mesh-work-queue.js';
62
+ import { readLedgerEntries } from './mesh-ledger.js';
63
+ import { pruneStaleDirectDispatches } from './mesh-active-work.js';
64
+ import { findTerminalLedgerEvidenceForTask, reconcileDirectDispatchCompletionFromTranscript } from './mesh-events-stale.js';
65
+ import { extractFinalAssistantSummaryEvidence } from '../providers/chat-message-normalization.js';
66
+ import type { ChatMessage } from '../types.js';
67
+
68
+ // Default reconcile cadence. approval/completion notifications to a live CLI
69
+ // coordinator land within at most one interval. Overridable via env for tuning.
70
+ const DEFAULT_RECONCILE_INTERVAL_MS = 4_000;
71
+
72
+ // PHASE 5 (auto-prune) conservative age gate. A direct dispatch whose node/session is
73
+ // orphaned (no longer in the live mesh) is only auto-pruned once it is at least this old,
74
+ // measured from its dispatch time. This protects against a node/session that is only
75
+ // *transiently* invisible (a momentary probe failure, a daemon restart) being pruned the
76
+ // instant it disappears. The MANUAL prune (mesh_prune_stale_direct) has no age gate — an
77
+ // operator pruning explicitly wants the orphan gone now. Overridable via env for tuning.
78
+ const DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 60_000; // 24h
79
+
80
+ function resolveAutoPruneMinAgeMs(): number {
81
+ const raw = readNonEmptyString(process.env.MESH_AUTO_PRUNE_MIN_AGE_MS);
82
+ if (raw) {
83
+ const parsed = Number.parseInt(raw, 10);
84
+ // Clamp to [1h, 30d] so a mis-set env can't make the gate pathologically aggressive
85
+ // (prune the moment something blinks) or effectively disable it forever.
86
+ if (Number.isFinite(parsed) && parsed >= 60 * 60_000 && parsed <= 30 * 24 * 60 * 60_000) return parsed;
87
+ }
88
+ return DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
89
+ }
90
+
91
+ function resolveReconcileIntervalMs(): number {
92
+ const raw = readNonEmptyString(process.env.MESH_RECONCILE_INTERVAL_MS);
93
+ if (raw) {
94
+ const parsed = Number.parseInt(raw, 10);
95
+ if (Number.isFinite(parsed) && parsed >= 1_000 && parsed <= 60_000) return parsed;
96
+ }
97
+ return DEFAULT_RECONCILE_INTERVAL_MS;
98
+ }
99
+
100
+ // RECONCILE-SYNTH-PREEMPTS-COMPLETION in-flight debounce. PHASE 4 only synthesizes a missing
101
+ // completion when the worker session reads `idle`. But a worker that is GENUINELY generating
102
+ // (it emitted agent:generating_started — the dispatch row is 'acked' — and has not yet
103
+ // completed) can momentarily read `idle` mid-turn: a CLI PTY parser sees an inter-turn blip
104
+ // between tool calls, or the read_chat probe races a brief settle. A single such idle read
105
+ // must NOT fabricate a completion for an in-flight task — doing so writes a synthesized
106
+ // terminal that then masks the REAL completion when it lands seconds later
107
+ // (drop:duplicate_completion_terminal_ledger; the observed 71s task a250fb44 lost its [System]
108
+ // notification this way). We require the session to read `idle` on CONSECUTIVE reconcile ticks
109
+ // before synthesizing for an `acked` (started-generating) dispatch — a transient mid-turn idle
110
+ // flicker clears on the next ~4s tick, whereas a genuinely-settled (completed-but-lost) or dead
111
+ // session reads idle every tick. A dispatch that was never acked (worker never started) is NOT
112
+ // debounced here: there is no in-flight generation to protect, and the downstream grace gate +
113
+ // stale-summary guard remain the backstops for that lost-dispatch case.
114
+ //
115
+ // Keyed by `${meshId}::${taskId}`. The map is pruned each PHASE-4 pass to the set of currently
116
+ // active dispatches, so a completed/pruned task's counter is dropped (no unbounded growth).
117
+ const REQUIRED_CONSECUTIVE_IDLE_TICKS_FOR_INFLIGHT_SYNTH = 2;
118
+ const inFlightIdleObservationCounts = new Map<string, number>();
119
+
120
+ function inFlightSynthKey(meshId: string, taskId: string): string {
121
+ return `${meshId}::${taskId}`;
122
+ }
123
+
124
+ // Test hook: clear the in-flight idle debounce state between cases.
125
+ export function __resetReconcileInFlightSynthDebounceForTests(): void {
126
+ inFlightIdleObservationCounts.clear();
127
+ }
128
+
129
+ interface LiveCoordinator {
130
+ meshId: string;
131
+ instance: ReturnType<DaemonComponents['instanceManager']['getInstance']>;
132
+ // Runtime session id of this coordinator instance (getState().instanceId). PHASE 2
133
+ // strict-matches an event's targetCoordinatorSessionId against this so a completion
134
+ // routes back to the exact originating coordinator session, not a sibling on the same
135
+ // daemon (the multi-coordinator misroute).
136
+ sessionId: string;
137
+ idle: boolean;
138
+ // True when the coordinator session is parked on a harness modal awaiting a
139
+ // human answer — claude-cli AskUserQuestion (waiting_choice) or a tool-consent
140
+ // prompt (waiting_approval). A force-inject into such a session would write raw
141
+ // keystrokes the modal key handler consumes, silently selecting a choice the
142
+ // user never made (data corruption). PHASE 2 excludes these from force-inject
143
+ // and leaves the event queued for a later (modal-resolved) tick.
144
+ modalParked: boolean;
145
+ }
146
+
147
+ // The set of coordinator-daemon ids THIS daemon answers to when draining the
148
+ // pending-events queue. A unicast completion event is stamped with the worker's
149
+ // meshCoordinatorDaemonId, which can be either:
150
+ // - the daemon's canonical status id (`standalone_<machineId>` / `daemon_<machineId>`),
151
+ // stamped by the MCP layer via ctx.localDaemonId (= getStatus().status.instanceId), or
152
+ // - the bare machineId, stamped by the local queue-assignment path (loadConfig().machineId).
153
+ // - the config-form node daemonId (`daemon_<machineId>`), which the MCP layer's
154
+ // resolveCoordinatorDaemonId prefers and stamps onto direct-dispatch workers.
155
+ // Draining with only one of these silently misses events stamped with the other —
156
+ // the exact reason a generating coordinator never self-received local completions,
157
+ // and the base-node completion-surface bug (base completions land full-form
158
+ // `daemon_<machineId>` while a coordinator that only knows itself as bare
159
+ // `<machineId>` never matches them). We expand to EVERY equivalent form so the
160
+ // scope match (host gate, self-node detection, and the drain IN-filter downstream)
161
+ // succeeds regardless of which path stamped the event.
162
+ function resolveCoordinatorDaemonIds(components: DaemonComponents): string[] {
163
+ const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
164
+ const machineId = readNonEmptyString(loadConfig().machineId);
165
+ return expandDaemonIdForms([statusInstanceId, machineId]);
166
+ }
167
+
168
+ // Whether THIS daemon is the coordinator/host for a mesh — i.e. the daemon that
169
+ // owns coordinator ownership and must collect every worker node's completion
170
+ // events into its local queue. This is true regardless of whether a *live CLI*
171
+ // coordinator session currently exists: the coordinator is frequently a pure
172
+ // stdio MCP LLM (no live CLI session to inject into), and that LLM only sees the
173
+ // queue when it next calls a mesh tool. For it to see remote worker completions
174
+ // at all, the daemon must have already pulled them into the local queue on the
175
+ // timer — which is exactly what this predicate gates.
176
+ //
177
+ // Rule: this daemon hosts the mesh when meshHost.role is 'host' (the default for
178
+ // standalone-compat meshes with no host metadata) AND, when a hostDaemonId is
179
+ // pinned, it resolves to one of this daemon's ids. Member-only daemons return
180
+ // false — their own queue is pulled BY the host, not the other way around.
181
+ //
182
+ // `daemonIds` here is the EXPANDED self-identity set (runtime drain ids ∪ this
183
+ // daemon's mesh-config node id forms) — see resolveCoordinatorSelfIds. The
184
+ // pinned hostDaemonId is itself a config-form id and frequently does NOT equal a
185
+ // runtime id (bare machineId / status id), so gating on the runtime ids alone
186
+ // would wrongly classify the real host as a non-host and skip the remote pull
187
+ // entirely.
188
+ function daemonHostsMesh(mesh: LocalMeshEntry, daemonIds: string[]): boolean {
189
+ const host = mesh.meshHost;
190
+ // No metadata → default host (standalone compatibility, see createDefaultMeshHostMetadata).
191
+ if (!host) return true;
192
+ if (host.role && host.role !== 'host') return false;
193
+ const hostDaemonId = readNonEmptyString(host.hostDaemonId);
194
+ // Host role but no pinned hostDaemonId → treat as host (single-daemon / legacy).
195
+ if (!hostDaemonId) return true;
196
+ return daemonIdListIncludes(daemonIds, hostDaemonId);
197
+ }
198
+
199
+ function daemonIdListIncludes(ids: readonly string[], id: string | undefined): boolean {
200
+ if (!id) return false;
201
+ return ids.some(candidate => candidate === id || daemonIdsEquivalent(candidate, id));
202
+ }
203
+
204
+ // Resolve EVERY id-form this daemon answers to FOR A GIVEN MESH: the runtime drain
205
+ // ids (status id + bare machineId) unioned with this daemon's mesh-config identity
206
+ // forms — the self node's daemonId/machineId (the node whose daemonId/machineId
207
+ // matches a runtime id) and the pinned meshHost.hostDaemonId WHEN it is provably
208
+ // ours. This is the single source of truth for "is this id me?" across both the
209
+ // host gate and the remote pull filter; the worker's meshCoordinatorDaemonId stamp
210
+ // is guaranteed to be one of these forms (it comes from resolveCoordinatorDaemonId,
211
+ // which prefers the coordinator node's config-form daemonId over the runtime status id).
212
+ function resolveCoordinatorSelfIds(mesh: LocalMeshEntry, drainDaemonIds: string[]): string[] {
213
+ const ids = new Set<string>(drainDaemonIds);
214
+ // Expand with the config-form id(s) of the self node — the mesh node whose
215
+ // daemonId/machineId matches a runtime id. Its config-form daemonId is exactly
216
+ // what resolveCoordinatorNode()→resolveCoordinatorDaemonId() stamps onto a worker.
217
+ for (const node of mesh.nodes) {
218
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
219
+ const nodeMachineId = readNonEmptyString(node.machineId);
220
+ const isSelf = (nodeDaemonId && daemonIdListIncludes(drainDaemonIds, nodeDaemonId))
221
+ || (nodeMachineId && daemonIdListIncludes(drainDaemonIds, nodeMachineId));
222
+ if (!isSelf) continue;
223
+ if (nodeDaemonId) ids.add(nodeDaemonId);
224
+ if (nodeMachineId) ids.add(nodeMachineId);
225
+ }
226
+ // The pinned host id is included ONLY when it is provably one of THIS daemon's ids
227
+ // (it already matches a runtime id or a resolved self-node id). A hostDaemonId that
228
+ // names a DIFFERENT daemon must NOT be claimed — that would make a member-only
229
+ // daemon believe it is the host and pull queues it does not own. Having a node on
230
+ // this daemon does not make this daemon the host; daemonHostsMesh still honours a
231
+ // foreign hostDaemonId and rejects ownership.
232
+ const hostDaemonId = readNonEmptyString(mesh.meshHost?.hostDaemonId);
233
+ if (hostDaemonId && daemonIdListIncludes([...ids], hostDaemonId)) ids.add(hostDaemonId);
234
+ return [...ids];
235
+ }
236
+
237
+ // Observability: last-seen modal-park state per coordinator session, so we LOG.info
238
+ // only on a TRANSITION (clear → parked, parked → cleared) instead of every 4s tick.
239
+ // Per-process; a restart re-logs the first observation, which is desirable — it
240
+ // re-confirms a coordinator that is still parked after the restart (the exact
241
+ // "restart does not clear it" symptom the operator needs visibility into).
242
+ const coordinatorModalParkState = new Map<string, boolean>();
243
+
244
+ // Find live CLI coordinator instances on THIS daemon, keyed by mesh.
245
+ function findLiveCoordinators(components: DaemonComponents): LiveCoordinator[] {
246
+ const out: LiveCoordinator[] = [];
247
+ for (const inst of components.instanceManager.getByCategory('cli')) {
248
+ const state = inst.getState();
249
+ const settings = state.settings && typeof state.settings === 'object'
250
+ ? state.settings as Record<string, unknown>
251
+ : {};
252
+ const meshId = readNonEmptyString(settings.meshCoordinatorFor);
253
+ if (!meshId) continue;
254
+ const status = readNonEmptyString(state.status).toLowerCase();
255
+ // getState() overlays the modal-park statuses: an active AskUserQuestion
256
+ // prompt surfaces as waiting_choice, a tool-consent prompt as waiting_approval.
257
+ // Lowercase literal compare — the SessionStatus enum is forked across modules
258
+ // and waiting_choice is absent from some of them (see cli-provider-instance).
259
+ const modalParked = status === 'waiting_choice' || status === 'waiting_approval';
260
+ const sessionId = readNonEmptyString(state.instanceId);
261
+ // Modal-park transition observability: a coordinator entering modal-park is what
262
+ // begins holding completion events under `modal_parked`; one leaving it is what
263
+ // drains them. Both transitions were previously SILENT (the operator had no log
264
+ // to diagnose a stuck/held completion), so emit a single line per edge.
265
+ const stateKey = `${meshId}::${sessionId || '?'}`;
266
+ const prevParked = coordinatorModalParkState.get(stateKey);
267
+ if (prevParked !== modalParked) {
268
+ coordinatorModalParkState.set(stateKey, modalParked);
269
+ if (modalParked) {
270
+ LOG.info('MeshReconcile', `Coordinator ${sessionId || '?'} (mesh ${meshId}) entered modal-park (status=${status}) — terminal events for it will be held until the modal is answered`);
271
+ } else if (prevParked === true) {
272
+ LOG.info('MeshReconcile', `Coordinator ${sessionId || '?'} (mesh ${meshId}) left modal-park (status=${status}) — held events will drain on this/next tick`);
273
+ }
274
+ }
275
+ out.push({ meshId, instance: inst, sessionId, idle: status === 'idle', modalParked });
276
+ }
277
+ return out;
278
+ }
279
+
280
+ /**
281
+ * DRAIN-WITHOUT-INJECT guard. Classify, for a mesh on THIS daemon, whether a
282
+ * queue-drain caller (the MCP `get_pending_mesh_events` poll) may safely consume
283
+ * pending coordinator events — i.e. whether there is a surface that will actually
284
+ * deliver them.
285
+ *
286
+ * Root cause being guarded: `get_pending_mesh_events` marks rows drained=1
287
+ * atomically and unconditionally. When the live CLI coordinator for the mesh is
288
+ * GENERATING (or modal-parked), the reconcile loop correctly HOLDS its terminal
289
+ * events (drained=0) for the coordinator's next idle tick — but a concurrent MCP
290
+ * poll draining the SAME queue consumes those held rows into a tool result that
291
+ * the busy coordinator never surfaces as a turn, so the completion is lost
292
+ * forever (drained=1, never re-queued). The reconcile loop is the authoritative
293
+ * delivery path for a live CLI coordinator; the MCP poll must defer to it.
294
+ *
295
+ * Returns:
296
+ * - hasLiveCliCoordinator: a CLI session with meshCoordinatorFor === meshId
297
+ * exists on this daemon (the reconcile loop owns its delivery).
298
+ * - deliverableNow: there is an IDLE live CLI coordinator (reconcile would
299
+ * full-drain into it) — draining now is safe and equivalent.
300
+ * - holdForReconcile: a live CLI coordinator exists but is non-idle
301
+ * (generating / modal-parked). The MCP poll MUST NOT drain; the reconcile
302
+ * loop holds the events undrained and injects them on the next idle tick.
303
+ *
304
+ * A mesh with NO live CLI coordinator on this daemon is a pure stdio MCP / LLM
305
+ * coordinator: the MCP tool result IS the only surface, so the poll legitimately
306
+ * drains (holdForReconcile=false). No regression to that path.
307
+ */
308
+ export function resolveCoordinatorDrainDeliverability(
309
+ components: Pick<DaemonComponents, 'instanceManager'>,
310
+ meshId: string,
311
+ ): { hasLiveCliCoordinator: boolean; deliverableNow: boolean; holdForReconcile: boolean } {
312
+ const coordinators = findLiveCoordinators(components as DaemonComponents).filter(c => c.meshId === meshId);
313
+ if (coordinators.length === 0) {
314
+ return { hasLiveCliCoordinator: false, deliverableNow: false, holdForReconcile: false };
315
+ }
316
+ const hasIdle = coordinators.some(c => c.idle);
317
+ return {
318
+ hasLiveCliCoordinator: true,
319
+ deliverableNow: hasIdle,
320
+ // A live CLI coordinator exists but none is idle → the reconcile loop is
321
+ // holding the events; the poll must not steal them.
322
+ holdForReconcile: !hasIdle,
323
+ };
324
+ }
325
+
326
+ /**
327
+ * DRAIN-WITHOUT-INJECT guard for the `get_pending_mesh_events` daemon handler.
328
+ *
329
+ * Decides whether an incoming pending-events DRAIN must be held (return nothing,
330
+ * leave rows drained=0) because the only surface for those events is a LOCAL live
331
+ * CLI coordinator that is currently busy (generating / modal-parked) — in which
332
+ * case the reconcile loop owns delivery on the coordinator's next idle tick, and
333
+ * the poll draining them now would lose them.
334
+ *
335
+ * The hold applies ONLY when BOTH:
336
+ * 1) a live CLI coordinator for this mesh on THIS daemon is non-idle, AND
337
+ * 2) the drain is targeted at THIS daemon (the requested coordinatorDaemonId is
338
+ * empty/broadcast, or matches one of this daemon's id forms).
339
+ *
340
+ * A REMOTE coordinator pulling our worker's events passes its own (remote)
341
+ * coordinatorDaemonId — condition (2) is false — so the drain proceeds and the
342
+ * remote pull is never blocked by our local coordinator's busy state. A pure
343
+ * stdio MCP coordinator (no live CLI session) never satisfies (1), so its tool
344
+ * result remains the surface and the drain proceeds. No regression to either.
345
+ */
346
+ export function shouldHoldPendingDrainForBusyLocalCoordinator(
347
+ components: Pick<DaemonComponents, 'instanceManager'> & { statusInstanceId?: string },
348
+ meshId: string,
349
+ requestedCoordinatorDaemonId?: string | null,
350
+ ): boolean {
351
+ if (!meshId) return false;
352
+ const deliverability = resolveCoordinatorDrainDeliverability(components, meshId);
353
+ if (!deliverability.holdForReconcile) return false;
354
+ // The local CLI coordinator is busy. Hold only when the drain is for THIS daemon.
355
+ const requested = readNonEmptyString(requestedCoordinatorDaemonId);
356
+ if (!requested) return true; // broadcast drain → would consume the held local events
357
+ const localIds = expandDaemonIdForms([
358
+ readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId),
359
+ readNonEmptyString(loadConfig().machineId),
360
+ ]);
361
+ return localIds.some(id => daemonIdsEquivalent(id, requested));
362
+ }
363
+
364
+ // Inject a drained pending event into a live coordinator session. Force-inject
365
+ // events carry force:true so they bypass the busy send-guard and land in the PTY
366
+ // even while the coordinator is generating (see shouldForceInjectMeshEvent).
367
+ function injectPendingIntoCoordinator(
368
+ coordinator: LiveCoordinator['instance'],
369
+ pending: PendingMeshCoordinatorEvent,
370
+ ): void {
371
+ if (!coordinator || !pending.coordinatorMessage) return;
372
+ const force = shouldForceInjectMeshEvent(pending.event);
373
+ // EVTTRACE: event surfaced to the coordinator (injected into its live CLI session).
374
+ // This is the terminal happy-path stage. Observation only.
375
+ traceMeshEventStage('surfaced', {
376
+ taskId: pending.metadataEvent?.taskId,
377
+ sessionId: pending.metadataEvent?.targetSessionId ?? pending.targetCoordinatorSessionId,
378
+ nodeId: pending.nodeId,
379
+ meshId: pending.meshId,
380
+ event: pending.event,
381
+ }, force ? 'force-inject' : 'inject');
382
+ coordinator.onEvent('send_message', {
383
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
384
+ ...(force ? { force: true } : {}),
385
+ });
386
+ }
387
+
388
+ // Held-event ledger dedup: fingerprints of held terminal events already written as an
389
+ // `event_held` ledger audit record in THIS process. Prevents the 4s reconcile tick from
390
+ // re-logging the same held event every interval while a coordinator stays modal-parked.
391
+ // Per-process only (not persisted) — if the daemon restarts while an event is still held
392
+ // it is re-logged once, which is desirable: it re-confirms the event is still undelivered.
393
+ const heldEventLedgerRecorded = new Set<string>();
394
+
395
+ // C1 (data safety): when a terminal completion/approval/bootstrap event cannot be
396
+ // delivered because the only coordinators are modal-parked, the event is held at
397
+ // drained=0 in the pending queue (SQLite + JSONL) for a later tick. That queue is
398
+ // disk-persisted but carries no operator-visible audit trail and can be silently
399
+ // dropped by the pending-file trim (100 KB / 50-entry cap). To guarantee a held
400
+ // completion's worker summary is never silently lost, mirror each held terminal event
401
+ // into the coordinator's mesh ledger as an `event_held` entry — auditable and
402
+ // recoverable (the finalSummary survives even if the pending copy is later trimmed or
403
+ // the coordinator session is force-resolved before re-drain). Idempotent per process
404
+ // via heldEventLedgerRecorded so a long modal park does not spam the ledger.
405
+ function recordHeldTerminalEventsToLedger(
406
+ meshId: string,
407
+ drainDaemonIds: string[],
408
+ reason: string,
409
+ heldForCoordinatorCount: number,
410
+ ): void {
411
+ let pending: readonly PendingMeshCoordinatorEvent[];
412
+ try {
413
+ pending = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
414
+ } catch {
415
+ return; // best-effort audit — never let a peek failure break the tick
416
+ }
417
+ for (const event of pending) {
418
+ // Only audit terminal/force-inject events (completion / approval / stop / refine·
419
+ // bootstrap). Silent lifecycle events (agent:ready / generating_started) carry no
420
+ // worker output to preserve and re-drain harmlessly, so they need no audit trail.
421
+ if (!shouldForceInjectMeshEvent(event.event)) continue;
422
+ const fingerprint = buildPendingEventFingerprint(event);
423
+ const key = `${meshId}::${fingerprint || `${event.event}::${event.nodeId || ''}::${event.queuedAt}`}`;
424
+ if (heldEventLedgerRecorded.has(key)) continue;
425
+ heldEventLedgerRecorded.add(key);
426
+ const finalSummary = readMeshCompletionSummary(event.metadataEvent);
427
+ try {
428
+ appendLedgerEntry(meshId, {
429
+ kind: 'event_held',
430
+ ...(event.nodeId ? { nodeId: event.nodeId } : {}),
431
+ payload: {
432
+ event: event.event,
433
+ reason,
434
+ recoverable: true,
435
+ heldForCoordinators: heldForCoordinatorCount,
436
+ nodeLabel: event.nodeLabel,
437
+ ...(event.workspace ? { workspace: event.workspace } : {}),
438
+ targetCoordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
439
+ queuedAt: event.queuedAt,
440
+ ...(fingerprint ? { fingerprint } : {}),
441
+ ...(finalSummary ? { finalSummary } : {}),
442
+ },
443
+ });
444
+ LOG.info('MeshReconcile', `Ledger-recorded held ${event.event} for mesh ${meshId} (reason ${reason}) — recoverable from ledger`);
445
+ } catch (e: any) {
446
+ // Failed to persist — drop the dedup marker so the next tick retries.
447
+ heldEventLedgerRecorded.delete(key);
448
+ LOG.warn('MeshReconcile', `Failed to ledger-record held ${event.event} for mesh ${meshId}: ${e?.message || e}`);
449
+ }
450
+ }
451
+ }
452
+
453
+ // One reconcile tick. Two independent phases:
454
+ //
455
+ // PHASE 1 — Remote queue pull (the fix for remote worktree completions never
456
+ // reaching an MCP/LLM coordinator). For EVERY mesh this daemon hosts/
457
+ // coordinates, pull each remote worker node's pending-events queue over P2P
458
+ // into THIS daemon's local queue. This runs *regardless of whether a live CLI
459
+ // coordinator exists* — the coordinator is usually a pure stdio MCP LLM with
460
+ // no live CLI session, and it can only observe a remote worker's completion
461
+ // once that event has been pulled into the local queue (which it then drains
462
+ // on its next mesh tool call). Previously this pull was gated behind a live
463
+ // CLI coordinator and so never ran for MCP/LLM coordinators — remote
464
+ // completions sat on the remote node's queue until the LLM happened to call
465
+ // mesh_read_chat, which triggered the MCP-side pull. The daemon now does it
466
+ // autonomously on the timer. Standalone (no dispatchMeshCommand) skips this
467
+ // phase entirely — there are no remote nodes to pull from.
468
+ //
469
+ // PHASE 2 — Live CLI inject. For each mesh that has a live CLI coordinator on
470
+ // THIS daemon, drain the local queue and inject pending events into the PTY.
471
+ // Unchanged from before.
472
+ // Bug B: how long a row may sit 'assigned' with an unconfirmed dispatch before the
473
+ // watchdog reclaims it. Must be comfortably larger than the per-dispatch confirm
474
+ // timeout (DISPATCH_CONFIRM_TIMEOUT_MS in mesh-events-coordinator) so a slow-but-live
475
+ // dispatch still inside its normal confirm window is never reclaimed early — this is
476
+ // the durable backstop for the case the in-process confirm timer can't cover (a timer
477
+ // lost to a daemon restart between claim and confirm).
478
+ const ASSIGNED_STRANDED_DEADLINE_MS = 5 * 60_000;
479
+
480
+ // PHASE 2.5 — assigned-stranded dispatch watchdog (Bug B). claimNextTask atomically
481
+ // flips a row to 'assigned' BEFORE the fire-and-forget dispatch runs. If that dispatch
482
+ // neither rejects (→ no .catch requeue) nor is confirmed delivered — a relay that hangs
483
+ // without acking, or a confirm timer lost across a restart — the row stays 'assigned'
484
+ // forever: it contributes 0 pending, so PHASE 3 (gated on pendingQueueTaskCount>0) never
485
+ // re-examines it, and nothing but a manual requeue clears it. This is that missing net.
486
+ //
487
+ // Regression guard: a row whose delivery IS confirmed (delivered/acked/completed) is a
488
+ // genuinely in-flight (or completion-lost) task — left to PHASE 4's completion reconcile,
489
+ // never reclaimed here. And the deadline is generous so a slow-but-live dispatch still in
490
+ // its normal confirm window is never reclaimed early. Reclaimed rows return to 'pending'
491
+ // with ownership cleared, so the PHASE 3 trigger below re-dispatches them this same tick.
492
+ function recoverStrandedAssignedDispatches(meshId: string, store: MeshRuntimeStore): void {
493
+ const assigned = getQueue(meshId, { status: ['assigned'] });
494
+ if (!assigned.length) return;
495
+ const nowMs = Date.now();
496
+ for (const row of assigned) {
497
+ const dispatchedAtMs = Date.parse(row.dispatchTimestamp ?? '');
498
+ if (!Number.isFinite(dispatchedAtMs)) continue; // no dispatch ts → can't age it
499
+ if (nowMs - dispatchedAtMs < ASSIGNED_STRANDED_DEADLINE_MS) continue; // still in confirm window
500
+ const terminal = findTerminalLedgerEvidenceForTask({
501
+ meshId,
502
+ taskId: row.id,
503
+ });
504
+ if (terminal) {
505
+ const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
506
+ updateTaskStatus(meshId, row.id, status);
507
+ LOG.warn('MeshReconcile', `Skipped stranded reclaim redispatch for terminal task ${row.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
508
+ traceMeshEventDrop('assigned_stranded_terminal_ledger', {
509
+ taskId: row.id,
510
+ sessionId: row.assignedSessionId,
511
+ nodeId: row.assignedNodeId,
512
+ meshId,
513
+ event: 'agent:generating_completed',
514
+ }, terminal.kind);
515
+ continue;
516
+ }
517
+ if (store.taskHasConfirmedDelivery(meshId, row.id)) continue; // dispatched → PHASE 4's job
518
+ const reclaimed = reclaimStrandedAssignedTask(meshId, row.id, {
519
+ reason: 'assigned_stranded_dispatch_unconfirmed',
520
+ ageMs: nowMs - dispatchedAtMs,
521
+ });
522
+ if (reclaimed) {
523
+ LOG.warn('MeshReconcile', `Reclaimed stranded assigned task ${row.id} on mesh ${meshId} `
524
+ + `(node=${row.assignedNodeId ?? '?'} session=${row.assignedSessionId ?? '?'}, dispatched `
525
+ + `${Math.round((nowMs - dispatchedAtMs) / 1000)}s ago, never confirmed delivered → ${reclaimed.status})`);
526
+ // EVTTRACE: the dispatch for this task was stranded (assigned, never confirmed
527
+ // delivered) and reclaimed (CANON-B) — its expected completion event never
528
+ // arrived. Observation only; the reclaim decision above is unchanged.
529
+ traceMeshEventDrop('assigned_stranded_reclaim', {
530
+ taskId: row.id,
531
+ sessionId: row.assignedSessionId,
532
+ nodeId: row.assignedNodeId,
533
+ meshId,
534
+ event: 'agent:generating_completed',
535
+ }, `unconfirmed ${Math.round((nowMs - dispatchedAtMs) / 1000)}s → ${reclaimed.status}`);
536
+ }
537
+ }
538
+ }
539
+
540
+ export async function runMeshReconcileTick(components: DaemonComponents): Promise<void> {
541
+ const localDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
542
+ // The id-set used to scope the local queue drain (status id + machineId). See
543
+ // resolveCoordinatorDaemonIds — the status id is what the MCP layer stamps and
544
+ // is mandatory here for a generating CLI coordinator to self-receive completions.
545
+ const drainDaemonIds = resolveCoordinatorDaemonIds(components);
546
+ const dispatchMeshCommand = components.dispatchMeshCommand;
547
+ const store = (() => {
548
+ try { return MeshRuntimeStore.getInstance(); } catch { return undefined; }
549
+ })();
550
+
551
+ // ── PHASE 0: retry the worker-side unresolved-delegate forward outbox ──────
552
+ // Cloud-only (needs dispatchMeshCommand). A worker that is NOT a member of the
553
+ // coordinator's mesh cannot be reached by the coordinator's PHASE 1 pull (it is
554
+ // in no mesh.node), so its completion must be PUSHED to the coordinator. This
555
+ // drains the durable outbox enqueued by forwardUnresolvedDelegateEvent and retries
556
+ // any push that has not yet been acked. See mesh-unresolved-forward-outbox.ts.
557
+ if (dispatchMeshCommand) {
558
+ try {
559
+ await retryUnresolvedDelegateForwards(components);
560
+ } catch (e: any) {
561
+ LOG.warn('MeshReconcile', `Unresolved-delegate forward retry failed: ${e?.message || e}`);
562
+ }
563
+ }
564
+
565
+ // ── PHASE 1: pull remote node queues for every mesh this daemon hosts ──────
566
+ // Cloud-only (dispatchMeshCommand present). Runs whether or not a live CLI
567
+ // coordinator exists — this is what lets an MCP/LLM coordinator ever see a
568
+ // remote worker's completion.
569
+ if (dispatchMeshCommand) {
570
+ for (const mesh of listMeshes()) {
571
+ // Expand to every id-form this daemon answers to for this mesh (runtime
572
+ // drain ids ∪ config-form node/host ids) and use it for BOTH the host gate
573
+ // and the remote pull filter, so a worker stamp in any form is recovered.
574
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
575
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
576
+ try {
577
+ await pullRemoteNodeQueues(components, mesh, localDaemonId, selfIds);
578
+ } catch (e: any) {
579
+ LOG.warn('MeshReconcile', `Remote node pull failed for mesh ${mesh.id}: ${e?.message || e}`);
580
+ }
581
+ }
582
+ }
583
+
584
+ // ── PHASE 2.5: assigned-stranded dispatch watchdog (Bug B) ─────────────────
585
+ // Runs before PHASE 3 so any row it returns to 'pending' is re-dispatched by the
586
+ // PHASE 3 trigger in this same tick. See recoverStrandedAssignedDispatches.
587
+ if (store) {
588
+ for (const mesh of listMeshes()) {
589
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
590
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
591
+ try {
592
+ recoverStrandedAssignedDispatches(mesh.id, store);
593
+ } catch (e: any) {
594
+ LOG.warn('MeshReconcile', `Assigned-stranded watchdog failed for mesh ${mesh.id}: ${e?.message || e}`);
595
+ }
596
+ }
597
+ }
598
+
599
+ // ── PHASE 3: recover pending queue claims for newly-idle sessions ──────────
600
+ // The event-driven claim paths (agent:ready / agent:generating_completed in
601
+ // mesh-events-coordinator) re-claim the queue the moment a session goes idle,
602
+ // but that depends on a single event being emitted AND (for a remote node)
603
+ // successfully forwarded to this coordinator. If that event is missed/dropped,
604
+ // a pending task targeting a now-idle session would sit unclaimed forever —
605
+ // there was no periodic safety net. This phase is that net: for every mesh this
606
+ // daemon hosts that has at least one pending task, run one triggerMeshQueue so a
607
+ // session that became idle without a delivered ready-event still gets its work.
608
+ //
609
+ // O(1) guard: skip the (relatively expensive) full idle-session + remote-idle
610
+ // scan entirely when the queue has no pending tasks — a COUNT(*) over the
611
+ // indexed status column, so an idle mesh costs one cheap query per tick.
612
+ // claimNextQueueTask is atomic, so racing the event-driven path can only have
613
+ // one winner; double-claiming is impossible.
614
+ for (const mesh of listMeshes()) {
615
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
616
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
617
+ if (store) {
618
+ try {
619
+ if (store.pendingQueueTaskCount(mesh.id) === 0) continue;
620
+ } catch { /* fall through and let triggerMeshQueue decide */ }
621
+ }
622
+ try {
623
+ await triggerMeshQueue(components, mesh.id);
624
+ } catch (e: any) {
625
+ LOG.warn('MeshReconcile', `Pending-claim recovery trigger failed for mesh ${mesh.id}: ${e?.message || e}`);
626
+ }
627
+ }
628
+
629
+ // ── PHASE 4: synthesize lost completions for unterminated direct dispatches ─
630
+ // Symmetric to PHASE 3 (which recovers a *lost claim* for a newly-idle session)
631
+ // but for the opposite gap: a worker that ALREADY completed, went idle, and
632
+ // whose terminal completion event was never persisted (dropped before reaching
633
+ // the queue/outbox, or its forward was lost). PHASE 1/2/3 can only deliver an
634
+ // event that exists in a queue — they cannot recover a completion that was
635
+ // never recorded, so the coordinator keeps believing the worker is generating.
636
+ //
637
+ // reconcileDirectDispatchCompletionFromTranscript already synthesizes the
638
+ // missing terminal event from the worker's transcript, but until now it ran
639
+ // ONLY when an LLM coordinator polled mesh_status (mcp_mesh_status_transcript_
640
+ // reconciliation). This phase pulls that same correction onto the daemon timer
641
+ // so it no longer depends on the LLM polling. The reconcile is idempotent
642
+ // (hasTerminalLedgerAfterDispatch guards against re-synthesis), so attempting it
643
+ // every tick for the same dispatch is safe — once a terminal exists it no-ops.
644
+ for (const mesh of listMeshes()) {
645
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
646
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
647
+ try {
648
+ await reconcileUnterminatedDirectDispatches(components, mesh, selfIds, localDaemonId);
649
+ } catch (e: any) {
650
+ LOG.warn('MeshReconcile', `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
651
+ }
652
+ }
653
+
654
+ // ── PHASE 5: auto-prune orphaned direct dispatch records ───────────────────
655
+ // staleDirectWork (orphaned direct-dispatch rows whose node/session is no longer in the
656
+ // live mesh) otherwise accumulates indefinitely: a removed worktree node or a cleanly
657
+ // terminated session leaves its direct-dispatch row behind, stuck in a non-terminal status
658
+ // (e.g. generating) for days. This is NOT a false-idle bug — it is the separate problem of
659
+ // orphaned records that the only existing cleanup path (manual MCP mesh_prune_stale_direct)
660
+ // never reaches unless an operator runs it by hand.
661
+ //
662
+ // This phase runs the SAME prune core the manual tool calls (pruneStaleDirectDispatches),
663
+ // in execute mode, on the daemon timer. The only difference from the manual path is a
664
+ // conservative age gate (DEFAULT_AUTO_PRUNE_MIN_AGE_MS): a freshly-orphaned record is held
665
+ // back until it is provably stale, so a transient probe miss never auto-prunes live work.
666
+ // Every other safety rule is inherited unchanged from the core — active/pending/generating
667
+ // work and fresh unacknowledged dispatch failures are never pruned, ledger-only audit entries
668
+ // are preserved, and the prune itself is recorded with a direct_dispatch_pruned ledger entry.
669
+ // Idempotent: a pruned row is gone from getActiveDirectDispatches, so the next tick finds
670
+ // nothing to re-prune. Isolated in its own try/catch per mesh so it can never kill the tick.
671
+ {
672
+ const minAgeMs = resolveAutoPruneMinAgeMs();
673
+ for (const mesh of listMeshes()) {
674
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
675
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
676
+ try {
677
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
678
+ } catch (e: any) {
679
+ LOG.warn('MeshReconcile', `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
680
+ }
681
+ }
682
+ }
683
+
684
+ // ── PHASE 2: inject into live CLI coordinators on this daemon ──────────────
685
+ const coordinators = findLiveCoordinators(components);
686
+ if (coordinators.length === 0) {
687
+ // No live CLI coordinator on this daemon — nothing to inject into.
688
+ // (MCP-only LLM coordinators drain the local queue via their own tool
689
+ // calls; PHASE 1 above has already populated it from remote nodes.)
690
+ return;
691
+ }
692
+
693
+ // Group coordinators by mesh; multiple coordinator instances for one mesh is
694
+ // unusual but supported (each gets the same drained events).
695
+ const byMesh = new Map<string, LiveCoordinator[]>();
696
+ for (const c of coordinators) {
697
+ const list = byMesh.get(c.meshId);
698
+ if (list) list.push(c);
699
+ else byMesh.set(c.meshId, [c]);
700
+ }
701
+
702
+ for (const [meshId, meshCoordinators] of byMesh) {
703
+ // Drain the local queue scoped to this coordinator daemon and inject.
704
+ // - If an idle coordinator exists, FULL-drain and deliver every event to it
705
+ // (the idle input box accepts the prompt as a real next turn). The drain
706
+ // marks consumed rows drained=1 atomically, so the pull path can't re-deliver.
707
+ // - If only GENERATING coordinators exist (no idle target), we HOLD: leave the
708
+ // events queued (drained=0) for the coordinator's next idle/turn-end tick.
709
+ //
710
+ // NOTIF-SURFACE-LOCAL (false-idle hold): we used to force-inject terminal events
711
+ // (completion/approval/stop/refine·bootstrap) straight into a *generating*
712
+ // coordinator's PTY (forceSendMessage → atomic content+\r write), on the theory it
713
+ // bypassed the busy send-guard and broke the await-result deadlock. But a raw PTY
714
+ // write into a claude-cli that is mid-generation is NOT consumed as a new turn — the
715
+ // bytes land in the terminal input buffer and the LLM never reads them on its next
716
+ // turn. The `surfaced/force-inject` trace fired, the row was marked drained=1, and the
717
+ // genuine completion was lost forever (the exact same-daemon local-worktree miss: the
718
+ // coordinator's OWN session is generating at the moment its worker completes). The
719
+ // deadlock the force path guarded against does not actually require force: a
720
+ // coordinator that dispatched a task via mesh_send_task returns to idle when that
721
+ // tool call resolves (dispatch is fire-and-forget; the worker runs for minutes while
722
+ // the coordinator is idle/between turns), so the completion lands on the very next
723
+ // idle tick (≤ one reconcile interval). Holding the event undrained for that idle
724
+ // tick is therefore the single, reliable delivery — and it is the SAME skip-and-hold
725
+ // the modal-park branch below already uses. This also makes double-injection
726
+ // structurally impossible: there is exactly one delivery path (the idle full-drain),
727
+ // so we never need a surface-time fingerprint to dedup a force-write against a re-drain.
728
+ const idleCoordinators = meshCoordinators.filter(c => c.idle);
729
+ // A coordinator parked on a harness modal (waiting_choice / waiting_approval) is
730
+ // non-idle; it is held under the modal-park branch (a force-inject into a modal would
731
+ // write raw keystrokes the modal key handler eats, silently selecting a choice the
732
+ // user never made). A plainly-generating coordinator (non-idle, non-modal-parked) is
733
+ // ALSO held now — for the false-idle reason above — but separately, so the C1 ledger
734
+ // audit and the operator-facing skip log can name the right hold reason.
735
+ const generatingCoordinators = meshCoordinators.filter(c => !c.idle && !c.modalParked);
736
+ const modalParkedCoordinators = meshCoordinators.filter(c => !c.idle && c.modalParked);
737
+ // Only an IDLE coordinator is a deliverable target. A generating coordinator's PTY
738
+ // does not consume an injected prompt as a turn, so it is held (not a target).
739
+ const targetCoordinators = idleCoordinators;
740
+
741
+ // ── no-idle-target short-circuit (MUST precede the drain) ─────────────────
742
+ // When there is no IDLE coordinator for this mesh — only generating and/or
743
+ // modal-parked ones — there is nowhere a queued event can land as a real turn.
744
+ // We skip-and-hold: by NOT draining we leave the events at drained=0 in the queue,
745
+ // so a later tick (once a coordinator returns to idle) delivers them. This
746
+ // short-circuit MUST run BEFORE drainPendingMeshCoordinatorEvents — the drain marks
747
+ // rows drained=1 atomically, which would lose the events for a coordinator that is
748
+ // only transiently busy (the false-idle local-worktree miss). Both the generating
749
+ // hold and the modal-park hold record a C1 ledger audit copy so a held completion's
750
+ // worker summary is recoverable even if the coordinator never returns or the pending
751
+ // file is later trimmed.
752
+ if (targetCoordinators.length === 0) {
753
+ if (modalParkedCoordinators.length > 0) {
754
+ // ── orphan escape (MUST precede the blanket modal-park hold) ──────────
755
+ // A modal-parked coordinator with no idle/generating sibling otherwise
756
+ // wedges EVERY pending event under `modal_parked` until that modal resolves
757
+ // — including a STRICT-routed completion whose originating coordinator
758
+ // session is GONE (an orphan: the worktree/session that produced it was
759
+ // removed, or that coordinator session died). Such an event will never be
760
+ // deliverable to its target session no matter what the modal-parked sibling
761
+ // does, so holding it under modal_parked is a permanent-held leak (the very
762
+ // "data restart re-reproduces it" symptom — the gate is reconstructed live
763
+ // from the still-parked modal, so a restart does not clear it). Route those
764
+ // orphan events through the strict-route hold/expire path so the bounded
765
+ // STRICT_SESSION_MATCH_TTL eventually expires them (recoverable, ledgered)
766
+ // instead of leaving them held forever. A strict event whose target session
767
+ // IS live but merely modal-parked is left to the blanket hold below (it is
768
+ // genuinely transiently blocked, not orphaned).
769
+ const liveSessionIds = new Set(
770
+ meshCoordinators.map(c => readNonEmptyString(c.sessionId)).filter(Boolean),
771
+ );
772
+ let orphanEscaped = 0;
773
+ const hasPendingForOrphanPeek = !store
774
+ || (() => { try { return store.pendingEventCount(meshId) > 0; } catch { return true; } })();
775
+ if (hasPendingForOrphanPeek) {
776
+ // Identify which pending event NAMES correspond to orphan-targeted events
777
+ // (a strict targetCoordinatorSessionId that matches no live coordinator).
778
+ let peeked: readonly PendingMeshCoordinatorEvent[] = [];
779
+ try {
780
+ peeked = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
781
+ } catch { peeked = []; }
782
+ const isOrphan = (e: PendingMeshCoordinatorEvent): boolean => {
783
+ const want = readNonEmptyString(e.targetCoordinatorSessionId);
784
+ return !!want && !liveSessionIds.has(want);
785
+ };
786
+ const orphanEventNames = new Set(peeked.filter(isOrphan).map(e => e.event));
787
+ if (orphanEventNames.size > 0) {
788
+ // The drain filter is event-NAME scoped (not per-row), so draining by the
789
+ // orphan event names also pulls any non-orphan event sharing that name. Drain
790
+ // them all, then re-route: orphan-targeted events go through the strict-route
791
+ // hold/expire path (bounded TTL → eventually ledger-expired, recoverable);
792
+ // non-orphan events of the same name are re-queued unchanged (queuedAt
793
+ // preserved) so they remain genuinely held for their still-live, modal-parked
794
+ // target. This is the same per-event strict routing PHASE 2 does below — just
795
+ // reached here because the blanket modal-park short-circuit would otherwise
796
+ // wedge the orphans forever.
797
+ let drained: PendingMeshCoordinatorEvent[] = [];
798
+ try {
799
+ drained = drainPendingMeshCoordinatorEvents(
800
+ meshId,
801
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
802
+ { onlyEvents: orphanEventNames },
803
+ );
804
+ } catch (e: any) {
805
+ LOG.warn('MeshReconcile', `Orphan-escape drain failed for mesh ${meshId}: ${e?.message || e}`);
806
+ drained = [];
807
+ }
808
+ for (const pending of drained) {
809
+ if (isOrphan(pending)) {
810
+ holdOrExpireStrictUnmatchedEvent(pending, readNonEmptyString(pending.targetCoordinatorSessionId), meshId);
811
+ orphanEscaped++;
812
+ } else {
813
+ // Still-live (modal-parked) target — re-queue unchanged so it is held
814
+ // for the next modal-resolved tick, exactly like the blanket hold would.
815
+ try { queuePendingMeshCoordinatorEvent(pending); } catch { /* best-effort re-queue */ }
816
+ }
817
+ }
818
+ }
819
+ }
820
+ LOG.info('MeshReconcile', `Reconcile skip → modal-parked: holding pending event(s) for mesh ${meshId} (${modalParkedCoordinators.length} coordinator(s) awaiting a modal answer; events left queued${orphanEscaped > 0 ? `; ${orphanEscaped} orphan-targeted event(s) routed to strict-route TTL` : ''})`);
821
+ // C1: mirror held terminal events into the ledger so a held completion's
822
+ // worker summary is auditable/recoverable even if the modal is never
823
+ // resolved, the coordinator restarts, or the pending file is later trimmed.
824
+ // The events stay queued (drained=0) for re-drain on a later tick; this only
825
+ // adds the durable audit copy. Idempotent per process — only newly-held
826
+ // events are logged. O(1)-gated: skip the peek when the queue is empty.
827
+ let hasPending = true;
828
+ if (store) {
829
+ try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
830
+ }
831
+ if (hasPending) {
832
+ recordHeldTerminalEventsToLedger(
833
+ meshId,
834
+ drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
835
+ 'modal_parked',
836
+ modalParkedCoordinators.length,
837
+ );
838
+ }
839
+ } else if (generatingCoordinators.length > 0) {
840
+ // ── generating hold (NOTIF-SURFACE-LOCAL false-idle fix) ─────────────
841
+ // The only coordinator(s) for this mesh are plainly generating (no idle, no
842
+ // modal). A raw force-write into a generating claude-cli PTY is not consumed
843
+ // as a turn, so we do NOT inject and do NOT drain — the events stay queued
844
+ // (drained=0) and the next tick that finds the coordinator idle full-drains
845
+ // them as real turns (the coordinator returns to idle when its current
846
+ // tool-call/turn resolves; a dispatched worker runs for minutes while the
847
+ // coordinator is idle, so this lands within one reconcile interval). C1: mirror
848
+ // any held terminal events into the ledger so a completion's worker summary is
849
+ // recoverable even before that idle tick. Idempotent per process; O(1)-gated.
850
+ let hasPending = true;
851
+ if (store) {
852
+ try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
853
+ }
854
+ if (hasPending) {
855
+ LOG.info('MeshReconcile', `Reconcile skip → generating: holding pending event(s) for mesh ${meshId} (${generatingCoordinators.length} coordinator(s) busy; events left queued for the next idle tick)`);
856
+ recordHeldTerminalEventsToLedger(
857
+ meshId,
858
+ drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
859
+ 'generating_no_idle_coordinator',
860
+ generatingCoordinators.length,
861
+ );
862
+ }
863
+ }
864
+ continue;
865
+ }
866
+
867
+ // O(1) guard: skip the drain entirely when the queue is empty.
868
+ if (store) {
869
+ try {
870
+ if (store.pendingEventCount(meshId) === 0) continue;
871
+ } catch { /* fall through to drain */ }
872
+ }
873
+
874
+ // An idle coordinator is present (targetCoordinators.length > 0): FULL-drain every
875
+ // queued event and deliver it to the idle input box as a real turn. The no-idle case
876
+ // (generating/modal-only) was already held above and never reaches here, so there is
877
+ // no force-drain-into-generating path left — the single delivery is the idle drain.
878
+ let pendingEvents: PendingMeshCoordinatorEvent[] = [];
879
+ try {
880
+ pendingEvents = drainPendingMeshCoordinatorEvents(
881
+ meshId,
882
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
883
+ );
884
+ } catch (e: any) {
885
+ LOG.warn('MeshReconcile', `Drain failed for mesh ${meshId}: ${e?.message || e}`);
886
+ continue;
887
+ }
888
+ if (pendingEvents.length === 0) continue;
889
+
890
+ LOG.info('MeshReconcile', `Reconcile inject → idle: ${pendingEvents.length} pending event(s) → ${targetCoordinators.length} coordinator(s) for mesh ${meshId}`);
891
+ for (const pending of pendingEvents) {
892
+ // Strict session routing (multi-coordinator): when the event names an
893
+ // originating coordinator session, deliver ONLY to the live coordinator whose
894
+ // session id matches — a sibling coordinator on the same daemon must NOT receive
895
+ // another coordinator's completion. When the event carries no session id (legacy /
896
+ // version-skewed / single-coordinator), fall back to the daemon-level set
897
+ // (unchanged behaviour — regression-0 for the common case).
898
+ const wantSession = readNonEmptyString(pending.targetCoordinatorSessionId);
899
+ if (wantSession) {
900
+ const matched = targetCoordinators.filter(c => c.sessionId === wantSession);
901
+ if (matched.length === 0) {
902
+ // The originating coordinator session is not deliverable on this daemon
903
+ // right now (gone, or modal-parked and excluded from targets). Strict mode
904
+ // does NOT broadcast to siblings — hold the event for a later tick, and
905
+ // ledger-expire it past a TTL so it can never wedge forever.
906
+ holdOrExpireStrictUnmatchedEvent(pending, wantSession, meshId);
907
+ continue;
908
+ }
909
+ for (const c of matched) injectPendingIntoCoordinator(c.instance, pending);
910
+ continue;
911
+ }
912
+ for (const c of targetCoordinators) {
913
+ injectPendingIntoCoordinator(c.instance, pending);
914
+ }
915
+ }
916
+ }
917
+ }
918
+
919
+ // Strict-routing TTL: how long a drained completion whose originating coordinator session
920
+ // is not currently deliverable is held (re-queued for re-drain) before it is ledger-
921
+ // expired. Bounded so a coordinator session that never returns cannot wedge the event
922
+ // forever; broad enough to ride out a transient modal-park / brief restart.
923
+ const STRICT_SESSION_MATCH_TTL_MS = 60_000;
924
+
925
+ // Re-queue (hold) a strict-routed event whose coordinator session is not live, or — once it
926
+ // has aged past STRICT_SESSION_MATCH_TTL_MS — ledger-expire it (recoverable) and drop it.
927
+ // We deliberately do NOT broadcast an aged-out event to sibling coordinators: that is the
928
+ // very misroute strict routing exists to prevent. The drain already marked the row drained=1,
929
+ // so re-queuing re-persists a fresh undrained copy (dedup keys on drained=0 only); queuedAt is
930
+ // preserved so the TTL measures the event's true age across re-queues.
931
+ function holdOrExpireStrictUnmatchedEvent(
932
+ pending: PendingMeshCoordinatorEvent,
933
+ wantSession: string,
934
+ meshId: string,
935
+ ): void {
936
+ const queuedAt = typeof pending.queuedAt === 'number' ? pending.queuedAt : Date.now();
937
+ if (Date.now() - queuedAt <= STRICT_SESSION_MATCH_TTL_MS) {
938
+ try {
939
+ queuePendingMeshCoordinatorEvent(pending); // preserves queuedAt → true age retained
940
+ LOG.info('MeshReconcile', `Strict route hold: coordinator session ${wantSession} not live on mesh ${meshId} — re-queued (${pending.event})`);
941
+ // EVTTRACE: event held (re-queued) — its originating coordinator session is not
942
+ // currently deliverable. Held, not dropped; surfaces later or expires past TTL.
943
+ traceMeshEventDrop('strict_route_hold', {
944
+ taskId: pending.metadataEvent?.taskId,
945
+ sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
946
+ nodeId: pending.nodeId,
947
+ meshId,
948
+ event: pending.event,
949
+ }, `coordinatorSession=${wantSession} not live`);
950
+ } catch (e: any) {
951
+ LOG.warn('MeshReconcile', `Strict route re-queue failed for ${pending.event} on mesh ${meshId}: ${e?.message || e}`);
952
+ }
953
+ return;
954
+ }
955
+ const finalSummary = readMeshCompletionSummary(pending.metadataEvent || {});
956
+ try {
957
+ appendLedgerEntry(meshId, {
958
+ kind: 'event_held',
959
+ ...(pending.nodeId ? { nodeId: pending.nodeId } : {}),
960
+ payload: {
961
+ event: pending.event,
962
+ reason: 'strict_route_expired',
963
+ recoverable: true,
964
+ targetCoordinatorSessionId: wantSession,
965
+ targetCoordinatorDaemonId: pending.targetCoordinatorDaemonId ?? null,
966
+ nodeLabel: pending.nodeLabel,
967
+ ...(pending.workspace ? { workspace: pending.workspace } : {}),
968
+ queuedAt,
969
+ ...(finalSummary ? { finalSummary } : {}),
970
+ },
971
+ });
972
+ LOG.warn('MeshReconcile', `Strict route expire: coordinator session ${wantSession} never returned for mesh ${meshId} — recorded to ledger (recoverable), dropped (${pending.event})`);
973
+ // EVTTRACE: event expired past the strict-route TTL — dropped (recoverable, ledgered).
974
+ traceMeshEventDrop('strict_route_expired', {
975
+ taskId: pending.metadataEvent?.taskId,
976
+ sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
977
+ nodeId: pending.nodeId,
978
+ meshId,
979
+ event: pending.event,
980
+ }, `coordinatorSession=${wantSession} never returned`);
981
+ } catch (e: any) {
982
+ LOG.warn('MeshReconcile', `Failed to ledger-expire strict-unmatched ${pending.event} for mesh ${meshId}: ${e?.message || e}`);
983
+ }
984
+ }
985
+
986
+ // Cloud-only: retry the worker-side unresolved-delegate forward outbox. For each
987
+ // durably-queued entry, push it to its coordinator daemon over P2P (mesh_forward_event)
988
+ // and ack (mark drained) ONLY on a successful, non-rejected response. A failed or
989
+ // rejected push leaves the entry queued for the next tick — at-least-once delivery.
990
+ // Stale entries (coordinator unreachable past the max age) are expired first so the
991
+ // outbox can't grow without bound. The coordinator dedups duplicate deliveries on its
992
+ // own fingerprint, so a retry that races the original immediate push is harmless.
993
+ // RECONCILE-MESHID-DROP: per-entry count of consecutive HARD rejections (the coordinator
994
+ // returned success:false, e.g. "meshId required"). A rejection means the push was delivered
995
+ // and deterministically refused — retrying the identical payload every 4s can never succeed,
996
+ // so it would loop until the 30-minute age expiry, spamming the log the whole time. After
997
+ // MAX_FORWARD_REJECTIONS such rejections we drop the entry (drain it) with ONE fail-loud
998
+ // warning. Transient transport failures (the dispatch throws — coordinator momentarily
999
+ // unreachable) do NOT count here; those legitimately retry until the age expiry. In-memory
1000
+ // (keyed by the durable outbox row id) is sufficient: a daemon restart re-arms the loop, and
1001
+ // the age expiry remains the durable backstop. Cleared whenever an entry is delivered/drained.
1002
+ const unresolvedForwardRejectionCounts = new Map<string, number>();
1003
+ const MAX_FORWARD_REJECTIONS = 5;
1004
+
1005
+ export function __resetUnresolvedForwardRejectionCountsForTests(): void {
1006
+ unresolvedForwardRejectionCounts.clear();
1007
+ }
1008
+
1009
+ async function retryUnresolvedDelegateForwards(components: DaemonComponents): Promise<void> {
1010
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1011
+ if (!dispatchMeshCommand) return;
1012
+
1013
+ // Drop entries that have exhausted their retry budget (fail-loud inside).
1014
+ expireStaleUnresolvedDelegateForwards();
1015
+
1016
+ const entries = peekUnresolvedDelegateForwards();
1017
+ if (entries.length === 0) {
1018
+ // Nothing queued — clear any stale per-entry rejection counters so the map can't grow.
1019
+ if (unresolvedForwardRejectionCounts.size > 0) unresolvedForwardRejectionCounts.clear();
1020
+ return;
1021
+ }
1022
+
1023
+ // Every id-form THIS daemon answers to. A self-addressed outbox entry (coordinator
1024
+ // == this daemon) must never be cross-dialled — see the self-route branch below.
1025
+ const selfIds = resolveCoordinatorDaemonIds(components);
1026
+ const isSelfCoordinatorId = (id: string): boolean =>
1027
+ selfIds.some(self => daemonIdsEquivalent(self, id));
1028
+
1029
+ for (const entry of entries) {
1030
+ // EVTTRACE correlation context for this outbox entry's retry.
1031
+ const entryTraceCtx = {
1032
+ taskId: (entry.payload as Record<string, unknown>).taskId,
1033
+ sessionId: readNonEmptyString(entry.payload.targetSessionId) || readNonEmptyString(entry.payload.sessionId),
1034
+ nodeId: readNonEmptyString(entry.payload.nodeId),
1035
+ event: readNonEmptyString(entry.payload.event),
1036
+ };
1037
+
1038
+ // Self-addressed forward: the coordinator daemon this entry targets IS this
1039
+ // daemon (a self-coordinating / single-node mesh, or a delegate whose coordinator
1040
+ // anchor resolved to our own id). A cross-daemon mesh_forward_event to our own id
1041
+ // is REFUSED by the dispatch self-dial guard ("Refusing to send ... to this
1042
+ // daemon's own id; route via the local router instead") on every retry, so the
1043
+ // entry can never be acked and loops forever (~every tick), spamming the log and
1044
+ // pinning the outbox row permanently undrained. Honour the guard's own advice:
1045
+ // route the event straight through the local receiver (handleMeshForwardEvent —
1046
+ // the same path the coordinator runs on receiving a remote push), then ack it.
1047
+ // We drain regardless of the local result: a cross-daemon dispatch could not have
1048
+ // resolved it either (the guard rejects before the receiver ever runs), so leaving
1049
+ // it queued only re-spams. handleMeshForwardEvent has the BEST recovery chance —
1050
+ // this daemon hosts the mesh, so its workspace/nodeId → meshId recovery applies.
1051
+ if (isSelfCoordinatorId(entry.coordinatorDaemonId)) {
1052
+ let localResult: any;
1053
+ try {
1054
+ traceMeshEventStage('forward_send', entryTraceCtx, `self → local router (${entry.coordinatorDaemonId})`);
1055
+ localResult = handleMeshForwardEvent(components, entry.payload);
1056
+ } catch (e: any) {
1057
+ LOG.warn('MeshReconcile', `Local route of self-addressed forward to ${entry.coordinatorDaemonId} threw: ${e?.message || e} — draining anyway to break the retry loop`);
1058
+ }
1059
+ ackUnresolvedDelegateForward(entry.id);
1060
+ unresolvedForwardRejectionCounts.delete(entry.id);
1061
+ if (localResult && localResult.success === false) {
1062
+ LOG.warn('MeshReconcile', `Self-addressed unresolved-delegate ${readNonEmptyString(entry.payload.event)} rejected by local router (${readNonEmptyString(localResult.error) || 'no reason'}) — drained to break the self-forward retry loop`);
1063
+ traceMeshEventDrop('self_forward_local_rejected', entryTraceCtx, readNonEmptyString(localResult.error) || 'no reason');
1064
+ } else {
1065
+ LOG.info('MeshReconcile', `Self-addressed unresolved-delegate ${readNonEmptyString(entry.payload.event)} routed via local router (coordinator ${entry.coordinatorDaemonId} is self) — drained`);
1066
+ }
1067
+ continue;
1068
+ }
1069
+
1070
+ // RECONCILE-MESHID-DROP: the stored forward payload was built when the worker
1071
+ // "couldn't resolve" its meshId, so the coordinator rejects it "meshId required"
1072
+ // when its own workspace/nodeId recovery misses. The worker can usually resolve it
1073
+ // now (member node membership / live-session meshNodeFor) — stamp it on so the
1074
+ // coordinator accepts. Covers entries persisted before this fix AND late-bound
1075
+ // sessions. No-op when the payload already carries a meshId or none is resolvable.
1076
+ let pushPayload = entry.payload;
1077
+ if (!readNonEmptyString(pushPayload.meshId)) {
1078
+ const recoveredMeshId = resolveForwardEventMeshId(components, pushPayload);
1079
+ if (recoveredMeshId) {
1080
+ pushPayload = { ...pushPayload, meshId: recoveredMeshId };
1081
+ traceMeshEventStage('forward_meshid_recovered', entryTraceCtx, `meshId=${recoveredMeshId}`);
1082
+ }
1083
+ }
1084
+
1085
+ let result: any;
1086
+ try {
1087
+ traceMeshEventStage('forward_send', entryTraceCtx, `retry → ${entry.coordinatorDaemonId}`);
1088
+ result = await dispatchMeshCommand(entry.coordinatorDaemonId, 'mesh_forward_event', pushPayload);
1089
+ } catch (e: any) {
1090
+ // Coordinator unreachable (transport threw) — keep the entry queued and try again
1091
+ // next tick. This is NOT a hard rejection, so it does not count toward the cap;
1092
+ // the age expiry bounds a permanently-offline coordinator.
1093
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} failed: ${e?.message || e} — left queued`);
1094
+ traceMeshEventDrop('retry_forward_failed', entryTraceCtx, e?.message || String(e));
1095
+ continue;
1096
+ }
1097
+ if (result && result.success === false) {
1098
+ // Hard rejection: the push was delivered and deterministically refused. Retrying
1099
+ // the identical payload can never succeed, so bound it — after MAX_FORWARD_REJECTIONS
1100
+ // drop (drain) the entry with one fail-loud warning instead of re-spamming every tick.
1101
+ const rejections = (unresolvedForwardRejectionCounts.get(entry.id) || 0) + 1;
1102
+ unresolvedForwardRejectionCounts.set(entry.id, rejections);
1103
+ const reason = readNonEmptyString(result.error) || 'no reason';
1104
+ if (rejections >= MAX_FORWARD_REJECTIONS) {
1105
+ ackUnresolvedDelegateForward(entry.id);
1106
+ unresolvedForwardRejectionCounts.delete(entry.id);
1107
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected ${rejections}x (${reason}) — dropping unresolved-delegate ${readNonEmptyString(entry.payload.event)} (sess=${readNonEmptyString(entry.payload.targetSessionId) || readNonEmptyString(entry.payload.sessionId) || '-'}) to stop the retry loop`);
1108
+ traceMeshEventDrop('retry_forward_exhausted', entryTraceCtx, `${reason} (${rejections} rejections)`);
1109
+ } else {
1110
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected (${reason}) — left queued (attempt ${rejections}/${MAX_FORWARD_REJECTIONS})`);
1111
+ traceMeshEventDrop('retry_forward_rejected', entryTraceCtx, reason);
1112
+ }
1113
+ continue;
1114
+ }
1115
+ // Acked — mark the durable copy delivered.
1116
+ ackUnresolvedDelegateForward(entry.id);
1117
+ unresolvedForwardRejectionCounts.delete(entry.id);
1118
+ LOG.info('MeshReconcile', `Retried+delivered unresolved-delegate ${readNonEmptyString(entry.payload.event)} to coordinator ${entry.coordinatorDaemonId}`);
1119
+ }
1120
+ }
1121
+
1122
+ // Cloud-only: poll each remote worker node daemon for pending coordinator events
1123
+ // and re-inject them locally via handleMeshForwardEvent (which re-queues +
1124
+ // surfaces to the live coordinator on the next tick / immediately if idle).
1125
+ //
1126
+ // Scoping: the remote handler (get_pending_mesh_events) drains its queue filtered
1127
+ // by coordinatorDaemonId — returning events targeted at that id OR unscoped, and
1128
+ // leaving events targeted at a *different* coordinator. A remote worker stamps the
1129
+ // coordinator id in one of SEVERAL forms (the canonical status id `standalone_`/
1130
+ // `daemon_<machineId>` stamped by the MCP layer, the bare machineId stamped by the
1131
+ // local queue path, OR — most commonly for remote launches — the coordinator mesh
1132
+ // node's config-form `daemonId`, which resolveCoordinatorDaemonId prefers and which
1133
+ // is NOT canonicalised). `candidateDaemonIds` is the already-expanded self-identity
1134
+ // set (resolveCoordinatorSelfIds: runtime drain ids ∪ this daemon's mesh-config node/
1135
+ // host id forms), so we pull ONCE PER candidate id and a completion stamped with any
1136
+ // of them is recovered. The remote drain is atomic (drained=1), so issuing multiple
1137
+ // pulls cannot double-deliver — the first pull that matches consumes the event; the
1138
+ // rest see nothing. When no ids resolve we fall back to a single unscoped pull.
1139
+ async function pullRemoteNodeQueues(
1140
+ components: DaemonComponents,
1141
+ mesh: LocalMeshEntry,
1142
+ localDaemonId: string | undefined,
1143
+ candidateDaemonIds: string[],
1144
+ ): Promise<void> {
1145
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1146
+ if (!dispatchMeshCommand) return;
1147
+ const meshId = mesh.id;
1148
+
1149
+ // One args object per candidate coordinator-id form, or a single unscoped pull
1150
+ // when none resolve.
1151
+ const pulls: Array<Record<string, unknown>> = candidateDaemonIds.length > 0
1152
+ ? candidateDaemonIds.map(id => ({ meshId, coordinatorDaemonId: id }))
1153
+ : [{ meshId }];
1154
+
1155
+ for (const node of mesh.nodes) {
1156
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
1157
+ // Skip nodes without a daemon, and nodes on THIS daemon (their events are
1158
+ // already in the local queue drained in PHASE 2). "This daemon" is matched
1159
+ // against the full self-identity set (candidateDaemonIds), not just the bare
1160
+ // localDaemonId — a self node can be registered under the config-form daemonId
1161
+ // (`daemon_<machineId>`) which would NOT equal bare localDaemonId, and pulling
1162
+ // from ourselves over P2P is both wasteful and a self-dispatch hazard.
1163
+ if (!nodeDaemonId) continue;
1164
+ if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) continue;
1165
+ if (daemonIdListIncludes(candidateDaemonIds, nodeDaemonId)) continue;
1166
+
1167
+ for (const pendingEventArgs of pulls) {
1168
+ let events: unknown;
1169
+ try {
1170
+ events = await dispatchMeshCommand(nodeDaemonId, 'get_pending_mesh_events', pendingEventArgs);
1171
+ } catch {
1172
+ // Remote pull is best-effort; the node may be offline. Retry next tick.
1173
+ break; // node unreachable — don't bother with the other id form this tick.
1174
+ }
1175
+ const list = extractPendingEvents(events).filter(e => readNonEmptyString(e?.meshId) === meshId);
1176
+ for (const event of list) {
1177
+ const payload = buildForwardPayloadFromPending(event);
1178
+ if (!payload.event || !payload.meshId) continue;
1179
+ try {
1180
+ handleMeshForwardEvent(components, payload);
1181
+ } catch { /* best-effort re-inject */ }
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ // Pull the read_chat payload out of whatever envelope the transport returned.
1188
+ // A local commandHandler.handle() returns the CommandResult directly; a remote
1189
+ // dispatchMeshCommand returns it possibly wrapped in { payload } / { result }.
1190
+ function unwrapReadChatPayload(raw: unknown): Record<string, unknown> | null {
1191
+ let cursor: unknown = raw;
1192
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === 'object'; depth++) {
1193
+ const record = cursor as Record<string, unknown>;
1194
+ if (Array.isArray(record.messages)) return record;
1195
+ if (record.payload && typeof record.payload === 'object') { cursor = record.payload; continue; }
1196
+ if (record.result && typeof record.result === 'object') { cursor = record.result; continue; }
1197
+ if (record.data && typeof record.data === 'object') { cursor = record.data; continue; }
1198
+ break;
1199
+ }
1200
+ return cursor && typeof cursor === 'object' ? cursor as Record<string, unknown> : null;
1201
+ }
1202
+
1203
+ function readChatPayloadStatus(payload: Record<string, unknown> | null): string {
1204
+ return readNonEmptyString(payload?.status).toLowerCase();
1205
+ }
1206
+
1207
+ // PHASE 4 helper. For every active (non-terminal) direct dispatch this daemon
1208
+ // hosts, confirm the worker session is idle via a read_chat and — if a final
1209
+ // assistant summary is present but no terminal ledger exists for that dispatch —
1210
+ // synthesize the missing completion through reconcileDirectDispatchCompletionFromTranscript.
1211
+ //
1212
+ // read_chat is resolved against the target node: a node on THIS daemon is read
1213
+ // through the local commandHandler; a remote node is read over P2P via
1214
+ // dispatchMeshCommand. Both yield the same { messages, status, providerSessionId }
1215
+ // shape. We only synthesize when the session reports idle AND a final assistant
1216
+ // message exists — the same evidence bar the MCP poll path uses — so an actively
1217
+ // generating worker is never falsely completed. The reconcile itself is idempotent.
1218
+ async function reconcileUnterminatedDirectDispatches(
1219
+ components: DaemonComponents,
1220
+ mesh: LocalMeshEntry,
1221
+ selfIds: string[],
1222
+ localDaemonId: string | undefined,
1223
+ ): Promise<void> {
1224
+ const dispatches = getActiveDirectDispatches(mesh.id);
1225
+ if (dispatches.length === 0) return; // cheap exit — nothing dispatched, nothing to reconcile
1226
+
1227
+ // Prune the in-flight idle debounce map to the tasks still active in THIS mesh, so a
1228
+ // completed/pruned task's counter is dropped (the map never grows without bound).
1229
+ const activeTaskKeys = new Set(
1230
+ dispatches
1231
+ .map(d => readNonEmptyString(d.taskId))
1232
+ .filter(Boolean)
1233
+ .map(taskId => inFlightSynthKey(mesh.id, taskId)),
1234
+ );
1235
+ for (const key of inFlightIdleObservationCounts.keys()) {
1236
+ if (key.startsWith(`${mesh.id}::`) && !activeTaskKeys.has(key)) {
1237
+ inFlightIdleObservationCounts.delete(key);
1238
+ }
1239
+ }
1240
+
1241
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1242
+ const nodeById = new Map(mesh.nodes.map(n => [n.id, n] as const));
1243
+
1244
+ for (const dispatch of dispatches) {
1245
+ const sessionId = readNonEmptyString(dispatch.sessionId);
1246
+ const nodeId = readNonEmptyString(dispatch.nodeId);
1247
+ const taskId = readNonEmptyString(dispatch.taskId);
1248
+ if (!sessionId || !nodeId || !taskId) continue;
1249
+
1250
+ const node = nodeById.get(nodeId);
1251
+ const nodeDaemonId = readNonEmptyString(node?.daemonId);
1252
+ // A node is local when it has no daemonId, names this daemon, or actually
1253
+ // has a live instance here. Anything else is reached over P2P.
1254
+ const isLocalNode = !nodeDaemonId
1255
+ || daemonIdListIncludes(selfIds, nodeDaemonId)
1256
+ || daemonIdsEquivalent(nodeDaemonId, localDaemonId)
1257
+ || !!components.instanceManager.getInstance(sessionId);
1258
+
1259
+ const providerType = readNonEmptyString(dispatch.providerType);
1260
+ const readArgs: Record<string, unknown> = {
1261
+ sessionId,
1262
+ targetSessionId: sessionId,
1263
+ tailLimit: 10,
1264
+ ...(node?.workspace ? { workspace: node.workspace } : {}),
1265
+ ...(providerType ? { agentType: providerType, providerType } : {}),
1266
+ };
1267
+
1268
+ let payload: Record<string, unknown> | null = null;
1269
+ try {
1270
+ if (isLocalNode) {
1271
+ const result = await components.commandHandler.handle('read_chat', readArgs);
1272
+ if (result && (result as { success?: boolean }).success === false) continue;
1273
+ payload = unwrapReadChatPayload(result);
1274
+ } else if (dispatchMeshCommand) {
1275
+ const result = await dispatchMeshCommand(nodeDaemonId, 'read_chat', readArgs);
1276
+ payload = unwrapReadChatPayload(result);
1277
+ if (payload && (payload as { success?: boolean }).success === false) continue;
1278
+ } else {
1279
+ continue; // remote node but no P2P transport — can't read; retry next tick
1280
+ }
1281
+ } catch {
1282
+ continue; // best-effort; session may be gone or node offline — retry next tick
1283
+ }
1284
+ if (!payload) continue;
1285
+
1286
+ // Only act on a session that has actually settled to idle. A generating /
1287
+ // waiting_approval session is mid-turn — synthesizing a completion now would
1288
+ // be wrong. (idle is the only status the MCP poll path reconciles too.)
1289
+ const synthKey = inFlightSynthKey(mesh.id, taskId);
1290
+ if (readChatPayloadStatus(payload) !== 'idle') {
1291
+ // Not idle → the worker is mid-turn. Reset any partial idle streak so a single
1292
+ // idle blip during a long generation never accumulates toward the synth threshold.
1293
+ inFlightIdleObservationCounts.delete(synthKey);
1294
+ continue;
1295
+ }
1296
+
1297
+ // RECONCILE-SYNTH-PREEMPTS-COMPLETION: a dispatch whose worker was OBSERVED to start
1298
+ // generating (the agent:generating_started ack flipped the row to 'acked') and has no
1299
+ // terminal yet is potentially still in-flight — its `idle` read here may be a transient
1300
+ // mid-turn flicker, not a settled completion. Require CONSECUTIVE idle observations
1301
+ // before synthesizing for such a task: a flicker clears next tick (counter reset above),
1302
+ // while a genuinely-settled (completed-but-lost) or dead session reads idle every tick
1303
+ // and crosses the threshold within ~one extra interval. A never-acked dispatch (worker
1304
+ // never started) is exempt — there is no in-flight generation to pre-empt, and its
1305
+ // lost-dispatch case is still covered by the downstream grace + stale-summary guards.
1306
+ if (dispatch.status === 'acked') {
1307
+ const idleStreak = (inFlightIdleObservationCounts.get(synthKey) ?? 0) + 1;
1308
+ inFlightIdleObservationCounts.set(synthKey, idleStreak);
1309
+ if (idleStreak < REQUIRED_CONSECUTIVE_IDLE_TICKS_FOR_INFLIGHT_SYNTH) {
1310
+ LOG.info('MeshReconcile', `In-flight synth hold: task ${taskId} on node ${nodeId} (mesh ${mesh.id}) read idle ${idleStreak}/${REQUIRED_CONSECUTIVE_IDLE_TICKS_FOR_INFLIGHT_SYNTH} consecutive tick(s) after generating_started — deferring completion synth until the idle settle is confirmed (guards against a mid-turn idle flicker pre-empting the real completion)`);
1311
+ continue;
1312
+ }
1313
+ }
1314
+
1315
+ const messages = Array.isArray(payload.messages) ? payload.messages as ChatMessage[] : [];
1316
+ const evidence = extractFinalAssistantSummaryEvidence(messages);
1317
+ if (!evidence.finalSummary) continue; // no assistant result yet — nothing to attribute
1318
+
1319
+ // STALE-SUMMARY guard (modal-parked / reused-session misattribution): a direct
1320
+ // dispatch frequently reuses a session that already ran a PRIOR task. read_chat
1321
+ // returns the tail of the WHOLE session, so extractFinalAssistantSummaryEvidence
1322
+ // picks the latest user-facing assistant message — which, for a task that has
1323
+ // barely started (the session momentarily reads idle between turns), is the prior
1324
+ // task's final summary. The downstream reconcile proves the summary is after the
1325
+ // LEDGER task_dispatched entry; here we additionally have the AUTHORITATIVE per-task
1326
+ // dispatchedAt (the dispatch-store row, immune to ledger-ordering quirks), so when
1327
+ // the selected transcript message is provably BEFORE this task's own dispatch we
1328
+ // refuse it outright — it is a prior task's summary, not this task's output (the
1329
+ // 2843ms-duration stale-summary bug where task 2e3f501e copy-pasted 4eca2d9d's
1330
+ // summary). When the message carries no usable timestamp we do NOT block here: the
1331
+ // downstream reconcile already rejects a non-JSON summary it cannot prove is
1332
+ // post-dispatch (transcript_not_proven_after_dispatch), and a structured
1333
+ // final_summary_json is self-attributing — so a timeless provider is not
1334
+ // over-blocked while the provable-stale case is still caught.
1335
+ const dispatchedAtMs = Date.parse(readNonEmptyString(dispatch.dispatchedAt));
1336
+ const transcriptAtMs = Date.parse(evidence.transcriptMessageAt ?? '');
1337
+ if (Number.isFinite(dispatchedAtMs) && Number.isFinite(transcriptAtMs) && transcriptAtMs < dispatchedAtMs) {
1338
+ LOG.info('MeshReconcile', `Stale-summary guard: skipping transcript reconcile for task ${taskId} on node ${nodeId} (mesh ${mesh.id}) — final assistant message (${evidence.transcriptMessageAt}) predates this task's dispatch (${dispatch.dispatchedAt}); it is a prior task's summary`);
1339
+ traceMeshEventDrop('reconcile_stale_summary_before_dispatch', {
1340
+ taskId, sessionId, nodeId, meshId: mesh.id, event: 'agent:generating_completed',
1341
+ }, `transcriptAt=${evidence.transcriptMessageAt} < dispatchedAt=${dispatch.dispatchedAt}`);
1342
+ continue;
1343
+ }
1344
+
1345
+ const providerSessionId = readNonEmptyString(payload.providerSessionId);
1346
+ const coordinatorDaemonId = selfIds.find(id => !!id);
1347
+ try {
1348
+ const result = reconcileDirectDispatchCompletionFromTranscript({
1349
+ meshId: mesh.id,
1350
+ nodeId,
1351
+ sessionId,
1352
+ providerType: providerType || undefined,
1353
+ providerSessionId: providerSessionId || undefined,
1354
+ taskId,
1355
+ finalSummary: evidence.finalSummary,
1356
+ ...(evidence.transcriptMessageAt ? { transcriptMessageAt: evidence.transcriptMessageAt } : {}),
1357
+ ...(coordinatorDaemonId ? { targetCoordinatorDaemonId: coordinatorDaemonId } : {}),
1358
+ source: 'daemon_reconcile_transcript_completion',
1359
+ });
1360
+ if (result.reconciled) {
1361
+ LOG.info('MeshReconcile', `Synthesized missing completion (${result.kind}) for task ${taskId} on node ${nodeId} (mesh ${mesh.id})`);
1362
+ }
1363
+ } catch (e: any) {
1364
+ LOG.warn('MeshReconcile', `Transcript completion reconcile threw for task ${taskId}: ${e?.message || e}`);
1365
+ }
1366
+ }
1367
+ }
1368
+
1369
+ // PHASE 5 helper. Build the live-node view (mesh.nodes decorated with each node's live
1370
+ // session list) and run the shared prune core in execute mode with the conservative age gate.
1371
+ //
1372
+ // Orphan detection needs the SAME live-session evidence the manual MCP prune uses: a node still
1373
+ // in mesh.nodes whose session list no longer contains the dispatched sessionId is "session not
1374
+ // present" (prunable); a node missing from mesh.nodes entirely is "node no longer in live mesh"
1375
+ // (prunable). We obtain live sessions per node via get_status_metadata — local nodes through the
1376
+ // local commandHandler, remote nodes over P2P (dispatchMeshCommand) — exactly the transports
1377
+ // PHASE 4 already uses. A node we cannot probe (offline) keeps an empty session list; combined
1378
+ // with the age gate that only matters once the orphan is genuinely old.
1379
+ //
1380
+ // O(1) fast exit: when there are no active direct dispatches at all there is nothing to prune,
1381
+ // so we skip the (per-node) status probes entirely — an idle mesh costs one indexed query.
1382
+ async function autoPruneStaleDirectDispatches(
1383
+ components: DaemonComponents,
1384
+ mesh: LocalMeshEntry,
1385
+ selfIds: string[],
1386
+ localDaemonId: string | undefined,
1387
+ minAgeMs: number,
1388
+ ): Promise<void> {
1389
+ const directDispatches = getActiveDirectDispatches(mesh.id);
1390
+ if (directDispatches.length === 0) return; // nothing dispatched → nothing to prune
1391
+
1392
+ const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
1393
+
1394
+ const result = pruneStaleDirectDispatches({
1395
+ meshId: mesh.id,
1396
+ queue: getQueue(mesh.id),
1397
+ ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
1398
+ directDispatches,
1399
+ nodes: liveNodes,
1400
+ execute: true,
1401
+ minAgeMs,
1402
+ source: 'daemon_reconcile_auto_prune',
1403
+ });
1404
+
1405
+ // Log only when something was actually pruned — silence on the common no-op tick.
1406
+ if (result.prunedCount > 0) {
1407
+ LOG.info('MeshReconcile', `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
1408
+ }
1409
+ }
1410
+
1411
+ // Probe each node for its live session list (get_status_metadata) and return mesh.nodes
1412
+ // decorated with a `sessions` array — the shape buildMeshActiveWork / sessionStatusFromNodes
1413
+ // consume to decide whether a dispatched session is still present. Best-effort: an unreachable
1414
+ // node yields an empty session list rather than throwing.
1415
+ async function collectLiveNodesWithSessions(
1416
+ components: DaemonComponents,
1417
+ mesh: LocalMeshEntry,
1418
+ selfIds: string[],
1419
+ localDaemonId: string | undefined,
1420
+ ): Promise<any[]> {
1421
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1422
+ return Promise.all(mesh.nodes.map(async (node) => {
1423
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
1424
+ const isLocalNode = !nodeDaemonId
1425
+ || daemonIdListIncludes(selfIds, nodeDaemonId)
1426
+ || daemonIdsEquivalent(nodeDaemonId, localDaemonId);
1427
+ let statusResult: unknown;
1428
+ try {
1429
+ if (isLocalNode) {
1430
+ statusResult = await components.commandHandler.handle('get_status_metadata', {});
1431
+ } else if (dispatchMeshCommand) {
1432
+ statusResult = await dispatchMeshCommand(nodeDaemonId, 'get_status_metadata', {});
1433
+ } else {
1434
+ return node; // remote node, no P2P transport — leave undecorated
1435
+ }
1436
+ } catch {
1437
+ return node; // unreachable — leave undecorated (empty session list)
1438
+ }
1439
+ const sessions = extractStatusMetadataSessions(statusResult);
1440
+ return sessions.length > 0 ? { ...node, sessions } : node;
1441
+ }));
1442
+ }
1443
+
1444
+ // Pull the live session list out of a get_status_metadata result, tolerating the same
1445
+ // envelope shapes unwrapReadChatPayload handles (direct CommandResult or { payload }/{ result }).
1446
+ function extractStatusMetadataSessions(raw: unknown): any[] {
1447
+ let cursor: unknown = raw;
1448
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === 'object'; depth++) {
1449
+ const record = cursor as Record<string, unknown>;
1450
+ const status = record.status && typeof record.status === 'object' ? record.status as Record<string, unknown> : undefined;
1451
+ if (status && Array.isArray(status.sessions)) return status.sessions;
1452
+ if (Array.isArray(record.sessions)) return record.sessions;
1453
+ if (record.payload && typeof record.payload === 'object') { cursor = record.payload; continue; }
1454
+ if (record.result && typeof record.result === 'object') { cursor = record.result; continue; }
1455
+ if (record.data && typeof record.data === 'object') { cursor = record.data; continue; }
1456
+ break;
1457
+ }
1458
+ return [];
1459
+ }
1460
+
1461
+ function extractPendingEvents(raw: unknown): any[] {
1462
+ if (Array.isArray(raw)) return raw;
1463
+ if (raw && typeof raw === 'object') {
1464
+ const events = (raw as Record<string, unknown>).events;
1465
+ if (Array.isArray(events)) return events;
1466
+ }
1467
+ return [];
1468
+ }
1469
+
1470
+ // Flatten a queued PendingMeshCoordinatorEvent into the flat payload shape
1471
+ // handleMeshForwardEvent expects (mirrors the MCP buildMeshForwardPayloadFromPendingEvent).
1472
+ function buildForwardPayloadFromPending(event: any): Record<string, unknown> {
1473
+ const metadata = event?.metadataEvent && typeof event.metadataEvent === 'object'
1474
+ ? event.metadataEvent as Record<string, unknown>
1475
+ : {};
1476
+ return {
1477
+ event: readNonEmptyString(event?.event),
1478
+ meshId: readNonEmptyString(event?.meshId),
1479
+ nodeId: readNonEmptyString(event?.nodeId) || readNonEmptyString(metadata.meshNodeId),
1480
+ workspace: readNonEmptyString(event?.workspace) || readNonEmptyString(metadata.workspace),
1481
+ // Preserve the originating coordinator session id across the relay. It is normally
1482
+ // carried inside metadataEvent.meshCoordinatorSessionId (spread below), but pass the
1483
+ // top-level field through explicitly too so the handleMeshForwardEvent whitelist
1484
+ // recovers it regardless of which carrier the producing daemon used.
1485
+ ...(readNonEmptyString(event?.targetCoordinatorSessionId)
1486
+ ? { targetCoordinatorSessionId: readNonEmptyString(event.targetCoordinatorSessionId) }
1487
+ : {}),
1488
+ ...metadata,
1489
+ // NOTIF-MISS (FIX 3): surface the dispatch task id at the TOP LEVEL so the relay's
1490
+ // received-stage trace (and buildRelayMetadataEvent) recovers it regardless of which
1491
+ // carrier the producing daemon used. The metadata spread above may carry the id only as
1492
+ // `meshActiveTaskId` (a worker provider event), leaving top-level `taskId` unset and the
1493
+ // received stage rendering `task=-`. Resolve both carriers into an explicit `taskId` so
1494
+ // dedup stays task-scoped end-to-end. Only set when a non-empty id exists (no clobber to
1495
+ // undefined when neither is present).
1496
+ ...((): Record<string, unknown> => {
1497
+ const tid = readNonEmptyString(metadata.taskId) || readNonEmptyString(metadata.meshActiveTaskId);
1498
+ return tid ? { taskId: tid } : {};
1499
+ })(),
1500
+ };
1501
+ }
1502
+
1503
+ interface ReconcileLoopHandle {
1504
+ stop(): void;
1505
+ }
1506
+
1507
+ // Start the periodic reconcile loop. Returns a handle with stop() for shutdown.
1508
+ export function setupMeshReconcileLoop(components: DaemonComponents): ReconcileLoopHandle {
1509
+ const intervalMs = resolveReconcileIntervalMs();
1510
+ let running = false;
1511
+ const timer = setInterval(() => {
1512
+ if (running) return; // never overlap ticks
1513
+ running = true;
1514
+ void runMeshReconcileTick(components)
1515
+ .catch((e: any) => LOG.warn('MeshReconcile', `Reconcile tick error: ${e?.message || e}`))
1516
+ .finally(() => { running = false; });
1517
+ }, intervalMs);
1518
+ // Don't keep the process alive solely for this timer.
1519
+ if (typeof timer.unref === 'function') timer.unref();
1520
+ LOG.info('MeshReconcile', `Mesh reconcile loop started (interval ${intervalMs}ms)`);
1521
+ return {
1522
+ stop() {
1523
+ clearInterval(timer);
1524
+ LOG.info('MeshReconcile', 'Mesh reconcile loop stopped');
1525
+ },
1526
+ };
1527
+ }