@adhdev/daemon-core 0.9.82-rc.40 → 0.9.82-rc.400

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