@adhdev/daemon-core 0.9.82-rc.43 → 0.9.82-rc.431

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