@adhdev/daemon-core 0.9.82-rc.36 → 0.9.82-rc.360

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 (325) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +55 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -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 +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +125 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +336 -1
  23. package/dist/commands/upgrade-helper.d.ts +41 -1
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +54 -13
  37. package/dist/index.js +44143 -17595
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +43858 -17438
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/logging/logger.d.ts +1 -1
  48. package/dist/mesh/contracts.d.ts +164 -0
  49. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  50. package/dist/mesh/coordinator-registry.d.ts +59 -0
  51. package/dist/mesh/mesh-active-work.d.ts +174 -0
  52. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  53. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  54. package/dist/mesh/mesh-events-coordinator.d.ts +170 -0
  55. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  56. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  57. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  58. package/dist/mesh/mesh-events.d.ts +6 -49
  59. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  60. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  61. package/dist/mesh/mesh-init.d.ts +86 -0
  62. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  63. package/dist/mesh/mesh-ledger.d.ts +77 -1
  64. package/dist/mesh/mesh-missions.d.ts +164 -0
  65. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  66. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  67. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  68. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  69. package/dist/mesh/mesh-routing.d.ts +70 -0
  70. package/dist/mesh/mesh-runtime-store.d.ts +429 -0
  71. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  72. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  73. package/dist/mesh/mesh-work-queue.d.ts +246 -5
  74. package/dist/mesh/preview-freshness.d.ts +18 -0
  75. package/dist/mesh/refine-config.d.ts +216 -0
  76. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  77. package/dist/providers/acp-provider-instance.d.ts +5 -0
  78. package/dist/providers/approval-utils.d.ts +20 -0
  79. package/dist/providers/chat-message-normalization.d.ts +12 -0
  80. package/dist/providers/cli-provider-instance.d.ts +106 -3
  81. package/dist/providers/contracts.d.ts +139 -6
  82. package/dist/providers/external-sources.d.ts +71 -0
  83. package/dist/providers/manual-attendance.d.ts +63 -0
  84. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  85. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  86. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  87. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  88. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  89. package/dist/providers/native-history/index.d.ts +13 -0
  90. package/dist/providers/provider-instance-manager.d.ts +14 -0
  91. package/dist/providers/provider-instance.d.ts +23 -1
  92. package/dist/providers/provider-loader.d.ts +26 -4
  93. package/dist/providers/provider-trust.d.ts +31 -0
  94. package/dist/providers/read-chat-contract.d.ts +29 -0
  95. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  96. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  97. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  98. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  99. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  100. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  101. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  102. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  103. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  104. package/dist/providers/sdk/v1/index.d.ts +30 -0
  105. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  106. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  107. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  108. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  109. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  110. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  111. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  112. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  113. package/dist/providers/spec/adapter.d.ts +91 -0
  114. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  115. package/dist/providers/spec/evaluator.d.ts +45 -0
  116. package/dist/providers/spec/fsm-driver.d.ts +368 -0
  117. package/dist/providers/spec/fsm-evaluator.d.ts +76 -0
  118. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  119. package/dist/providers/spec/fsm-types.d.ts +174 -0
  120. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  121. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  122. package/dist/providers/spec/route.d.ts +4 -0
  123. package/dist/providers/spec/types.d.ts +222 -0
  124. package/dist/providers/status-monitor.d.ts +7 -7
  125. package/dist/providers/transcript-v2.d.ts +176 -0
  126. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  127. package/dist/providers/working-dir.d.ts +17 -0
  128. package/dist/repo-mesh-types.d.ts +295 -13
  129. package/dist/sessions/registry.d.ts +6 -0
  130. package/dist/shared-types-extra.d.ts +2 -4
  131. package/dist/shared-types.d.ts +59 -2
  132. package/dist/status/normalize.d.ts +1 -1
  133. package/dist/status/normalize.js +1 -0
  134. package/dist/status/normalize.js.map +1 -1
  135. package/dist/status/normalize.mjs +1 -0
  136. package/dist/status/normalize.mjs.map +1 -1
  137. package/dist/status/reporter.d.ts +2 -0
  138. package/dist/status/snapshot.d.ts +26 -0
  139. package/dist/system/load-better-sqlite3.d.ts +21 -0
  140. package/dist/types.d.ts +5 -0
  141. package/package.json +7 -3
  142. package/src/agent-stream/poller.ts +2 -3
  143. package/src/agent-stream/provider-adapter.ts +1 -1
  144. package/src/boot/daemon-lifecycle.ts +55 -12
  145. package/src/boot/process-hardening.ts +89 -0
  146. package/src/build-info.ts +73 -0
  147. package/src/chat/source-machine.ts +534 -0
  148. package/src/chat/source-resolver.ts +0 -0
  149. package/src/chat/subscription-updates.ts +20 -1
  150. package/src/cli-adapter-types.d.ts +1 -0
  151. package/src/cli-adapter-types.ts +56 -2
  152. package/src/cli-adapters/cli-script-runner.ts +421 -0
  153. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  154. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  155. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  156. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  157. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  158. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  159. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  160. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  161. package/src/cli-adapters/pty-transport.ts +2 -1
  162. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  163. package/src/cli-adapters/resolve-executable.ts +90 -0
  164. package/src/cli-adapters/session-host-transport.ts +2 -1
  165. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  166. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  167. package/src/cli-adapters/terminal-screen.ts +16 -81
  168. package/src/commands/WINDOWS-UPGRADE-LOCK-FAILURE.md +198 -0
  169. package/src/commands/chat-commands.ts +1823 -62
  170. package/src/commands/cli-manager.ts +336 -19
  171. package/src/commands/handler.ts +841 -2
  172. package/src/commands/mesh-coordinator.ts +332 -122
  173. package/src/commands/router.ts +7624 -1312
  174. package/src/commands/stream-commands.ts +8 -0
  175. package/src/commands/upgrade-helper.ts +310 -45
  176. package/src/config/chat-history.ts +483 -24
  177. package/src/config/config.ts +12 -0
  178. package/src/config/mesh-config.ts +388 -6
  179. package/src/config/recent-activity.ts +8 -2
  180. package/src/daemon/dev-auto-implement.ts +3 -2
  181. package/src/daemon/dev-cli-debug.ts +10 -1
  182. package/src/detection/cli-detector.ts +28 -9
  183. package/src/detection/ide-detector.ts +55 -16
  184. package/src/detection/win32-ide-version.ts +106 -0
  185. package/src/git/change-impact-config.ts +354 -0
  186. package/src/git/git-commands.ts +55 -14
  187. package/src/git/git-diff.ts +81 -11
  188. package/src/git/git-executor.ts +12 -0
  189. package/src/git/git-status.ts +574 -43
  190. package/src/git/git-types.ts +14 -62
  191. package/src/git/git-worktree.ts +8 -1
  192. package/src/git/index.ts +16 -0
  193. package/src/index.ts +156 -12
  194. package/src/installer.d.ts +1 -1
  195. package/src/installer.ts +8 -6
  196. package/src/ipc/local-ipc-server.ts +278 -0
  197. package/src/launch.d.ts +1 -1
  198. package/src/launch.ts +37 -28
  199. package/src/logging/async-batch-writer.ts +55 -0
  200. package/src/logging/command-log.ts +7 -5
  201. package/src/logging/log-redactor.ts +100 -0
  202. package/src/logging/log-tail-reader.ts +220 -0
  203. package/src/logging/logger.ts +14 -7
  204. package/src/mesh/contracts.ts +329 -0
  205. package/src/mesh/coordinator-prompt.ts +234 -31
  206. package/src/mesh/coordinator-registry.ts +121 -0
  207. package/src/mesh/mesh-active-work.ts +667 -0
  208. package/src/mesh/mesh-delivery-policy.ts +315 -0
  209. package/src/mesh/mesh-event-trace.ts +67 -0
  210. package/src/mesh/mesh-events-coordinator.ts +2572 -0
  211. package/src/mesh/mesh-events-pending.ts +599 -0
  212. package/src/mesh/mesh-events-stale.ts +309 -0
  213. package/src/mesh/mesh-events-utils.ts +381 -0
  214. package/src/mesh/mesh-events.ts +30 -1035
  215. package/src/mesh/mesh-fast-forward.ts +839 -0
  216. package/src/mesh/mesh-host-ownership.ts +73 -0
  217. package/src/mesh/mesh-init.ts +260 -0
  218. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  219. package/src/mesh/mesh-ledger.ts +591 -102
  220. package/src/mesh/mesh-missions.ts +322 -0
  221. package/src/mesh/mesh-reconcile-loop.ts +1096 -0
  222. package/src/mesh/mesh-refine-batch.ts +197 -0
  223. package/src/mesh/mesh-refine-status.ts +231 -0
  224. package/src/mesh/mesh-review-inbox.ts +307 -0
  225. package/src/mesh/mesh-routing.ts +291 -0
  226. package/src/mesh/mesh-runtime-store.ts +1697 -0
  227. package/src/mesh/mesh-task-stats.ts +161 -0
  228. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  229. package/src/mesh/mesh-work-queue.ts +997 -141
  230. package/src/mesh/preview-freshness.ts +118 -0
  231. package/src/mesh/refine-config.ts +423 -0
  232. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  233. package/src/providers/acp-provider-instance.ts +43 -10
  234. package/src/providers/approval-utils.d.ts +5 -0
  235. package/src/providers/approval-utils.ts +57 -5
  236. package/src/providers/chat-message-normalization.ts +45 -5
  237. package/src/providers/cli-provider-instance.ts +1254 -101
  238. package/src/providers/contracts.d.ts +55 -0
  239. package/src/providers/contracts.ts +150 -6
  240. package/src/providers/extension-provider-instance.ts +12 -7
  241. package/src/providers/external-sources.ts +218 -0
  242. package/src/providers/ide-provider-instance.ts +35 -12
  243. package/src/providers/manual-attendance.ts +85 -0
  244. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  245. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  246. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  247. package/src/providers/native-history/dispatcher.ts +340 -0
  248. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  249. package/src/providers/native-history/index.ts +30 -0
  250. package/src/providers/provider-instance-manager.ts +30 -0
  251. package/src/providers/provider-instance.ts +19 -1
  252. package/src/providers/provider-loader.ts +670 -50
  253. package/src/providers/provider-schema.ts +87 -14
  254. package/src/providers/provider-trust.ts +114 -0
  255. package/src/providers/read-chat-contract.ts +76 -16
  256. package/src/providers/sdk/README.md +49 -0
  257. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  258. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  259. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  260. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  261. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  262. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  263. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  264. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  265. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  266. package/src/providers/sdk/v1/index.ts +152 -0
  267. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  268. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  269. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  270. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  271. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  272. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  280. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  281. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  282. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  283. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  284. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  285. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  286. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  287. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  288. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  289. package/src/providers/sdk/v1/validators/index.ts +19 -0
  290. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  291. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  292. package/src/providers/spec/adapter.ts +235 -0
  293. package/src/providers/spec/cli-adapter.ts +1051 -0
  294. package/src/providers/spec/evaluator.ts +407 -0
  295. package/src/providers/spec/fsm-driver.ts +1251 -0
  296. package/src/providers/spec/fsm-evaluator.ts +272 -0
  297. package/src/providers/spec/fsm-loader.ts +120 -0
  298. package/src/providers/spec/fsm-types.ts +273 -0
  299. package/src/providers/spec/native-history-executor.ts +1136 -0
  300. package/src/providers/spec/pre-launch-trust.ts +104 -0
  301. package/src/providers/spec/route.ts +51 -0
  302. package/src/providers/spec/types.ts +262 -0
  303. package/src/providers/status-monitor.d.ts +7 -7
  304. package/src/providers/status-monitor.ts +37 -22
  305. package/src/providers/transcript-v2.ts +567 -0
  306. package/src/providers/types/interactive-prompt.ts +536 -0
  307. package/src/providers/version-archive.ts +64 -24
  308. package/src/providers/working-dir.ts +23 -0
  309. package/src/repo-mesh-types.ts +378 -14
  310. package/src/sessions/registry.ts +6 -0
  311. package/src/shared-types-extra.ts +2 -4
  312. package/src/shared-types.d.ts +8 -0
  313. package/src/shared-types.ts +64 -1
  314. package/src/status/builders.ts +26 -6
  315. package/src/status/normalize.ts +2 -0
  316. package/src/status/reporter.ts +19 -1
  317. package/src/status/snapshot.ts +95 -26
  318. package/src/system/host-memory.ts +29 -12
  319. package/src/system/load-better-sqlite3.ts +68 -0
  320. package/src/types.ts +5 -0
  321. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  322. package/dist/mesh/mesh-sync.d.ts +0 -53
  323. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  324. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  325. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1096 @@
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, MESH_FORCE_INJECT_EVENTS, triggerMeshQueue } 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 } from './mesh-work-queue.js';
62
+ import { readLedgerEntries } from './mesh-ledger.js';
63
+ import { pruneStaleDirectDispatches } from './mesh-active-work.js';
64
+ import { 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
+ interface LiveCoordinator {
101
+ meshId: string;
102
+ instance: ReturnType<DaemonComponents['instanceManager']['getInstance']>;
103
+ // Runtime session id of this coordinator instance (getState().instanceId). PHASE 2
104
+ // strict-matches an event's targetCoordinatorSessionId against this so a completion
105
+ // routes back to the exact originating coordinator session, not a sibling on the same
106
+ // daemon (the multi-coordinator misroute).
107
+ sessionId: string;
108
+ idle: boolean;
109
+ // True when the coordinator session is parked on a harness modal awaiting a
110
+ // human answer — claude-cli AskUserQuestion (waiting_choice) or a tool-consent
111
+ // prompt (waiting_approval). A force-inject into such a session would write raw
112
+ // keystrokes the modal key handler consumes, silently selecting a choice the
113
+ // user never made (data corruption). PHASE 2 excludes these from force-inject
114
+ // and leaves the event queued for a later (modal-resolved) tick.
115
+ modalParked: boolean;
116
+ }
117
+
118
+ // The set of coordinator-daemon ids THIS daemon answers to when draining the
119
+ // pending-events queue. A unicast completion event is stamped with the worker's
120
+ // meshCoordinatorDaemonId, which can be either:
121
+ // - the daemon's canonical status id (`standalone_<machineId>` / `daemon_<machineId>`),
122
+ // stamped by the MCP layer via ctx.localDaemonId (= getStatus().status.instanceId), or
123
+ // - the bare machineId, stamped by the local queue-assignment path (loadConfig().machineId).
124
+ // - the config-form node daemonId (`daemon_<machineId>`), which the MCP layer's
125
+ // resolveCoordinatorDaemonId prefers and stamps onto direct-dispatch workers.
126
+ // Draining with only one of these silently misses events stamped with the other —
127
+ // the exact reason a generating coordinator never self-received local completions,
128
+ // and the base-node completion-surface bug (base completions land full-form
129
+ // `daemon_<machineId>` while a coordinator that only knows itself as bare
130
+ // `<machineId>` never matches them). We expand to EVERY equivalent form so the
131
+ // scope match (host gate, self-node detection, and the drain IN-filter downstream)
132
+ // succeeds regardless of which path stamped the event.
133
+ function resolveCoordinatorDaemonIds(components: DaemonComponents): string[] {
134
+ const statusInstanceId = readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId);
135
+ const machineId = readNonEmptyString(loadConfig().machineId);
136
+ return expandDaemonIdForms([statusInstanceId, machineId]);
137
+ }
138
+
139
+ // Whether THIS daemon is the coordinator/host for a mesh — i.e. the daemon that
140
+ // owns coordinator ownership and must collect every worker node's completion
141
+ // events into its local queue. This is true regardless of whether a *live CLI*
142
+ // coordinator session currently exists: the coordinator is frequently a pure
143
+ // stdio MCP LLM (no live CLI session to inject into), and that LLM only sees the
144
+ // queue when it next calls a mesh tool. For it to see remote worker completions
145
+ // at all, the daemon must have already pulled them into the local queue on the
146
+ // timer — which is exactly what this predicate gates.
147
+ //
148
+ // Rule: this daemon hosts the mesh when meshHost.role is 'host' (the default for
149
+ // standalone-compat meshes with no host metadata) AND, when a hostDaemonId is
150
+ // pinned, it resolves to one of this daemon's ids. Member-only daemons return
151
+ // false — their own queue is pulled BY the host, not the other way around.
152
+ //
153
+ // `daemonIds` here is the EXPANDED self-identity set (runtime drain ids ∪ this
154
+ // daemon's mesh-config node id forms) — see resolveCoordinatorSelfIds. The
155
+ // pinned hostDaemonId is itself a config-form id and frequently does NOT equal a
156
+ // runtime id (bare machineId / status id), so gating on the runtime ids alone
157
+ // would wrongly classify the real host as a non-host and skip the remote pull
158
+ // entirely.
159
+ function daemonHostsMesh(mesh: LocalMeshEntry, daemonIds: string[]): boolean {
160
+ const host = mesh.meshHost;
161
+ // No metadata → default host (standalone compatibility, see createDefaultMeshHostMetadata).
162
+ if (!host) return true;
163
+ if (host.role && host.role !== 'host') return false;
164
+ const hostDaemonId = readNonEmptyString(host.hostDaemonId);
165
+ // Host role but no pinned hostDaemonId → treat as host (single-daemon / legacy).
166
+ if (!hostDaemonId) return true;
167
+ return daemonIds.includes(hostDaemonId);
168
+ }
169
+
170
+ // Resolve EVERY id-form this daemon answers to FOR A GIVEN MESH: the runtime drain
171
+ // ids (status id + bare machineId) unioned with this daemon's mesh-config identity
172
+ // forms — the self node's daemonId/machineId (the node whose daemonId/machineId
173
+ // matches a runtime id) and the pinned meshHost.hostDaemonId WHEN it is provably
174
+ // ours. This is the single source of truth for "is this id me?" across both the
175
+ // host gate and the remote pull filter; the worker's meshCoordinatorDaemonId stamp
176
+ // is guaranteed to be one of these forms (it comes from resolveCoordinatorDaemonId,
177
+ // which prefers the coordinator node's config-form daemonId over the runtime status id).
178
+ function resolveCoordinatorSelfIds(mesh: LocalMeshEntry, drainDaemonIds: string[]): string[] {
179
+ const ids = new Set<string>(drainDaemonIds);
180
+ // Expand with the config-form id(s) of the self node — the mesh node whose
181
+ // daemonId/machineId matches a runtime id. Its config-form daemonId is exactly
182
+ // what resolveCoordinatorNode()→resolveCoordinatorDaemonId() stamps onto a worker.
183
+ for (const node of mesh.nodes) {
184
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
185
+ const nodeMachineId = readNonEmptyString(node.machineId);
186
+ const isSelf = (nodeDaemonId && drainDaemonIds.includes(nodeDaemonId))
187
+ || (nodeMachineId && drainDaemonIds.includes(nodeMachineId));
188
+ if (!isSelf) continue;
189
+ if (nodeDaemonId) ids.add(nodeDaemonId);
190
+ if (nodeMachineId) ids.add(nodeMachineId);
191
+ }
192
+ // The pinned host id is included ONLY when it is provably one of THIS daemon's ids
193
+ // (it already matches a runtime id or a resolved self-node id). A hostDaemonId that
194
+ // names a DIFFERENT daemon must NOT be claimed — that would make a member-only
195
+ // daemon believe it is the host and pull queues it does not own. Having a node on
196
+ // this daemon does not make this daemon the host; daemonHostsMesh still honours a
197
+ // foreign hostDaemonId and rejects ownership.
198
+ const hostDaemonId = readNonEmptyString(mesh.meshHost?.hostDaemonId);
199
+ if (hostDaemonId && ids.has(hostDaemonId)) ids.add(hostDaemonId);
200
+ return [...ids];
201
+ }
202
+
203
+ // Find live CLI coordinator instances on THIS daemon, keyed by mesh.
204
+ function findLiveCoordinators(components: DaemonComponents): LiveCoordinator[] {
205
+ const out: LiveCoordinator[] = [];
206
+ for (const inst of components.instanceManager.getByCategory('cli')) {
207
+ const state = inst.getState();
208
+ const settings = state.settings && typeof state.settings === 'object'
209
+ ? state.settings as Record<string, unknown>
210
+ : {};
211
+ const meshId = readNonEmptyString(settings.meshCoordinatorFor);
212
+ if (!meshId) continue;
213
+ const status = readNonEmptyString(state.status).toLowerCase();
214
+ // getState() overlays the modal-park statuses: an active AskUserQuestion
215
+ // prompt surfaces as waiting_choice, a tool-consent prompt as waiting_approval.
216
+ // Lowercase literal compare — the SessionStatus enum is forked across modules
217
+ // and waiting_choice is absent from some of them (see cli-provider-instance).
218
+ const modalParked = status === 'waiting_choice' || status === 'waiting_approval';
219
+ const sessionId = readNonEmptyString(state.instanceId);
220
+ out.push({ meshId, instance: inst, sessionId, idle: status === 'idle', modalParked });
221
+ }
222
+ return out;
223
+ }
224
+
225
+ // Inject a drained pending event into a live coordinator session. Force-inject
226
+ // events carry force:true so they bypass the busy send-guard and land in the PTY
227
+ // even while the coordinator is generating (see shouldForceInjectMeshEvent).
228
+ function injectPendingIntoCoordinator(
229
+ coordinator: LiveCoordinator['instance'],
230
+ pending: PendingMeshCoordinatorEvent,
231
+ ): void {
232
+ if (!coordinator || !pending.coordinatorMessage) return;
233
+ const force = shouldForceInjectMeshEvent(pending.event);
234
+ // EVTTRACE: event surfaced to the coordinator (injected into its live CLI session).
235
+ // This is the terminal happy-path stage. Observation only.
236
+ traceMeshEventStage('surfaced', {
237
+ taskId: pending.metadataEvent?.taskId,
238
+ sessionId: pending.metadataEvent?.targetSessionId ?? pending.targetCoordinatorSessionId,
239
+ nodeId: pending.nodeId,
240
+ meshId: pending.meshId,
241
+ event: pending.event,
242
+ }, force ? 'force-inject' : 'inject');
243
+ coordinator.onEvent('send_message', {
244
+ input: { text: pending.coordinatorMessage, textFallback: pending.coordinatorMessage },
245
+ ...(force ? { force: true } : {}),
246
+ });
247
+ }
248
+
249
+ // Held-event ledger dedup: fingerprints of held terminal events already written as an
250
+ // `event_held` ledger audit record in THIS process. Prevents the 4s reconcile tick from
251
+ // re-logging the same held event every interval while a coordinator stays modal-parked.
252
+ // Per-process only (not persisted) — if the daemon restarts while an event is still held
253
+ // it is re-logged once, which is desirable: it re-confirms the event is still undelivered.
254
+ const heldEventLedgerRecorded = new Set<string>();
255
+
256
+ // C1 (data safety): when a terminal completion/approval/bootstrap event cannot be
257
+ // delivered because the only coordinators are modal-parked, the event is held at
258
+ // drained=0 in the pending queue (SQLite + JSONL) for a later tick. That queue is
259
+ // disk-persisted but carries no operator-visible audit trail and can be silently
260
+ // dropped by the pending-file trim (100 KB / 50-entry cap). To guarantee a held
261
+ // completion's worker summary is never silently lost, mirror each held terminal event
262
+ // into the coordinator's mesh ledger as an `event_held` entry — auditable and
263
+ // recoverable (the finalSummary survives even if the pending copy is later trimmed or
264
+ // the coordinator session is force-resolved before re-drain). Idempotent per process
265
+ // via heldEventLedgerRecorded so a long modal park does not spam the ledger.
266
+ function recordHeldTerminalEventsToLedger(
267
+ meshId: string,
268
+ drainDaemonIds: string[],
269
+ reason: string,
270
+ heldForCoordinatorCount: number,
271
+ ): void {
272
+ let pending: readonly PendingMeshCoordinatorEvent[];
273
+ try {
274
+ pending = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
275
+ } catch {
276
+ return; // best-effort audit — never let a peek failure break the tick
277
+ }
278
+ for (const event of pending) {
279
+ // Only audit terminal/force-inject events (completion / approval / stop / refine·
280
+ // bootstrap). Silent lifecycle events (agent:ready / generating_started) carry no
281
+ // worker output to preserve and re-drain harmlessly, so they need no audit trail.
282
+ if (!shouldForceInjectMeshEvent(event.event)) continue;
283
+ const fingerprint = buildPendingEventFingerprint(event);
284
+ const key = `${meshId}::${fingerprint || `${event.event}::${event.nodeId || ''}::${event.queuedAt}`}`;
285
+ if (heldEventLedgerRecorded.has(key)) continue;
286
+ heldEventLedgerRecorded.add(key);
287
+ const finalSummary = readMeshCompletionSummary(event.metadataEvent);
288
+ try {
289
+ appendLedgerEntry(meshId, {
290
+ kind: 'event_held',
291
+ ...(event.nodeId ? { nodeId: event.nodeId } : {}),
292
+ payload: {
293
+ event: event.event,
294
+ reason,
295
+ recoverable: true,
296
+ heldForCoordinators: heldForCoordinatorCount,
297
+ nodeLabel: event.nodeLabel,
298
+ ...(event.workspace ? { workspace: event.workspace } : {}),
299
+ targetCoordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
300
+ queuedAt: event.queuedAt,
301
+ ...(fingerprint ? { fingerprint } : {}),
302
+ ...(finalSummary ? { finalSummary } : {}),
303
+ },
304
+ });
305
+ LOG.info('MeshReconcile', `Ledger-recorded held ${event.event} for mesh ${meshId} (reason ${reason}) — recoverable from ledger`);
306
+ } catch (e: any) {
307
+ // Failed to persist — drop the dedup marker so the next tick retries.
308
+ heldEventLedgerRecorded.delete(key);
309
+ LOG.warn('MeshReconcile', `Failed to ledger-record held ${event.event} for mesh ${meshId}: ${e?.message || e}`);
310
+ }
311
+ }
312
+ }
313
+
314
+ // One reconcile tick. Two independent phases:
315
+ //
316
+ // PHASE 1 — Remote queue pull (the fix for remote worktree completions never
317
+ // reaching an MCP/LLM coordinator). For EVERY mesh this daemon hosts/
318
+ // coordinates, pull each remote worker node's pending-events queue over P2P
319
+ // into THIS daemon's local queue. This runs *regardless of whether a live CLI
320
+ // coordinator exists* — the coordinator is usually a pure stdio MCP LLM with
321
+ // no live CLI session, and it can only observe a remote worker's completion
322
+ // once that event has been pulled into the local queue (which it then drains
323
+ // on its next mesh tool call). Previously this pull was gated behind a live
324
+ // CLI coordinator and so never ran for MCP/LLM coordinators — remote
325
+ // completions sat on the remote node's queue until the LLM happened to call
326
+ // mesh_read_chat, which triggered the MCP-side pull. The daemon now does it
327
+ // autonomously on the timer. Standalone (no dispatchMeshCommand) skips this
328
+ // phase entirely — there are no remote nodes to pull from.
329
+ //
330
+ // PHASE 2 — Live CLI inject. For each mesh that has a live CLI coordinator on
331
+ // THIS daemon, drain the local queue and inject pending events into the PTY.
332
+ // Unchanged from before.
333
+ // Bug B: how long a row may sit 'assigned' with an unconfirmed dispatch before the
334
+ // watchdog reclaims it. Must be comfortably larger than the per-dispatch confirm
335
+ // timeout (DISPATCH_CONFIRM_TIMEOUT_MS in mesh-events-coordinator) so a slow-but-live
336
+ // dispatch still inside its normal confirm window is never reclaimed early — this is
337
+ // the durable backstop for the case the in-process confirm timer can't cover (a timer
338
+ // lost to a daemon restart between claim and confirm).
339
+ const ASSIGNED_STRANDED_DEADLINE_MS = 5 * 60_000;
340
+
341
+ // PHASE 2.5 — assigned-stranded dispatch watchdog (Bug B). claimNextTask atomically
342
+ // flips a row to 'assigned' BEFORE the fire-and-forget dispatch runs. If that dispatch
343
+ // neither rejects (→ no .catch requeue) nor is confirmed delivered — a relay that hangs
344
+ // without acking, or a confirm timer lost across a restart — the row stays 'assigned'
345
+ // forever: it contributes 0 pending, so PHASE 3 (gated on pendingQueueTaskCount>0) never
346
+ // re-examines it, and nothing but a manual requeue clears it. This is that missing net.
347
+ //
348
+ // Regression guard: a row whose delivery IS confirmed (delivered/acked/completed) is a
349
+ // genuinely in-flight (or completion-lost) task — left to PHASE 4's completion reconcile,
350
+ // never reclaimed here. And the deadline is generous so a slow-but-live dispatch still in
351
+ // its normal confirm window is never reclaimed early. Reclaimed rows return to 'pending'
352
+ // with ownership cleared, so the PHASE 3 trigger below re-dispatches them this same tick.
353
+ function recoverStrandedAssignedDispatches(meshId: string, store: MeshRuntimeStore): void {
354
+ const assigned = getQueue(meshId, { status: ['assigned'] });
355
+ if (!assigned.length) return;
356
+ const nowMs = Date.now();
357
+ for (const row of assigned) {
358
+ const dispatchedAtMs = Date.parse(row.dispatchTimestamp ?? '');
359
+ if (!Number.isFinite(dispatchedAtMs)) continue; // no dispatch ts → can't age it
360
+ if (nowMs - dispatchedAtMs < ASSIGNED_STRANDED_DEADLINE_MS) continue; // still in confirm window
361
+ if (store.taskHasConfirmedDelivery(meshId, row.id)) continue; // dispatched → PHASE 4's job
362
+ const reclaimed = reclaimStrandedAssignedTask(meshId, row.id, {
363
+ reason: 'assigned_stranded_dispatch_unconfirmed',
364
+ ageMs: nowMs - dispatchedAtMs,
365
+ });
366
+ if (reclaimed) {
367
+ LOG.warn('MeshReconcile', `Reclaimed stranded assigned task ${row.id} on mesh ${meshId} `
368
+ + `(node=${row.assignedNodeId ?? '?'} session=${row.assignedSessionId ?? '?'}, dispatched `
369
+ + `${Math.round((nowMs - dispatchedAtMs) / 1000)}s ago, never confirmed delivered → ${reclaimed.status})`);
370
+ // EVTTRACE: the dispatch for this task was stranded (assigned, never confirmed
371
+ // delivered) and reclaimed (CANON-B) — its expected completion event never
372
+ // arrived. Observation only; the reclaim decision above is unchanged.
373
+ traceMeshEventDrop('assigned_stranded_reclaim', {
374
+ taskId: row.id,
375
+ sessionId: row.assignedSessionId,
376
+ nodeId: row.assignedNodeId,
377
+ meshId,
378
+ event: 'agent:generating_completed',
379
+ }, `unconfirmed ${Math.round((nowMs - dispatchedAtMs) / 1000)}s → ${reclaimed.status}`);
380
+ }
381
+ }
382
+ }
383
+
384
+ export async function runMeshReconcileTick(components: DaemonComponents): Promise<void> {
385
+ const localDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
386
+ // The id-set used to scope the local queue drain (status id + machineId). See
387
+ // resolveCoordinatorDaemonIds — the status id is what the MCP layer stamps and
388
+ // is mandatory here for a generating CLI coordinator to self-receive completions.
389
+ const drainDaemonIds = resolveCoordinatorDaemonIds(components);
390
+ const dispatchMeshCommand = components.dispatchMeshCommand;
391
+ const store = (() => {
392
+ try { return MeshRuntimeStore.getInstance(); } catch { return undefined; }
393
+ })();
394
+
395
+ // ── PHASE 0: retry the worker-side unresolved-delegate forward outbox ──────
396
+ // Cloud-only (needs dispatchMeshCommand). A worker that is NOT a member of the
397
+ // coordinator's mesh cannot be reached by the coordinator's PHASE 1 pull (it is
398
+ // in no mesh.node), so its completion must be PUSHED to the coordinator. This
399
+ // drains the durable outbox enqueued by forwardUnresolvedDelegateEvent and retries
400
+ // any push that has not yet been acked. See mesh-unresolved-forward-outbox.ts.
401
+ if (dispatchMeshCommand) {
402
+ try {
403
+ await retryUnresolvedDelegateForwards(components);
404
+ } catch (e: any) {
405
+ LOG.warn('MeshReconcile', `Unresolved-delegate forward retry failed: ${e?.message || e}`);
406
+ }
407
+ }
408
+
409
+ // ── PHASE 1: pull remote node queues for every mesh this daemon hosts ──────
410
+ // Cloud-only (dispatchMeshCommand present). Runs whether or not a live CLI
411
+ // coordinator exists — this is what lets an MCP/LLM coordinator ever see a
412
+ // remote worker's completion.
413
+ if (dispatchMeshCommand) {
414
+ for (const mesh of listMeshes()) {
415
+ // Expand to every id-form this daemon answers to for this mesh (runtime
416
+ // drain ids ∪ config-form node/host ids) and use it for BOTH the host gate
417
+ // and the remote pull filter, so a worker stamp in any form is recovered.
418
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
419
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
420
+ try {
421
+ await pullRemoteNodeQueues(components, mesh, localDaemonId, selfIds);
422
+ } catch (e: any) {
423
+ LOG.warn('MeshReconcile', `Remote node pull failed for mesh ${mesh.id}: ${e?.message || e}`);
424
+ }
425
+ }
426
+ }
427
+
428
+ // ── PHASE 2.5: assigned-stranded dispatch watchdog (Bug B) ─────────────────
429
+ // Runs before PHASE 3 so any row it returns to 'pending' is re-dispatched by the
430
+ // PHASE 3 trigger in this same tick. See recoverStrandedAssignedDispatches.
431
+ if (store) {
432
+ for (const mesh of listMeshes()) {
433
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
434
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
435
+ try {
436
+ recoverStrandedAssignedDispatches(mesh.id, store);
437
+ } catch (e: any) {
438
+ LOG.warn('MeshReconcile', `Assigned-stranded watchdog failed for mesh ${mesh.id}: ${e?.message || e}`);
439
+ }
440
+ }
441
+ }
442
+
443
+ // ── PHASE 3: recover pending queue claims for newly-idle sessions ──────────
444
+ // The event-driven claim paths (agent:ready / agent:generating_completed in
445
+ // mesh-events-coordinator) re-claim the queue the moment a session goes idle,
446
+ // but that depends on a single event being emitted AND (for a remote node)
447
+ // successfully forwarded to this coordinator. If that event is missed/dropped,
448
+ // a pending task targeting a now-idle session would sit unclaimed forever —
449
+ // there was no periodic safety net. This phase is that net: for every mesh this
450
+ // daemon hosts that has at least one pending task, run one triggerMeshQueue so a
451
+ // session that became idle without a delivered ready-event still gets its work.
452
+ //
453
+ // O(1) guard: skip the (relatively expensive) full idle-session + remote-idle
454
+ // scan entirely when the queue has no pending tasks — a COUNT(*) over the
455
+ // indexed status column, so an idle mesh costs one cheap query per tick.
456
+ // claimNextQueueTask is atomic, so racing the event-driven path can only have
457
+ // one winner; double-claiming is impossible.
458
+ for (const mesh of listMeshes()) {
459
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
460
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
461
+ if (store) {
462
+ try {
463
+ if (store.pendingQueueTaskCount(mesh.id) === 0) continue;
464
+ } catch { /* fall through and let triggerMeshQueue decide */ }
465
+ }
466
+ try {
467
+ await triggerMeshQueue(components, mesh.id);
468
+ } catch (e: any) {
469
+ LOG.warn('MeshReconcile', `Pending-claim recovery trigger failed for mesh ${mesh.id}: ${e?.message || e}`);
470
+ }
471
+ }
472
+
473
+ // ── PHASE 4: synthesize lost completions for unterminated direct dispatches ─
474
+ // Symmetric to PHASE 3 (which recovers a *lost claim* for a newly-idle session)
475
+ // but for the opposite gap: a worker that ALREADY completed, went idle, and
476
+ // whose terminal completion event was never persisted (dropped before reaching
477
+ // the queue/outbox, or its forward was lost). PHASE 1/2/3 can only deliver an
478
+ // event that exists in a queue — they cannot recover a completion that was
479
+ // never recorded, so the coordinator keeps believing the worker is generating.
480
+ //
481
+ // reconcileDirectDispatchCompletionFromTranscript already synthesizes the
482
+ // missing terminal event from the worker's transcript, but until now it ran
483
+ // ONLY when an LLM coordinator polled mesh_status (mcp_mesh_status_transcript_
484
+ // reconciliation). This phase pulls that same correction onto the daemon timer
485
+ // so it no longer depends on the LLM polling. The reconcile is idempotent
486
+ // (hasTerminalLedgerAfterDispatch guards against re-synthesis), so attempting it
487
+ // every tick for the same dispatch is safe — once a terminal exists it no-ops.
488
+ for (const mesh of listMeshes()) {
489
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
490
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
491
+ try {
492
+ await reconcileUnterminatedDirectDispatches(components, mesh, selfIds, localDaemonId);
493
+ } catch (e: any) {
494
+ LOG.warn('MeshReconcile', `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
495
+ }
496
+ }
497
+
498
+ // ── PHASE 5: auto-prune orphaned direct dispatch records ───────────────────
499
+ // staleDirectWork (orphaned direct-dispatch rows whose node/session is no longer in the
500
+ // live mesh) otherwise accumulates indefinitely: a removed worktree node or a cleanly
501
+ // terminated session leaves its direct-dispatch row behind, stuck in a non-terminal status
502
+ // (e.g. generating) for days. This is NOT a false-idle bug — it is the separate problem of
503
+ // orphaned records that the only existing cleanup path (manual MCP mesh_prune_stale_direct)
504
+ // never reaches unless an operator runs it by hand.
505
+ //
506
+ // This phase runs the SAME prune core the manual tool calls (pruneStaleDirectDispatches),
507
+ // in execute mode, on the daemon timer. The only difference from the manual path is a
508
+ // conservative age gate (DEFAULT_AUTO_PRUNE_MIN_AGE_MS): a freshly-orphaned record is held
509
+ // back until it is provably stale, so a transient probe miss never auto-prunes live work.
510
+ // Every other safety rule is inherited unchanged from the core — active/pending/generating
511
+ // work and fresh unacknowledged dispatch failures are never pruned, ledger-only audit entries
512
+ // are preserved, and the prune itself is recorded with a direct_dispatch_pruned ledger entry.
513
+ // Idempotent: a pruned row is gone from getActiveDirectDispatches, so the next tick finds
514
+ // nothing to re-prune. Isolated in its own try/catch per mesh so it can never kill the tick.
515
+ {
516
+ const minAgeMs = resolveAutoPruneMinAgeMs();
517
+ for (const mesh of listMeshes()) {
518
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
519
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
520
+ try {
521
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
522
+ } catch (e: any) {
523
+ LOG.warn('MeshReconcile', `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
524
+ }
525
+ }
526
+ }
527
+
528
+ // ── PHASE 2: inject into live CLI coordinators on this daemon ──────────────
529
+ const coordinators = findLiveCoordinators(components);
530
+ if (coordinators.length === 0) {
531
+ // No live CLI coordinator on this daemon — nothing to inject into.
532
+ // (MCP-only LLM coordinators drain the local queue via their own tool
533
+ // calls; PHASE 1 above has already populated it from remote nodes.)
534
+ return;
535
+ }
536
+
537
+ // Group coordinators by mesh; multiple coordinator instances for one mesh is
538
+ // unusual but supported (each gets the same drained events).
539
+ const byMesh = new Map<string, LiveCoordinator[]>();
540
+ for (const c of coordinators) {
541
+ const list = byMesh.get(c.meshId);
542
+ if (list) list.push(c);
543
+ else byMesh.set(c.meshId, [c]);
544
+ }
545
+
546
+ for (const [meshId, meshCoordinators] of byMesh) {
547
+ // Drain the local queue scoped to this coordinator daemon and inject.
548
+ // - If an idle coordinator exists, FULL-drain and deliver every event to it
549
+ // (it can receive non-force progress events without deadlocking).
550
+ // - If only GENERATING coordinators exist, force-drain ONLY the force-inject
551
+ // events (completion/approval/stop/refine·bootstrap terminal) and force-inject
552
+ // them so a coordinator parked in `generating` while awaiting that very event
553
+ // is not deadlocked. Non-force progress events stay queued for the next idle
554
+ // tick — injecting them would be noise mid-generation. Both drains mark the
555
+ // consumed rows drained=1 atomically, so the pull path can't re-deliver.
556
+ const idleCoordinators = meshCoordinators.filter(c => c.idle);
557
+ // A coordinator parked on a harness modal (waiting_choice / waiting_approval)
558
+ // is non-idle, so it would otherwise be treated as a force-inject target. It
559
+ // must NOT be: a force-inject writes raw keystrokes into the PTY, which the
560
+ // modal's key handler consumes and silently resolves to a choice the user
561
+ // never made. Force-inject is only safe into a coordinator parked in plain
562
+ // `generating` (the deadlock the force path exists to break). So generating
563
+ // targets are the non-idle, non-modal-parked coordinators.
564
+ const generatingCoordinators = meshCoordinators.filter(c => !c.idle && !c.modalParked);
565
+ const modalParkedCoordinators = meshCoordinators.filter(c => !c.idle && c.modalParked);
566
+ const targetCoordinators = idleCoordinators.length > 0 ? idleCoordinators : generatingCoordinators;
567
+ const forceOnly = idleCoordinators.length === 0;
568
+
569
+ // ── modal-blocked short-circuit (MUST precede the drain) ──────────────────
570
+ // When the ONLY coordinators for this mesh are modal-parked (no idle, no plain
571
+ // generating target), there is nowhere safe to deliver. We skip-and-requeue:
572
+ // by NOT draining we leave the events at drained=0 in the queue, so a later tick
573
+ // (once the modal is resolved and the coordinator returns to idle/generating)
574
+ // delivers them. This short-circuit MUST run BEFORE drainPendingMeshCoordinatorEvents
575
+ // — the drain marks rows drained=1 atomically, which would lose the events for a
576
+ // coordinator that is only transiently blocked. (Note: generating is still
577
+ // force-injected via generatingCoordinators — we never block the deadlock-break.)
578
+ if (targetCoordinators.length === 0) {
579
+ if (modalParkedCoordinators.length > 0) {
580
+ 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)`);
581
+ // C1: mirror held terminal events into the ledger so a held completion's
582
+ // worker summary is auditable/recoverable even if the modal is never
583
+ // resolved, the coordinator restarts, or the pending file is later trimmed.
584
+ // The events stay queued (drained=0) for re-drain on a later tick; this only
585
+ // adds the durable audit copy. Idempotent per process — only newly-held
586
+ // events are logged. O(1)-gated: skip the peek when the queue is empty.
587
+ let hasPending = true;
588
+ if (store) {
589
+ try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
590
+ }
591
+ if (hasPending) {
592
+ recordHeldTerminalEventsToLedger(
593
+ meshId,
594
+ drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
595
+ 'modal_parked',
596
+ modalParkedCoordinators.length,
597
+ );
598
+ }
599
+ }
600
+ continue;
601
+ }
602
+
603
+ // O(1) guard: skip the drain entirely when the queue is empty.
604
+ if (store) {
605
+ try {
606
+ if (store.pendingEventCount(meshId) === 0) continue;
607
+ } catch { /* fall through to drain */ }
608
+ }
609
+
610
+ let pendingEvents: PendingMeshCoordinatorEvent[] = [];
611
+ try {
612
+ pendingEvents = drainPendingMeshCoordinatorEvents(
613
+ meshId,
614
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
615
+ forceOnly ? { onlyEvents: MESH_FORCE_INJECT_EVENTS } : undefined,
616
+ );
617
+ } catch (e: any) {
618
+ LOG.warn('MeshReconcile', `Drain failed for mesh ${meshId}: ${e?.message || e}`);
619
+ continue;
620
+ }
621
+ if (pendingEvents.length === 0) continue;
622
+
623
+ const mode = forceOnly ? 'force-drain → generating' : 'inject → idle';
624
+ LOG.info('MeshReconcile', `Reconcile ${mode}: ${pendingEvents.length} pending event(s) → ${targetCoordinators.length} coordinator(s) for mesh ${meshId}`);
625
+ for (const pending of pendingEvents) {
626
+ // Strict session routing (multi-coordinator): when the event names an
627
+ // originating coordinator session, deliver ONLY to the live coordinator whose
628
+ // session id matches — a sibling coordinator on the same daemon must NOT receive
629
+ // another coordinator's completion. When the event carries no session id (legacy /
630
+ // version-skewed / single-coordinator), fall back to the daemon-level set
631
+ // (unchanged behaviour — regression-0 for the common case).
632
+ const wantSession = readNonEmptyString(pending.targetCoordinatorSessionId);
633
+ if (wantSession) {
634
+ const matched = targetCoordinators.filter(c => c.sessionId === wantSession);
635
+ if (matched.length === 0) {
636
+ // The originating coordinator session is not deliverable on this daemon
637
+ // right now (gone, or modal-parked and excluded from targets). Strict mode
638
+ // does NOT broadcast to siblings — hold the event for a later tick, and
639
+ // ledger-expire it past a TTL so it can never wedge forever.
640
+ holdOrExpireStrictUnmatchedEvent(pending, wantSession, meshId);
641
+ continue;
642
+ }
643
+ for (const c of matched) injectPendingIntoCoordinator(c.instance, pending);
644
+ continue;
645
+ }
646
+ for (const c of targetCoordinators) {
647
+ injectPendingIntoCoordinator(c.instance, pending);
648
+ }
649
+ }
650
+ }
651
+ }
652
+
653
+ // Strict-routing TTL: how long a drained completion whose originating coordinator session
654
+ // is not currently deliverable is held (re-queued for re-drain) before it is ledger-
655
+ // expired. Bounded so a coordinator session that never returns cannot wedge the event
656
+ // forever; broad enough to ride out a transient modal-park / brief restart.
657
+ const STRICT_SESSION_MATCH_TTL_MS = 60_000;
658
+
659
+ // Re-queue (hold) a strict-routed event whose coordinator session is not live, or — once it
660
+ // has aged past STRICT_SESSION_MATCH_TTL_MS — ledger-expire it (recoverable) and drop it.
661
+ // We deliberately do NOT broadcast an aged-out event to sibling coordinators: that is the
662
+ // very misroute strict routing exists to prevent. The drain already marked the row drained=1,
663
+ // so re-queuing re-persists a fresh undrained copy (dedup keys on drained=0 only); queuedAt is
664
+ // preserved so the TTL measures the event's true age across re-queues.
665
+ function holdOrExpireStrictUnmatchedEvent(
666
+ pending: PendingMeshCoordinatorEvent,
667
+ wantSession: string,
668
+ meshId: string,
669
+ ): void {
670
+ const queuedAt = typeof pending.queuedAt === 'number' ? pending.queuedAt : Date.now();
671
+ if (Date.now() - queuedAt <= STRICT_SESSION_MATCH_TTL_MS) {
672
+ try {
673
+ queuePendingMeshCoordinatorEvent(pending); // preserves queuedAt → true age retained
674
+ LOG.info('MeshReconcile', `Strict route hold: coordinator session ${wantSession} not live on mesh ${meshId} — re-queued (${pending.event})`);
675
+ // EVTTRACE: event held (re-queued) — its originating coordinator session is not
676
+ // currently deliverable. Held, not dropped; surfaces later or expires past TTL.
677
+ traceMeshEventDrop('strict_route_hold', {
678
+ taskId: pending.metadataEvent?.taskId,
679
+ sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
680
+ nodeId: pending.nodeId,
681
+ meshId,
682
+ event: pending.event,
683
+ }, `coordinatorSession=${wantSession} not live`);
684
+ } catch (e: any) {
685
+ LOG.warn('MeshReconcile', `Strict route re-queue failed for ${pending.event} on mesh ${meshId}: ${e?.message || e}`);
686
+ }
687
+ return;
688
+ }
689
+ const finalSummary = readMeshCompletionSummary(pending.metadataEvent || {});
690
+ try {
691
+ appendLedgerEntry(meshId, {
692
+ kind: 'event_held',
693
+ ...(pending.nodeId ? { nodeId: pending.nodeId } : {}),
694
+ payload: {
695
+ event: pending.event,
696
+ reason: 'strict_route_expired',
697
+ recoverable: true,
698
+ targetCoordinatorSessionId: wantSession,
699
+ targetCoordinatorDaemonId: pending.targetCoordinatorDaemonId ?? null,
700
+ nodeLabel: pending.nodeLabel,
701
+ ...(pending.workspace ? { workspace: pending.workspace } : {}),
702
+ queuedAt,
703
+ ...(finalSummary ? { finalSummary } : {}),
704
+ },
705
+ });
706
+ LOG.warn('MeshReconcile', `Strict route expire: coordinator session ${wantSession} never returned for mesh ${meshId} — recorded to ledger (recoverable), dropped (${pending.event})`);
707
+ // EVTTRACE: event expired past the strict-route TTL — dropped (recoverable, ledgered).
708
+ traceMeshEventDrop('strict_route_expired', {
709
+ taskId: pending.metadataEvent?.taskId,
710
+ sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
711
+ nodeId: pending.nodeId,
712
+ meshId,
713
+ event: pending.event,
714
+ }, `coordinatorSession=${wantSession} never returned`);
715
+ } catch (e: any) {
716
+ LOG.warn('MeshReconcile', `Failed to ledger-expire strict-unmatched ${pending.event} for mesh ${meshId}: ${e?.message || e}`);
717
+ }
718
+ }
719
+
720
+ // Cloud-only: retry the worker-side unresolved-delegate forward outbox. For each
721
+ // durably-queued entry, push it to its coordinator daemon over P2P (mesh_forward_event)
722
+ // and ack (mark drained) ONLY on a successful, non-rejected response. A failed or
723
+ // rejected push leaves the entry queued for the next tick — at-least-once delivery.
724
+ // Stale entries (coordinator unreachable past the max age) are expired first so the
725
+ // outbox can't grow without bound. The coordinator dedups duplicate deliveries on its
726
+ // own fingerprint, so a retry that races the original immediate push is harmless.
727
+ async function retryUnresolvedDelegateForwards(components: DaemonComponents): Promise<void> {
728
+ const dispatchMeshCommand = components.dispatchMeshCommand;
729
+ if (!dispatchMeshCommand) return;
730
+
731
+ // Drop entries that have exhausted their retry budget (fail-loud inside).
732
+ expireStaleUnresolvedDelegateForwards();
733
+
734
+ const entries = peekUnresolvedDelegateForwards();
735
+ if (entries.length === 0) return;
736
+
737
+ for (const entry of entries) {
738
+ // EVTTRACE correlation context for this outbox entry's retry.
739
+ const entryTraceCtx = {
740
+ taskId: (entry.payload as Record<string, unknown>).taskId,
741
+ sessionId: readNonEmptyString(entry.payload.targetSessionId) || readNonEmptyString(entry.payload.sessionId),
742
+ nodeId: readNonEmptyString(entry.payload.nodeId),
743
+ event: readNonEmptyString(entry.payload.event),
744
+ };
745
+ let result: any;
746
+ try {
747
+ traceMeshEventStage('forward_send', entryTraceCtx, `retry → ${entry.coordinatorDaemonId}`);
748
+ result = await dispatchMeshCommand(entry.coordinatorDaemonId, 'mesh_forward_event', entry.payload);
749
+ } catch (e: any) {
750
+ // Coordinator unreachable — keep the entry queued and try again next tick.
751
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} failed: ${e?.message || e} — left queued`);
752
+ traceMeshEventDrop('retry_forward_failed', entryTraceCtx, e?.message || String(e));
753
+ continue;
754
+ }
755
+ if (result && result.success === false) {
756
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected (${readNonEmptyString(result.error) || 'no reason'}) — left queued`);
757
+ traceMeshEventDrop('retry_forward_rejected', entryTraceCtx, readNonEmptyString(result.error) || 'no reason');
758
+ continue;
759
+ }
760
+ // Acked — mark the durable copy delivered.
761
+ ackUnresolvedDelegateForward(entry.id);
762
+ LOG.info('MeshReconcile', `Retried+delivered unresolved-delegate ${readNonEmptyString(entry.payload.event)} to coordinator ${entry.coordinatorDaemonId}`);
763
+ }
764
+ }
765
+
766
+ // Cloud-only: poll each remote worker node daemon for pending coordinator events
767
+ // and re-inject them locally via handleMeshForwardEvent (which re-queues +
768
+ // surfaces to the live coordinator on the next tick / immediately if idle).
769
+ //
770
+ // Scoping: the remote handler (get_pending_mesh_events) drains its queue filtered
771
+ // by coordinatorDaemonId — returning events targeted at that id OR unscoped, and
772
+ // leaving events targeted at a *different* coordinator. A remote worker stamps the
773
+ // coordinator id in one of SEVERAL forms (the canonical status id `standalone_`/
774
+ // `daemon_<machineId>` stamped by the MCP layer, the bare machineId stamped by the
775
+ // local queue path, OR — most commonly for remote launches — the coordinator mesh
776
+ // node's config-form `daemonId`, which resolveCoordinatorDaemonId prefers and which
777
+ // is NOT canonicalised). `candidateDaemonIds` is the already-expanded self-identity
778
+ // set (resolveCoordinatorSelfIds: runtime drain ids ∪ this daemon's mesh-config node/
779
+ // host id forms), so we pull ONCE PER candidate id and a completion stamped with any
780
+ // of them is recovered. The remote drain is atomic (drained=1), so issuing multiple
781
+ // pulls cannot double-deliver — the first pull that matches consumes the event; the
782
+ // rest see nothing. When no ids resolve we fall back to a single unscoped pull.
783
+ async function pullRemoteNodeQueues(
784
+ components: DaemonComponents,
785
+ mesh: LocalMeshEntry,
786
+ localDaemonId: string | undefined,
787
+ candidateDaemonIds: string[],
788
+ ): Promise<void> {
789
+ const dispatchMeshCommand = components.dispatchMeshCommand;
790
+ if (!dispatchMeshCommand) return;
791
+ const meshId = mesh.id;
792
+
793
+ // One args object per candidate coordinator-id form, or a single unscoped pull
794
+ // when none resolve.
795
+ const pulls: Array<Record<string, unknown>> = candidateDaemonIds.length > 0
796
+ ? candidateDaemonIds.map(id => ({ meshId, coordinatorDaemonId: id }))
797
+ : [{ meshId }];
798
+
799
+ for (const node of mesh.nodes) {
800
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
801
+ // Skip nodes without a daemon, and nodes on THIS daemon (their events are
802
+ // already in the local queue drained in PHASE 2). "This daemon" is matched
803
+ // against the full self-identity set (candidateDaemonIds), not just the bare
804
+ // localDaemonId — a self node can be registered under the config-form daemonId
805
+ // (`daemon_<machineId>`) which would NOT equal bare localDaemonId, and pulling
806
+ // from ourselves over P2P is both wasteful and a self-dispatch hazard.
807
+ if (!nodeDaemonId) continue;
808
+ if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) continue;
809
+ if (candidateDaemonIds.includes(nodeDaemonId)) continue;
810
+
811
+ for (const pendingEventArgs of pulls) {
812
+ let events: unknown;
813
+ try {
814
+ events = await dispatchMeshCommand(nodeDaemonId, 'get_pending_mesh_events', pendingEventArgs);
815
+ } catch {
816
+ // Remote pull is best-effort; the node may be offline. Retry next tick.
817
+ break; // node unreachable — don't bother with the other id form this tick.
818
+ }
819
+ const list = extractPendingEvents(events).filter(e => readNonEmptyString(e?.meshId) === meshId);
820
+ for (const event of list) {
821
+ const payload = buildForwardPayloadFromPending(event);
822
+ if (!payload.event || !payload.meshId) continue;
823
+ try {
824
+ handleMeshForwardEvent(components, payload);
825
+ } catch { /* best-effort re-inject */ }
826
+ }
827
+ }
828
+ }
829
+ }
830
+
831
+ // Pull the read_chat payload out of whatever envelope the transport returned.
832
+ // A local commandHandler.handle() returns the CommandResult directly; a remote
833
+ // dispatchMeshCommand returns it possibly wrapped in { payload } / { result }.
834
+ function unwrapReadChatPayload(raw: unknown): Record<string, unknown> | null {
835
+ let cursor: unknown = raw;
836
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === 'object'; depth++) {
837
+ const record = cursor as Record<string, unknown>;
838
+ if (Array.isArray(record.messages)) return record;
839
+ if (record.payload && typeof record.payload === 'object') { cursor = record.payload; continue; }
840
+ if (record.result && typeof record.result === 'object') { cursor = record.result; continue; }
841
+ if (record.data && typeof record.data === 'object') { cursor = record.data; continue; }
842
+ break;
843
+ }
844
+ return cursor && typeof cursor === 'object' ? cursor as Record<string, unknown> : null;
845
+ }
846
+
847
+ function readChatPayloadStatus(payload: Record<string, unknown> | null): string {
848
+ return readNonEmptyString(payload?.status).toLowerCase();
849
+ }
850
+
851
+ // PHASE 4 helper. For every active (non-terminal) direct dispatch this daemon
852
+ // hosts, confirm the worker session is idle via a read_chat and — if a final
853
+ // assistant summary is present but no terminal ledger exists for that dispatch —
854
+ // synthesize the missing completion through reconcileDirectDispatchCompletionFromTranscript.
855
+ //
856
+ // read_chat is resolved against the target node: a node on THIS daemon is read
857
+ // through the local commandHandler; a remote node is read over P2P via
858
+ // dispatchMeshCommand. Both yield the same { messages, status, providerSessionId }
859
+ // shape. We only synthesize when the session reports idle AND a final assistant
860
+ // message exists — the same evidence bar the MCP poll path uses — so an actively
861
+ // generating worker is never falsely completed. The reconcile itself is idempotent.
862
+ async function reconcileUnterminatedDirectDispatches(
863
+ components: DaemonComponents,
864
+ mesh: LocalMeshEntry,
865
+ selfIds: string[],
866
+ localDaemonId: string | undefined,
867
+ ): Promise<void> {
868
+ const dispatches = getActiveDirectDispatches(mesh.id);
869
+ if (dispatches.length === 0) return; // cheap exit — nothing dispatched, nothing to reconcile
870
+
871
+ const dispatchMeshCommand = components.dispatchMeshCommand;
872
+ const nodeById = new Map(mesh.nodes.map(n => [n.id, n] as const));
873
+
874
+ for (const dispatch of dispatches) {
875
+ const sessionId = readNonEmptyString(dispatch.sessionId);
876
+ const nodeId = readNonEmptyString(dispatch.nodeId);
877
+ const taskId = readNonEmptyString(dispatch.taskId);
878
+ if (!sessionId || !nodeId || !taskId) continue;
879
+
880
+ const node = nodeById.get(nodeId);
881
+ const nodeDaemonId = readNonEmptyString(node?.daemonId);
882
+ // A node is local when it has no daemonId, names this daemon, or actually
883
+ // has a live instance here. Anything else is reached over P2P.
884
+ const isLocalNode = !nodeDaemonId
885
+ || selfIds.includes(nodeDaemonId)
886
+ || daemonIdsEquivalent(nodeDaemonId, localDaemonId)
887
+ || !!components.instanceManager.getInstance(sessionId);
888
+
889
+ const providerType = readNonEmptyString(dispatch.providerType);
890
+ const readArgs: Record<string, unknown> = {
891
+ sessionId,
892
+ targetSessionId: sessionId,
893
+ tailLimit: 10,
894
+ ...(node?.workspace ? { workspace: node.workspace } : {}),
895
+ ...(providerType ? { agentType: providerType, providerType } : {}),
896
+ };
897
+
898
+ let payload: Record<string, unknown> | null = null;
899
+ try {
900
+ if (isLocalNode) {
901
+ const result = await components.commandHandler.handle('read_chat', readArgs);
902
+ if (result && (result as { success?: boolean }).success === false) continue;
903
+ payload = unwrapReadChatPayload(result);
904
+ } else if (dispatchMeshCommand) {
905
+ const result = await dispatchMeshCommand(nodeDaemonId, 'read_chat', readArgs);
906
+ payload = unwrapReadChatPayload(result);
907
+ if (payload && (payload as { success?: boolean }).success === false) continue;
908
+ } else {
909
+ continue; // remote node but no P2P transport — can't read; retry next tick
910
+ }
911
+ } catch {
912
+ continue; // best-effort; session may be gone or node offline — retry next tick
913
+ }
914
+ if (!payload) continue;
915
+
916
+ // Only act on a session that has actually settled to idle. A generating /
917
+ // waiting_approval session is mid-turn — synthesizing a completion now would
918
+ // be wrong. (idle is the only status the MCP poll path reconciles too.)
919
+ if (readChatPayloadStatus(payload) !== 'idle') continue;
920
+
921
+ const messages = Array.isArray(payload.messages) ? payload.messages as ChatMessage[] : [];
922
+ const evidence = extractFinalAssistantSummaryEvidence(messages);
923
+ if (!evidence.finalSummary) continue; // no assistant result yet — nothing to attribute
924
+
925
+ const providerSessionId = readNonEmptyString(payload.providerSessionId);
926
+ const coordinatorDaemonId = selfIds.find(id => !!id);
927
+ try {
928
+ const result = reconcileDirectDispatchCompletionFromTranscript({
929
+ meshId: mesh.id,
930
+ nodeId,
931
+ sessionId,
932
+ providerType: providerType || undefined,
933
+ providerSessionId: providerSessionId || undefined,
934
+ taskId,
935
+ finalSummary: evidence.finalSummary,
936
+ ...(evidence.transcriptMessageAt ? { transcriptMessageAt: evidence.transcriptMessageAt } : {}),
937
+ ...(coordinatorDaemonId ? { targetCoordinatorDaemonId: coordinatorDaemonId } : {}),
938
+ source: 'daemon_reconcile_transcript_completion',
939
+ });
940
+ if (result.reconciled) {
941
+ LOG.info('MeshReconcile', `Synthesized missing completion (${result.kind}) for task ${taskId} on node ${nodeId} (mesh ${mesh.id})`);
942
+ }
943
+ } catch (e: any) {
944
+ LOG.warn('MeshReconcile', `Transcript completion reconcile threw for task ${taskId}: ${e?.message || e}`);
945
+ }
946
+ }
947
+ }
948
+
949
+ // PHASE 5 helper. Build the live-node view (mesh.nodes decorated with each node's live
950
+ // session list) and run the shared prune core in execute mode with the conservative age gate.
951
+ //
952
+ // Orphan detection needs the SAME live-session evidence the manual MCP prune uses: a node still
953
+ // in mesh.nodes whose session list no longer contains the dispatched sessionId is "session not
954
+ // present" (prunable); a node missing from mesh.nodes entirely is "node no longer in live mesh"
955
+ // (prunable). We obtain live sessions per node via get_status_metadata — local nodes through the
956
+ // local commandHandler, remote nodes over P2P (dispatchMeshCommand) — exactly the transports
957
+ // PHASE 4 already uses. A node we cannot probe (offline) keeps an empty session list; combined
958
+ // with the age gate that only matters once the orphan is genuinely old.
959
+ //
960
+ // O(1) fast exit: when there are no active direct dispatches at all there is nothing to prune,
961
+ // so we skip the (per-node) status probes entirely — an idle mesh costs one indexed query.
962
+ async function autoPruneStaleDirectDispatches(
963
+ components: DaemonComponents,
964
+ mesh: LocalMeshEntry,
965
+ selfIds: string[],
966
+ localDaemonId: string | undefined,
967
+ minAgeMs: number,
968
+ ): Promise<void> {
969
+ const directDispatches = getActiveDirectDispatches(mesh.id);
970
+ if (directDispatches.length === 0) return; // nothing dispatched → nothing to prune
971
+
972
+ const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
973
+
974
+ const result = pruneStaleDirectDispatches({
975
+ meshId: mesh.id,
976
+ queue: getQueue(mesh.id),
977
+ ledgerEntries: readLedgerEntries(mesh.id, { tail: 500 }),
978
+ directDispatches,
979
+ nodes: liveNodes,
980
+ execute: true,
981
+ minAgeMs,
982
+ source: 'daemon_reconcile_auto_prune',
983
+ });
984
+
985
+ // Log only when something was actually pruned — silence on the common no-op tick.
986
+ if (result.prunedCount > 0) {
987
+ LOG.info('MeshReconcile', `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
988
+ }
989
+ }
990
+
991
+ // Probe each node for its live session list (get_status_metadata) and return mesh.nodes
992
+ // decorated with a `sessions` array — the shape buildMeshActiveWork / sessionStatusFromNodes
993
+ // consume to decide whether a dispatched session is still present. Best-effort: an unreachable
994
+ // node yields an empty session list rather than throwing.
995
+ async function collectLiveNodesWithSessions(
996
+ components: DaemonComponents,
997
+ mesh: LocalMeshEntry,
998
+ selfIds: string[],
999
+ localDaemonId: string | undefined,
1000
+ ): Promise<any[]> {
1001
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1002
+ return Promise.all(mesh.nodes.map(async (node) => {
1003
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
1004
+ const isLocalNode = !nodeDaemonId
1005
+ || selfIds.includes(nodeDaemonId)
1006
+ || daemonIdsEquivalent(nodeDaemonId, localDaemonId);
1007
+ let statusResult: unknown;
1008
+ try {
1009
+ if (isLocalNode) {
1010
+ statusResult = await components.commandHandler.handle('get_status_metadata', {});
1011
+ } else if (dispatchMeshCommand) {
1012
+ statusResult = await dispatchMeshCommand(nodeDaemonId, 'get_status_metadata', {});
1013
+ } else {
1014
+ return node; // remote node, no P2P transport — leave undecorated
1015
+ }
1016
+ } catch {
1017
+ return node; // unreachable — leave undecorated (empty session list)
1018
+ }
1019
+ const sessions = extractStatusMetadataSessions(statusResult);
1020
+ return sessions.length > 0 ? { ...node, sessions } : node;
1021
+ }));
1022
+ }
1023
+
1024
+ // Pull the live session list out of a get_status_metadata result, tolerating the same
1025
+ // envelope shapes unwrapReadChatPayload handles (direct CommandResult or { payload }/{ result }).
1026
+ function extractStatusMetadataSessions(raw: unknown): any[] {
1027
+ let cursor: unknown = raw;
1028
+ for (let depth = 0; depth < 4 && cursor && typeof cursor === 'object'; depth++) {
1029
+ const record = cursor as Record<string, unknown>;
1030
+ const status = record.status && typeof record.status === 'object' ? record.status as Record<string, unknown> : undefined;
1031
+ if (status && Array.isArray(status.sessions)) return status.sessions;
1032
+ if (Array.isArray(record.sessions)) return record.sessions;
1033
+ if (record.payload && typeof record.payload === 'object') { cursor = record.payload; continue; }
1034
+ if (record.result && typeof record.result === 'object') { cursor = record.result; continue; }
1035
+ if (record.data && typeof record.data === 'object') { cursor = record.data; continue; }
1036
+ break;
1037
+ }
1038
+ return [];
1039
+ }
1040
+
1041
+ function extractPendingEvents(raw: unknown): any[] {
1042
+ if (Array.isArray(raw)) return raw;
1043
+ if (raw && typeof raw === 'object') {
1044
+ const events = (raw as Record<string, unknown>).events;
1045
+ if (Array.isArray(events)) return events;
1046
+ }
1047
+ return [];
1048
+ }
1049
+
1050
+ // Flatten a queued PendingMeshCoordinatorEvent into the flat payload shape
1051
+ // handleMeshForwardEvent expects (mirrors the MCP buildMeshForwardPayloadFromPendingEvent).
1052
+ function buildForwardPayloadFromPending(event: any): Record<string, unknown> {
1053
+ const metadata = event?.metadataEvent && typeof event.metadataEvent === 'object'
1054
+ ? event.metadataEvent as Record<string, unknown>
1055
+ : {};
1056
+ return {
1057
+ event: readNonEmptyString(event?.event),
1058
+ meshId: readNonEmptyString(event?.meshId),
1059
+ nodeId: readNonEmptyString(event?.nodeId) || readNonEmptyString(metadata.meshNodeId),
1060
+ workspace: readNonEmptyString(event?.workspace) || readNonEmptyString(metadata.workspace),
1061
+ // Preserve the originating coordinator session id across the relay. It is normally
1062
+ // carried inside metadataEvent.meshCoordinatorSessionId (spread below), but pass the
1063
+ // top-level field through explicitly too so the handleMeshForwardEvent whitelist
1064
+ // recovers it regardless of which carrier the producing daemon used.
1065
+ ...(readNonEmptyString(event?.targetCoordinatorSessionId)
1066
+ ? { targetCoordinatorSessionId: readNonEmptyString(event.targetCoordinatorSessionId) }
1067
+ : {}),
1068
+ ...metadata,
1069
+ };
1070
+ }
1071
+
1072
+ interface ReconcileLoopHandle {
1073
+ stop(): void;
1074
+ }
1075
+
1076
+ // Start the periodic reconcile loop. Returns a handle with stop() for shutdown.
1077
+ export function setupMeshReconcileLoop(components: DaemonComponents): ReconcileLoopHandle {
1078
+ const intervalMs = resolveReconcileIntervalMs();
1079
+ let running = false;
1080
+ const timer = setInterval(() => {
1081
+ if (running) return; // never overlap ticks
1082
+ running = true;
1083
+ void runMeshReconcileTick(components)
1084
+ .catch((e: any) => LOG.warn('MeshReconcile', `Reconcile tick error: ${e?.message || e}`))
1085
+ .finally(() => { running = false; });
1086
+ }, intervalMs);
1087
+ // Don't keep the process alive solely for this timer.
1088
+ if (typeof timer.unref === 'function') timer.unref();
1089
+ LOG.info('MeshReconcile', `Mesh reconcile loop started (interval ${intervalMs}ms)`);
1090
+ return {
1091
+ stop() {
1092
+ clearInterval(timer);
1093
+ LOG.info('MeshReconcile', 'Mesh reconcile loop stopped');
1094
+ },
1095
+ };
1096
+ }