@adhdev/daemon-core 0.9.82-rc.48 → 0.9.82-rc.481

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 (473) 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 +220 -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 +23 -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 +51 -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 +64 -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 +48 -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 +152 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router-aggregate-status.d.ts +24 -0
  56. package/dist/commands/router-mesh-session-owner.d.ts +59 -0
  57. package/dist/commands/router-refine.d.ts +137 -0
  58. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  59. package/dist/commands/router.d.ts +204 -15
  60. package/dist/commands/upgrade-helper.d.ts +41 -1
  61. package/dist/config/chat-history.d.ts +11 -0
  62. package/dist/config/config.d.ts +19 -0
  63. package/dist/config/mesh-config.d.ts +136 -1
  64. package/dist/config/mesh-json-config.d.ts +199 -0
  65. package/dist/config/registry-resolver.d.ts +54 -0
  66. package/dist/config/repo-settings.d.ts +77 -0
  67. package/dist/config/state-store.d.ts +30 -0
  68. package/dist/daemon/dev-server.d.ts +0 -2
  69. package/dist/detection/cli-detector.d.ts +17 -0
  70. package/dist/detection/ide-detector.d.ts +13 -0
  71. package/dist/detection/win32-ide-version.d.ts +37 -0
  72. package/dist/git/change-impact-config.d.ts +159 -0
  73. package/dist/git/git-commands.d.ts +26 -2
  74. package/dist/git/git-diff.d.ts +6 -0
  75. package/dist/git/git-executor.d.ts +11 -0
  76. package/dist/git/git-status.d.ts +57 -0
  77. package/dist/git/git-types.d.ts +2 -50
  78. package/dist/git/git-worktree.d.ts +71 -1
  79. package/dist/git/index.d.ts +3 -1
  80. package/dist/index.d.ts +73 -17
  81. package/dist/index.js +52979 -18657
  82. package/dist/index.js.map +1 -1
  83. package/dist/index.mjs +59496 -25355
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/installer.d.ts +1 -4
  86. package/dist/ipc/local-ipc-server.d.ts +91 -0
  87. package/dist/launch.d.ts +1 -1
  88. package/dist/logging/async-batch-writer.d.ts +10 -0
  89. package/dist/logging/debug-config.d.ts +16 -0
  90. package/dist/logging/log-redactor.d.ts +24 -0
  91. package/dist/logging/log-tail-reader.d.ts +81 -0
  92. package/dist/logging/logger.d.ts +1 -1
  93. package/dist/mesh/contracts.d.ts +230 -0
  94. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  95. package/dist/mesh/coordinator-registry.d.ts +59 -0
  96. package/dist/mesh/mesh-active-work.d.ts +203 -0
  97. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  98. package/dist/mesh/mesh-completion-synthesis.d.ts +4 -0
  99. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  100. package/dist/mesh/mesh-delivery-policy.d.ts +104 -0
  101. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  102. package/dist/mesh/mesh-event-forwarding.d.ts +49 -0
  103. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  104. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  105. package/dist/mesh/mesh-events-pending.d.ts +246 -0
  106. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  107. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  108. package/dist/mesh/mesh-events.d.ts +6 -49
  109. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  110. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  111. package/dist/mesh/mesh-init.d.ts +128 -0
  112. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  113. package/dist/mesh/mesh-ledger.d.ts +139 -1
  114. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  115. package/dist/mesh/mesh-missions.d.ts +281 -0
  116. package/dist/mesh/mesh-node-identity.d.ts +310 -0
  117. package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
  118. package/dist/mesh/mesh-reconcile-acked-hold.d.ts +17 -0
  119. package/dist/mesh/mesh-reconcile-config.d.ts +6 -0
  120. package/dist/mesh/mesh-reconcile-identity.d.ts +6 -0
  121. package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
  122. package/dist/mesh/mesh-reconcile-v2-backstop.d.ts +16 -0
  123. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  124. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  125. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  126. package/dist/mesh/mesh-remote-event-pull.d.ts +15 -0
  127. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  128. package/dist/mesh/mesh-routing.d.ts +70 -0
  129. package/dist/mesh/mesh-runtime-store.d.ts +508 -0
  130. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  131. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  132. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  133. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  134. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  135. package/dist/mesh/mesh-work-queue.d.ts +363 -5
  136. package/dist/mesh/preview-freshness.d.ts +28 -0
  137. package/dist/mesh/refine-config.d.ts +216 -0
  138. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  139. package/dist/providers/acp-provider-instance.d.ts +5 -0
  140. package/dist/providers/approval-utils.d.ts +46 -0
  141. package/dist/providers/chat-message-normalization.d.ts +58 -1
  142. package/dist/providers/cli-provider-effect-format.d.ts +30 -0
  143. package/dist/providers/cli-provider-history-dedup.d.ts +17 -0
  144. package/dist/providers/cli-provider-input-prompt.d.ts +12 -0
  145. package/dist/providers/cli-provider-instance-types.d.ts +45 -0
  146. package/dist/providers/cli-provider-instance.d.ts +406 -30
  147. package/dist/providers/cli-provider-status-helpers.d.ts +46 -0
  148. package/dist/providers/cli-provider-transcript-merge.d.ts +7 -0
  149. package/dist/providers/contracts.d.ts +149 -6
  150. package/dist/providers/external-sources.d.ts +71 -0
  151. package/dist/providers/manual-attendance.d.ts +79 -0
  152. package/dist/providers/native-history/antigravity-claim-registry.d.ts +39 -0
  153. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  154. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  155. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  156. package/dist/providers/native-history/constants.d.ts +12 -0
  157. package/dist/providers/native-history/dispatcher.d.ts +44 -0
  158. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  159. package/dist/providers/native-history/index.d.ts +13 -0
  160. package/dist/providers/provider-instance-manager.d.ts +29 -0
  161. package/dist/providers/provider-instance.d.ts +30 -1
  162. package/dist/providers/provider-loader.d.ts +42 -5
  163. package/dist/providers/provider-trust.d.ts +31 -0
  164. package/dist/providers/read-chat-contract.d.ts +29 -0
  165. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  166. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  167. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  168. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  169. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  170. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  171. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  172. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  173. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  174. package/dist/providers/sdk/v1/index.d.ts +30 -0
  175. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  176. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  177. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  178. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  179. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  180. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  181. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  182. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  183. package/dist/providers/spec/adapter.d.ts +98 -0
  184. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  185. package/dist/providers/spec/evaluator.d.ts +45 -0
  186. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  187. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  188. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  189. package/dist/providers/spec/fsm-types.d.ts +202 -0
  190. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  191. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  192. package/dist/providers/spec/route.d.ts +4 -0
  193. package/dist/providers/spec/types.d.ts +244 -0
  194. package/dist/providers/status-monitor.d.ts +7 -7
  195. package/dist/providers/transcript-v2.d.ts +176 -0
  196. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  197. package/dist/providers/working-dir.d.ts +17 -0
  198. package/dist/repo-mesh-types.d.ts +629 -12
  199. package/dist/runtime-defaults.d.ts +2 -0
  200. package/dist/session-host/managed-host.d.ts +64 -0
  201. package/dist/session-host/runtime-surface.d.ts +10 -16
  202. package/dist/sessions/registry.d.ts +26 -0
  203. package/dist/shared-types-extra.d.ts +2 -4
  204. package/dist/shared-types.d.ts +98 -55
  205. package/dist/status/chat-tail-hot-sessions.d.ts +40 -0
  206. package/dist/status/normalize.d.ts +1 -1
  207. package/dist/status/normalize.js +1 -0
  208. package/dist/status/normalize.js.map +1 -1
  209. package/dist/status/normalize.mjs +1 -0
  210. package/dist/status/normalize.mjs.map +1 -1
  211. package/dist/status/reporter.d.ts +2 -0
  212. package/dist/status/snapshot.d.ts +26 -0
  213. package/dist/system/hash.d.ts +8 -0
  214. package/dist/system/load-better-sqlite3.d.ts +21 -0
  215. package/dist/types.d.ts +5 -0
  216. package/package.json +11 -4
  217. package/src/agent-stream/poller.ts +2 -3
  218. package/src/agent-stream/provider-adapter.ts +1 -1
  219. package/src/boot/daemon-lifecycle.ts +80 -14
  220. package/src/boot/process-hardening.ts +89 -0
  221. package/src/build-info.ts +73 -0
  222. package/src/chat/source-machine.ts +534 -0
  223. package/src/chat/source-resolver.ts +0 -0
  224. package/src/chat/subscription-updates.ts +20 -1
  225. package/src/cli-adapter-types.d.ts +3 -1
  226. package/src/cli-adapter-types.ts +68 -2
  227. package/src/cli-adapters/cli-script-runner.ts +421 -0
  228. package/src/cli-adapters/cli-state-engine.ts +1282 -0
  229. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  230. package/src/cli-adapters/provider-cli-adapter.ts +954 -1144
  231. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  232. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  233. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  234. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  235. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  236. package/src/cli-adapters/pty-transport.ts +2 -1
  237. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  238. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  239. package/src/cli-adapters/resolve-executable.ts +204 -0
  240. package/src/cli-adapters/session-host-transport.ts +2 -1
  241. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  242. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  243. package/src/cli-adapters/terminal-screen.ts +16 -81
  244. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  245. package/src/commands/chat-commands-read.ts +2767 -0
  246. package/src/commands/chat-commands-scope.ts +54 -0
  247. package/src/commands/chat-commands-shared.ts +114 -0
  248. package/src/commands/chat-commands-write.ts +891 -0
  249. package/src/commands/chat-commands.ts +19 -1841
  250. package/src/commands/cli-manager.d.ts +2 -0
  251. package/src/commands/cli-manager.ts +659 -27
  252. package/src/commands/handler.ts +845 -2
  253. package/src/commands/high-family/index.ts +28 -0
  254. package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
  255. package/src/commands/high-family/mesh-events.ts +102 -0
  256. package/src/commands/high-family/mesh-status.ts +849 -0
  257. package/src/commands/high-family/types.ts +80 -0
  258. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  259. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  260. package/src/commands/low-family/diagnostics.ts +57 -0
  261. package/src/commands/low-family/index.ts +37 -0
  262. package/src/commands/low-family/mesh-ledger.ts +62 -0
  263. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  264. package/src/commands/low-family/notification.ts +116 -0
  265. package/src/commands/low-family/refine-config.ts +106 -0
  266. package/src/commands/low-family/session-host.ts +282 -0
  267. package/src/commands/low-family/spec-providerdev.ts +217 -0
  268. package/src/commands/low-family/status-meta.ts +112 -0
  269. package/src/commands/low-family/types.ts +39 -0
  270. package/src/commands/med-family/cli-agent.ts +241 -0
  271. package/src/commands/med-family/fast-forward.ts +230 -0
  272. package/src/commands/med-family/ide.ts +163 -0
  273. package/src/commands/med-family/index.ts +37 -0
  274. package/src/commands/med-family/mesh-crud.ts +1287 -0
  275. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  276. package/src/commands/med-family/mesh-queue.ts +167 -0
  277. package/src/commands/med-family/mesh-restart.ts +92 -0
  278. package/src/commands/med-family/types.ts +153 -0
  279. package/src/commands/mesh-coordinator.ts +334 -124
  280. package/src/commands/router-aggregate-status.ts +209 -0
  281. package/src/commands/router-mesh-session-owner.ts +114 -0
  282. package/src/commands/router-refine.ts +1711 -0
  283. package/src/commands/router-worktree-cleanup.ts +870 -0
  284. package/src/commands/router.ts +795 -4143
  285. package/src/commands/stream-commands.ts +8 -0
  286. package/src/commands/upgrade-helper.ts +310 -45
  287. package/src/config/chat-history.ts +517 -24
  288. package/src/config/config.ts +30 -0
  289. package/src/config/mesh-config.ts +632 -23
  290. package/src/config/mesh-json-config.ts +376 -0
  291. package/src/config/recent-activity.ts +8 -2
  292. package/src/config/registry-resolver.ts +100 -0
  293. package/src/config/repo-settings.ts +111 -0
  294. package/src/config/state-store.ts +55 -0
  295. package/src/daemon/dev-auto-implement.ts +3 -2
  296. package/src/daemon/dev-cli-debug.ts +10 -1
  297. package/src/daemon/dev-server.ts +0 -541
  298. package/src/detection/cli-detector.ts +94 -9
  299. package/src/detection/ide-detector.ts +55 -16
  300. package/src/detection/win32-ide-version.ts +106 -0
  301. package/src/git/change-impact-config.ts +354 -0
  302. package/src/git/git-commands.ts +112 -16
  303. package/src/git/git-diff.ts +81 -11
  304. package/src/git/git-executor.ts +12 -0
  305. package/src/git/git-status.ts +767 -48
  306. package/src/git/git-types.ts +14 -62
  307. package/src/git/git-worktree.ts +261 -4
  308. package/src/git/index.ts +17 -0
  309. package/src/index.ts +213 -13
  310. package/src/installer.d.ts +1 -1
  311. package/src/installer.ts +8 -6
  312. package/src/ipc/local-ipc-server.ts +278 -0
  313. package/src/launch.d.ts +1 -1
  314. package/src/launch.ts +37 -28
  315. package/src/logging/async-batch-writer.ts +55 -0
  316. package/src/logging/command-log.ts +7 -5
  317. package/src/logging/debug-config.ts +25 -0
  318. package/src/logging/debug-trace.ts +7 -2
  319. package/src/logging/log-redactor.ts +100 -0
  320. package/src/logging/log-tail-reader.ts +341 -0
  321. package/src/logging/logger.ts +14 -7
  322. package/src/mesh/contracts.ts +469 -0
  323. package/src/mesh/coordinator-prompt.ts +572 -34
  324. package/src/mesh/coordinator-registry.ts +121 -0
  325. package/src/mesh/mesh-active-work.ts +706 -0
  326. package/src/mesh/mesh-clone-grace.ts +68 -0
  327. package/src/mesh/mesh-completion-synthesis.ts +416 -0
  328. package/src/mesh/mesh-coordinator-config.ts +97 -0
  329. package/src/mesh/mesh-delivery-policy.ts +284 -0
  330. package/src/mesh/mesh-event-classify.ts +78 -0
  331. package/src/mesh/mesh-event-forwarding.ts +2002 -0
  332. package/src/mesh/mesh-event-trace.ts +67 -0
  333. package/src/mesh/mesh-events-coordinator.ts +32 -0
  334. package/src/mesh/mesh-events-pending.ts +1494 -0
  335. package/src/mesh/mesh-events-stale.ts +452 -0
  336. package/src/mesh/mesh-events-utils.ts +443 -0
  337. package/src/mesh/mesh-events.ts +43 -1035
  338. package/src/mesh/mesh-fast-forward.ts +856 -0
  339. package/src/mesh/mesh-host-ownership.ts +111 -0
  340. package/src/mesh/mesh-init.ts +350 -0
  341. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  342. package/src/mesh/mesh-ledger.ts +898 -102
  343. package/src/mesh/mesh-magi-status.ts +223 -0
  344. package/src/mesh/mesh-missions.ts +695 -0
  345. package/src/mesh/mesh-node-identity.ts +2065 -0
  346. package/src/mesh/mesh-queue-assignment.ts +2263 -0
  347. package/src/mesh/mesh-reconcile-acked-hold.ts +230 -0
  348. package/src/mesh/mesh-reconcile-config.ts +66 -0
  349. package/src/mesh/mesh-reconcile-identity.ts +103 -0
  350. package/src/mesh/mesh-reconcile-loop.ts +1473 -0
  351. package/src/mesh/mesh-reconcile-v2-backstop.ts +62 -0
  352. package/src/mesh/mesh-refine-batch.ts +205 -0
  353. package/src/mesh/mesh-refine-gates.ts +1686 -0
  354. package/src/mesh/mesh-refine-status.ts +231 -0
  355. package/src/mesh/mesh-remote-event-pull.ts +279 -0
  356. package/src/mesh/mesh-review-inbox.ts +308 -0
  357. package/src/mesh/mesh-routing.ts +291 -0
  358. package/src/mesh/mesh-runtime-store.ts +2150 -0
  359. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  360. package/src/mesh/mesh-task-inflight.ts +70 -0
  361. package/src/mesh/mesh-task-stats.ts +161 -0
  362. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  363. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  364. package/src/mesh/mesh-work-queue.ts +1437 -147
  365. package/src/mesh/preview-freshness.ts +163 -0
  366. package/src/mesh/refine-config.ts +423 -0
  367. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  368. package/src/providers/acp-provider-instance.ts +43 -10
  369. package/src/providers/approval-utils.d.ts +5 -0
  370. package/src/providers/approval-utils.ts +100 -6
  371. package/src/providers/chat-message-normalization.ts +126 -4
  372. package/src/providers/cli-provider-effect-format.ts +53 -0
  373. package/src/providers/cli-provider-history-dedup.ts +75 -0
  374. package/src/providers/cli-provider-input-prompt.ts +133 -0
  375. package/src/providers/cli-provider-instance-types.ts +131 -0
  376. package/src/providers/cli-provider-instance.ts +2709 -499
  377. package/src/providers/cli-provider-status-helpers.ts +123 -0
  378. package/src/providers/cli-provider-transcript-merge.ts +114 -0
  379. package/src/providers/contracts.d.ts +55 -0
  380. package/src/providers/contracts.ts +160 -6
  381. package/src/providers/extension-provider-instance.ts +12 -7
  382. package/src/providers/external-sources.ts +218 -0
  383. package/src/providers/ide-provider-instance.ts +35 -12
  384. package/src/providers/manual-attendance.ts +105 -0
  385. package/src/providers/native-history/antigravity-claim-registry.ts +138 -0
  386. package/src/providers/native-history/antigravity-cli-transcript.ts +1275 -0
  387. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  388. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  389. package/src/providers/native-history/constants.ts +19 -0
  390. package/src/providers/native-history/dispatcher.ts +617 -0
  391. package/src/providers/native-history/hermes-cli-transcript.ts +312 -0
  392. package/src/providers/native-history/index.ts +30 -0
  393. package/src/providers/provider-instance-manager.ts +71 -0
  394. package/src/providers/provider-instance.ts +24 -1
  395. package/src/providers/provider-loader.ts +700 -55
  396. package/src/providers/provider-schema.ts +87 -14
  397. package/src/providers/provider-trust.ts +114 -0
  398. package/src/providers/read-chat-contract.ts +76 -16
  399. package/src/providers/sdk/README.md +49 -0
  400. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  401. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  402. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  403. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  404. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  405. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  406. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  407. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  408. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  409. package/src/providers/sdk/v1/index.ts +152 -0
  410. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  411. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  412. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  413. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  414. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  415. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  416. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  417. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  418. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  419. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  420. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  421. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  422. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  423. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  424. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  425. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  426. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  427. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  428. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  429. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  430. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  431. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  432. package/src/providers/sdk/v1/validators/index.ts +19 -0
  433. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  434. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  435. package/src/providers/spec/adapter.ts +246 -0
  436. package/src/providers/spec/cli-adapter.ts +1064 -0
  437. package/src/providers/spec/evaluator.ts +407 -0
  438. package/src/providers/spec/fsm-driver.ts +1528 -0
  439. package/src/providers/spec/fsm-evaluator.ts +290 -0
  440. package/src/providers/spec/fsm-loader.ts +128 -0
  441. package/src/providers/spec/fsm-types.ts +301 -0
  442. package/src/providers/spec/native-history-executor.ts +1241 -0
  443. package/src/providers/spec/pre-launch-trust.ts +104 -0
  444. package/src/providers/spec/route.ts +51 -0
  445. package/src/providers/spec/types.ts +284 -0
  446. package/src/providers/status-monitor.d.ts +7 -7
  447. package/src/providers/status-monitor.ts +37 -22
  448. package/src/providers/transcript-v2.ts +567 -0
  449. package/src/providers/types/interactive-prompt.ts +536 -0
  450. package/src/providers/version-archive.ts +64 -24
  451. package/src/providers/working-dir.ts +23 -0
  452. package/src/repo-mesh-types.ts +868 -13
  453. package/src/runtime-defaults.ts +39 -0
  454. package/src/session-host/managed-host.ts +218 -0
  455. package/src/session-host/runtime-surface.ts +20 -80
  456. package/src/sessions/registry.ts +44 -0
  457. package/src/shared-types-extra.ts +2 -4
  458. package/src/shared-types.d.ts +8 -0
  459. package/src/shared-types.ts +136 -55
  460. package/src/status/builders.ts +26 -6
  461. package/src/status/chat-tail-hot-sessions.ts +117 -2
  462. package/src/status/normalize.ts +2 -0
  463. package/src/status/reporter.ts +19 -1
  464. package/src/status/snapshot.ts +95 -26
  465. package/src/system/hash.ts +23 -0
  466. package/src/system/host-memory.ts +29 -12
  467. package/src/system/load-better-sqlite3.ts +68 -0
  468. package/src/types.ts +5 -0
  469. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  470. package/dist/mesh/mesh-sync.d.ts +0 -53
  471. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  472. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  473. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1473 @@
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 { loadConfig } from '../config/config.js';
45
+ import { listMeshes } from '../config/mesh-config.js';
46
+ import { LOG, getLogLevel } from '../logging/logger.js';
47
+ import { drainPendingMeshCoordinatorEvents, getPendingMeshCoordinatorEvents, buildPendingEventFingerprint, queuePendingMeshCoordinatorEvent } from './mesh-events-pending.js';
48
+ import type { PendingMeshCoordinatorEvent } from './mesh-events-pending.js';
49
+ import { appendLedgerEntry } from './mesh-ledger.js';
50
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
51
+ import { handleMeshForwardEvent, shouldForceInjectMeshEvent, triggerMeshQueue, resolveForwardEventMeshId } from './mesh-events-coordinator.js';
52
+ import { isMeshApprovalEvent, MESH_APPROVAL_EVENTS } from './mesh-event-classify.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, sessionIdsEquivalent } from '@adhdev/mesh-shared';
61
+ import { getQueue, reclaimStrandedAssignedTask, updateTaskStatus } from './mesh-work-queue.js';
62
+ import { resolveSessionBusyVerdict } from './mesh-queue-assignment.js';
63
+ import { readLedgerEntries } from './mesh-ledger.js';
64
+ import type { MeshLedgerEntry } from './mesh-ledger.js';
65
+ import { findTerminalLedgerEvidenceForTask } from './mesh-events-stale.js';
66
+ import {
67
+ resolveCoordinatorDaemonIds,
68
+ daemonHostsMesh,
69
+ resolveCoordinatorSelfIds,
70
+ } from './mesh-reconcile-identity.js';
71
+ import {
72
+ resolveAutoPruneMinAgeMs,
73
+ resolvePendingHeldDrainEscalateMs,
74
+ resolveReconcileIntervalMs,
75
+ } from './mesh-reconcile-config.js';
76
+ import { pullRemoteNodeQueues } from './mesh-remote-event-pull.js';
77
+ import {
78
+ reconcileUnterminatedDirectDispatches,
79
+ autoPruneStaleDirectDispatches,
80
+ } from './mesh-completion-synthesis.js';
81
+
82
+ // Re-export the extracted public API so existing importers (mesh-events.ts barrel;
83
+ // the reconcile-loop test suite) keep their `from './mesh-reconcile-loop.js'` paths.
84
+ export { getMeshV2BackstopCounters, __resetMeshV2BackstopCountersForTests } from './mesh-reconcile-v2-backstop.js';
85
+ export { __resetReconcileInFlightSynthDebounceForTests } from './mesh-reconcile-acked-hold.js';
86
+
87
+ // Reconcile-loop timing tunables + their env-override resolvers
88
+ // (DEFAULT_RECONCILE_INTERVAL_MS, DEFAULT_AUTO_PRUNE_MIN_AGE_MS,
89
+ // DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS, resolveReconcileIntervalMs,
90
+ // resolveAutoPruneMinAgeMs, resolvePendingHeldDrainEscalateMs) live in
91
+ // ./mesh-reconcile-config.ts (A-3 extraction) and are imported above.
92
+
93
+ interface LiveCoordinator {
94
+ meshId: string;
95
+ instance: ReturnType<DaemonComponents['instanceManager']['getInstance']>;
96
+ // Runtime session id of this coordinator instance (getState().instanceId). PHASE 2
97
+ // strict-matches an event's targetCoordinatorSessionId against this so a completion
98
+ // routes back to the exact originating coordinator session, not a sibling on the same
99
+ // daemon (the multi-coordinator misroute).
100
+ sessionId: string;
101
+ // PTY-OVERTRUST-DRAIN (Defect B): drain-eligibility, decided on the RAW adapter
102
+ // turn-state (mask-stripped) — NOT on getState().status, which overlays the
103
+ // auto-approve "hold-idle" visual mask that paints a genuinely-idle coordinator
104
+ // `generating` and so used to strand its worker's completion. True only when the
105
+ // raw adapter is at a real turn end AND the session is not modal-parked. When the
106
+ // instance does not expose getDrainStatus() (non-CLI / older), this falls back to
107
+ // the masked `status === 'idle'` (the pre-fix behaviour) so nothing regresses.
108
+ idle: boolean;
109
+ // True when the coordinator session is parked on a harness modal awaiting a
110
+ // human answer — claude-cli AskUserQuestion (waiting_choice) or a tool-consent
111
+ // prompt (waiting_approval). A force-inject into such a session would write raw
112
+ // keystrokes the modal key handler consumes, silently selecting a choice the
113
+ // user never made (data corruption). PHASE 2 excludes these from force-inject
114
+ // and leaves the event queued for a later (modal-resolved) tick.
115
+ modalParked: boolean;
116
+ }
117
+
118
+ // Observability: last-seen modal-park state per coordinator session, so we LOG.info
119
+ // only on a TRANSITION (clear → parked, parked → cleared) instead of every 4s tick.
120
+ // Per-process; a restart re-logs the first observation, which is desirable — it
121
+ // re-confirms a coordinator that is still parked after the restart (the exact
122
+ // "restart does not clear it" symptom the operator needs visibility into).
123
+ const coordinatorModalParkState = new Map<string, boolean>();
124
+
125
+ // Find live CLI coordinator instances on THIS daemon, keyed by mesh.
126
+ function findLiveCoordinators(components: DaemonComponents): LiveCoordinator[] {
127
+ const out: LiveCoordinator[] = [];
128
+ for (const inst of components.instanceManager.getByCategory('cli')) {
129
+ const state = inst.getState();
130
+ const settings = state.settings && typeof state.settings === 'object'
131
+ ? state.settings as Record<string, unknown>
132
+ : {};
133
+ const meshId = readNonEmptyString(settings.meshCoordinatorFor);
134
+ if (!meshId) continue;
135
+ const status = readNonEmptyString(state.status).toLowerCase();
136
+ // getState() overlays the modal-park statuses: an active AskUserQuestion
137
+ // prompt surfaces as waiting_choice, a tool-consent prompt as waiting_approval.
138
+ // NOTIF-HELD-DRAIN (Fix 1): consult the instance's own isModalParked() rather than the
139
+ // raw status literal so the corrected classification flows here — a busy mesh
140
+ // coordinator's routine, in-flight tool-consent (auto-approve off) is NOT a human-await
141
+ // modal and must NOT wedge the mesh's pending completion events under `modal_parked`.
142
+ // resolveModalParkStatus() (which isModalParked wraps) already encodes that distinction
143
+ // and the waiting_choice/stalled-auto-approve genuine-modal cases. Fall back to the
144
+ // status literal for any instance that does not expose the method. Lowercase compare —
145
+ // the SessionStatus enum is forked across modules and waiting_choice is absent from some.
146
+ const modalParked = typeof (inst as any).isModalParked === 'function'
147
+ ? (inst as any).isModalParked() === true
148
+ : (status === 'waiting_choice' || status === 'waiting_approval');
149
+ // PTY-OVERTRUST-DRAIN (Defect B, fix A): drain-eligible idle is decided on the
150
+ // RAW adapter turn-state, not getState().status. getState() overlays the
151
+ // auto-approve hold-idle mask that paints a genuinely-idle coordinator
152
+ // `generating` (a UI-flicker suppressant), and the reconcile loop used to trust
153
+ // that mask and HOLD the worker's completion (generating_no_idle_coordinator)
154
+ // even though the PTY was at a real turn end. getDrainStatus() strips the mask
155
+ // (raw adapter idle, modal-park preserved). Fall back to the masked literal for
156
+ // any instance that does not expose it (non-CLI / older) — regression-0.
157
+ const drainStatus: string | null = typeof (inst as any).getDrainStatus === 'function'
158
+ ? (inst as any).getDrainStatus()
159
+ : null;
160
+ const idle = drainStatus !== null ? drainStatus === 'idle' : (status === 'idle');
161
+ const sessionId = readNonEmptyString(state.instanceId);
162
+ // ── NOTIF (B) desync diagnostic (read-only, no behavior change) ───────────
163
+ // The confirmed (B) defect: a coordinator whose FSM is idle (status above ===
164
+ // 'idle' for minutes) is nonetheless classified busy here, so the generating/
165
+ // modal-park hold never drains and a worker completion is stranded until the
166
+ // user's next turn edge. Static analysis found no code path where getState()
167
+ // returns generating while lastStatus and the adapter raw are both idle — so the
168
+ // divergence is a runtime desync between the three status sources. Capture all
169
+ // three (plus the auto-approve mask state that getState() overlays at :803) for
170
+ // EVERY mesh-coordinator candidate on this tick, so the source that diverges from
171
+ // the others can be read directly against the same-tick "skip → generating"/
172
+ // "skip → modal-parked" hold logs below (pair by sessionId + timestamp).
173
+ //
174
+ // CRITICAL: reuse the `state` already fetched above (line ~301) — do NOT call
175
+ // getState() again. getState() runs maybeAutoApproveStatus() as a side effect,
176
+ // which would mutate the very auto-approve mask we are trying to observe. The
177
+ // adapter raw read uses allowParse:false, which only reads engine.activeModal and
178
+ // is side-effect-free.
179
+ if (getLogLevel() === 'debug') {
180
+ let adapterRaw = '?';
181
+ try {
182
+ const a = (inst as any).adapter;
183
+ if (a && typeof a.getStatus === 'function') {
184
+ adapterRaw = readNonEmptyString(a.getStatus({ allowParse: false })?.status) || '?';
185
+ }
186
+ } catch (e: any) {
187
+ adapterRaw = `err:${e?.message || e}`;
188
+ }
189
+ const lastStatus = readNonEmptyString((inst as any).lastStatus) || '?';
190
+ const autoApproveBusy = (inst as any).autoApproveBusy;
191
+ const maskSince = (inst as any).autoApproveMaskSince;
192
+ // PTY-OVERTRUST-DRAIN: include the mask-stripped drainStatus next to the three
193
+ // legacy sources so the divergence (getState=generating while adapterRaw=idle =
194
+ // the mask) is directly readable, and confirm drain now follows adapterRaw.
195
+ LOG.debug('MeshReconcile', `coordDiag sess=${sessionId || '?'} mesh=${meshId} getState=${status || '?'} drainStatus=${drainStatus || 'n/a'} lastStatus=${lastStatus} adapterRaw=${adapterRaw} autoApproveBusy=${autoApproveBusy === true} maskSince=${maskSince || 0}`);
196
+ }
197
+ // Modal-park transition observability: a coordinator entering modal-park is what
198
+ // begins holding completion events under `modal_parked`; one leaving it is what
199
+ // drains them. Both transitions were previously SILENT (the operator had no log
200
+ // to diagnose a stuck/held completion), so emit a single line per edge.
201
+ const stateKey = `${meshId}::${sessionId || '?'}`;
202
+ const prevParked = coordinatorModalParkState.get(stateKey);
203
+ if (prevParked !== modalParked) {
204
+ coordinatorModalParkState.set(stateKey, modalParked);
205
+ if (modalParked) {
206
+ LOG.info('MeshReconcile', `Coordinator ${sessionId || '?'} (mesh ${meshId}) entered modal-park (status=${status}) — terminal events for it will be held until the modal is answered`);
207
+ } else if (prevParked === true) {
208
+ LOG.info('MeshReconcile', `Coordinator ${sessionId || '?'} (mesh ${meshId}) left modal-park (status=${status}) — held events will drain on this/next tick`);
209
+ }
210
+ }
211
+ out.push({ meshId, instance: inst, sessionId, idle, modalParked });
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /**
217
+ * DRAIN-WITHOUT-INJECT guard. Classify, for a mesh on THIS daemon, whether a
218
+ * queue-drain caller (the MCP `get_pending_mesh_events` poll) may safely consume
219
+ * pending coordinator events — i.e. whether there is a surface that will actually
220
+ * deliver them.
221
+ *
222
+ * Root cause being guarded: `get_pending_mesh_events` marks rows drained=1
223
+ * atomically and unconditionally. When the live CLI coordinator for the mesh is
224
+ * GENERATING (or modal-parked), the reconcile loop correctly HOLDS its terminal
225
+ * events (drained=0) for the coordinator's next idle tick — but a concurrent MCP
226
+ * poll draining the SAME queue consumes those held rows into a tool result that
227
+ * the busy coordinator never surfaces as a turn, so the completion is lost
228
+ * forever (drained=1, never re-queued). The reconcile loop is the authoritative
229
+ * delivery path for a live CLI coordinator; the MCP poll must defer to it.
230
+ *
231
+ * Returns:
232
+ * - hasLiveCliCoordinator: a CLI session with meshCoordinatorFor === meshId
233
+ * exists on this daemon (the reconcile loop owns its delivery).
234
+ * - deliverableNow: there is an IDLE live CLI coordinator (reconcile would
235
+ * full-drain into it) — draining now is safe and equivalent.
236
+ * - holdForReconcile: a live CLI coordinator exists but is non-idle
237
+ * (generating / modal-parked). The MCP poll MUST NOT drain; the reconcile
238
+ * loop holds the events undrained and injects them on the next idle tick.
239
+ *
240
+ * A mesh with NO live CLI coordinator on this daemon is a pure stdio MCP / LLM
241
+ * coordinator: the MCP tool result IS the only surface, so the poll legitimately
242
+ * drains (holdForReconcile=false). No regression to that path.
243
+ */
244
+ export function resolveCoordinatorDrainDeliverability(
245
+ components: Pick<DaemonComponents, 'instanceManager'>,
246
+ meshId: string,
247
+ ): { hasLiveCliCoordinator: boolean; deliverableNow: boolean; holdForReconcile: boolean } {
248
+ const coordinators = findLiveCoordinators(components as DaemonComponents).filter(c => c.meshId === meshId);
249
+ if (coordinators.length === 0) {
250
+ return { hasLiveCliCoordinator: false, deliverableNow: false, holdForReconcile: false };
251
+ }
252
+ const hasIdle = coordinators.some(c => c.idle);
253
+ return {
254
+ hasLiveCliCoordinator: true,
255
+ deliverableNow: hasIdle,
256
+ // A live CLI coordinator exists but none is idle → the reconcile loop is
257
+ // holding the events; the poll must not steal them.
258
+ holdForReconcile: !hasIdle,
259
+ };
260
+ }
261
+
262
+ /**
263
+ * DRAIN-WITHOUT-INJECT guard for the `get_pending_mesh_events` daemon handler.
264
+ *
265
+ * Decides whether an incoming pending-events DRAIN must be held (return nothing,
266
+ * leave rows drained=0) because the only surface for those events is a LOCAL live
267
+ * CLI coordinator that is currently busy (generating / modal-parked) — in which
268
+ * case the reconcile loop owns delivery on the coordinator's next idle tick, and
269
+ * the poll draining them now would lose them.
270
+ *
271
+ * The hold applies ONLY when BOTH:
272
+ * 1) a live CLI coordinator for this mesh on THIS daemon is non-idle, AND
273
+ * 2) the drain is targeted at THIS daemon (the requested coordinatorDaemonId is
274
+ * empty/broadcast, or matches one of this daemon's id forms).
275
+ *
276
+ * A REMOTE coordinator pulling our worker's events passes its own (remote)
277
+ * coordinatorDaemonId — condition (2) is false — so the drain proceeds and the
278
+ * remote pull is never blocked by our local coordinator's busy state. A pure
279
+ * stdio MCP coordinator (no live CLI session) never satisfies (1), so its tool
280
+ * result remains the surface and the drain proceeds. No regression to either.
281
+ *
282
+ * SELF-COORDINATOR INBOX LEVEL-DRAIN (Defect 2): the hold above assumes the ONLY
283
+ * surface for a busy local coordinator's events is a future PTY inject on its idle
284
+ * edge, so it defers to the reconcile loop. But when the drain caller IS the local
285
+ * coordinator reading its OWN inbox (the `get_pending_mesh_events` call whose events
286
+ * are returned in the caller's tool RESULT — a data queue the self-coordinating LLM
287
+ * consumes directly), the events ARE surfaced losslessly the moment the tool returns,
288
+ * with NO PTY write. A busy self-coordinating LLM that calls a mesh tool mid-turn would
289
+ * otherwise get an empty inbox (held) and only see the completion on its NEXT busy→idle
290
+ * edge — the measured ~59s strand. `callerIsSelfCoordinatorInboxRead` marks that safe
291
+ * caller: the hold is relaxed for it (return the events), while every OTHER drain (a
292
+ * backfill relay, a broadcast poll, a DIFFERENT coordinator that genuinely needs its PTY)
293
+ * still defers to the reconcile loop. This relaxes delivery INTO the coordinator's own
294
+ * inbox only — it never changes how events are injected into a live PTY prompt.
295
+ */
296
+ export function shouldHoldPendingDrainForBusyLocalCoordinator(
297
+ components: Pick<DaemonComponents, 'instanceManager'> & { statusInstanceId?: string },
298
+ meshId: string,
299
+ requestedCoordinatorDaemonId?: string | null,
300
+ callerIsSelfCoordinatorInboxRead?: boolean,
301
+ ): boolean {
302
+ if (!meshId) return false;
303
+ const deliverability = resolveCoordinatorDrainDeliverability(components, meshId);
304
+ if (!deliverability.holdForReconcile) return false;
305
+ // The local CLI coordinator is busy. Hold only when the drain is for THIS daemon.
306
+ const requested = readNonEmptyString(requestedCoordinatorDaemonId);
307
+ if (!requested) return true; // broadcast drain → would consume the held local events
308
+ const localIds = expandDaemonIdForms([
309
+ readNonEmptyString((components as { statusInstanceId?: string }).statusInstanceId),
310
+ readNonEmptyString(loadConfig().machineId),
311
+ ]);
312
+ const targetsLocalCoordinator = localIds.some(id => daemonIdsEquivalent(id, requested));
313
+ if (!targetsLocalCoordinator) return false;
314
+ // SELF-COORDINATOR INBOX LEVEL-DRAIN: the busy local coordinator is itself the caller,
315
+ // reading its own inbox — the drained events return in ITS tool result (lossless data-queue
316
+ // surface, no PTY inject). Do NOT hold; let the self-coordinator see its completions now.
317
+ if (callerIsSelfCoordinatorInboxRead) return false;
318
+ return true;
319
+ }
320
+
321
+ // Inject a drained pending event into a live coordinator session. Force-inject
322
+ // events carry force:true so they bypass the busy send-guard and land in the PTY
323
+ // even while the coordinator is generating (see shouldForceInjectMeshEvent).
324
+ function injectPendingIntoCoordinator(
325
+ coordinator: LiveCoordinator['instance'],
326
+ pending: PendingMeshCoordinatorEvent,
327
+ opts?: { forceOverride?: boolean },
328
+ ): void {
329
+ if (!coordinator) return;
330
+ // NOTIF-DROP-SYNTH-NO-MESSAGE (defence-in-depth): a queued event with no coordinatorMessage
331
+ // used to be dropped here (drain-without-inject) — the row had already been consumed
332
+ // (drained=1) by the caller's drain, so silently returning lost it forever. The primary fix
333
+ // makes the transcript-reconcile synth always carry a coordinatorMessage, but as a backstop,
334
+ // lazily synthesize the [System] text for any force-inject (terminal: completion / approval /
335
+ // stop / refine·bootstrap) event that still arrives message-less, so it surfaces instead of
336
+ // vanishing. A NON-force lifecycle event (agent:ready / generating_started) legitimately
337
+ // carries no message and must NOT be injected (it is queued only to re-drive the claim state
338
+ // machine on pull) — for it we still return without injecting.
339
+ let coordinatorMessage = pending.coordinatorMessage;
340
+ if (!coordinatorMessage) {
341
+ if (!shouldForceInjectMeshEvent(pending.event)) return;
342
+ const metadataEvent = pending.metadataEvent && typeof pending.metadataEvent === 'object'
343
+ ? pending.metadataEvent
344
+ : {};
345
+ coordinatorMessage = buildMeshSystemMessage({
346
+ event: pending.event,
347
+ nodeLabel: pending.nodeLabel,
348
+ metadataEvent,
349
+ });
350
+ if (!coordinatorMessage) return; // builder produced nothing — nothing to surface
351
+ LOG.warn('MeshReconcile', `Lazily synthesized missing coordinatorMessage for ${pending.event} (mesh ${pending.meshId}) at inject time — a queued terminal event arrived message-less`);
352
+ }
353
+ // forceOverride lets the APPROVAL-Q1-REALTIME nudge path deliver into a busy
354
+ // coordinator WITHOUT a raw PTY force-write (force-inject-into-generating stays
355
+ // intentionally removed): a non-force send_message enters the adapter's
356
+ // pendingOutboundQueue and is surfaced at the coordinator's next turn boundary.
357
+ const force = opts?.forceOverride ?? shouldForceInjectMeshEvent(pending.event);
358
+ // EVTTRACE: event surfaced to the coordinator (injected into its live CLI session).
359
+ // This is the terminal happy-path stage. Observation only.
360
+ traceMeshEventStage('surfaced', {
361
+ taskId: pending.metadataEvent?.taskId,
362
+ sessionId: pending.metadataEvent?.targetSessionId ?? pending.targetCoordinatorSessionId,
363
+ nodeId: pending.nodeId,
364
+ meshId: pending.meshId,
365
+ event: pending.event,
366
+ }, force ? 'force-inject' : 'inject');
367
+ coordinator.onEvent('send_message', {
368
+ input: { text: coordinatorMessage, textFallback: coordinatorMessage },
369
+ ...(force ? { force: true } : {}),
370
+ });
371
+ }
372
+
373
+ // Held-event ledger dedup: fingerprints of held terminal events already written as an
374
+ // `event_held` ledger audit record in THIS process. Prevents the 4s reconcile tick from
375
+ // re-logging the same held event every interval while a coordinator stays modal-parked.
376
+ // Per-process only (not persisted) — if the daemon restarts while an event is still held
377
+ // it is re-logged once, which is desirable: it re-confirms the event is still undelivered.
378
+ const heldEventLedgerRecorded = new Set<string>();
379
+
380
+ // C1 (data safety): when a terminal completion/approval/bootstrap event cannot be
381
+ // delivered because the only coordinators are modal-parked, the event is held at
382
+ // drained=0 in the pending queue (SQLite + JSONL) for a later tick. That queue is
383
+ // disk-persisted but carries no operator-visible audit trail and can be silently
384
+ // dropped by the pending-file trim (100 KB / 50-entry cap). To guarantee a held
385
+ // completion's worker summary is never silently lost, mirror each held terminal event
386
+ // into the coordinator's mesh ledger as an `event_held` entry — auditable and
387
+ // recoverable (the finalSummary survives even if the pending copy is later trimmed or
388
+ // the coordinator session is force-resolved before re-drain). Idempotent per process
389
+ // via heldEventLedgerRecorded so a long modal park does not spam the ledger.
390
+ function recordHeldTerminalEventsToLedger(
391
+ meshId: string,
392
+ drainDaemonIds: string[],
393
+ reason: string,
394
+ heldForCoordinatorCount: number,
395
+ ): void {
396
+ let pending: readonly PendingMeshCoordinatorEvent[];
397
+ try {
398
+ pending = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
399
+ } catch {
400
+ return; // best-effort audit — never let a peek failure break the tick
401
+ }
402
+ for (const event of pending) {
403
+ // Only audit terminal/force-inject events (completion / approval / stop / refine·
404
+ // bootstrap). Silent lifecycle events (agent:ready / generating_started) carry no
405
+ // worker output to preserve and re-drain harmlessly, so they need no audit trail.
406
+ if (!shouldForceInjectMeshEvent(event.event)) continue;
407
+ const fingerprint = buildPendingEventFingerprint(event);
408
+ const key = `${meshId}::${fingerprint || `${event.event}::${event.nodeId || ''}::${event.queuedAt}`}`;
409
+ if (heldEventLedgerRecorded.has(key)) continue;
410
+ heldEventLedgerRecorded.add(key);
411
+ const finalSummary = readMeshCompletionSummary(event.metadataEvent);
412
+ try {
413
+ appendLedgerEntry(meshId, {
414
+ kind: 'event_held',
415
+ ...(event.nodeId ? { nodeId: event.nodeId } : {}),
416
+ payload: {
417
+ event: event.event,
418
+ reason,
419
+ recoverable: true,
420
+ heldForCoordinators: heldForCoordinatorCount,
421
+ nodeLabel: event.nodeLabel,
422
+ ...(event.workspace ? { workspace: event.workspace } : {}),
423
+ targetCoordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
424
+ queuedAt: event.queuedAt,
425
+ ...(fingerprint ? { fingerprint } : {}),
426
+ ...(finalSummary ? { finalSummary } : {}),
427
+ },
428
+ });
429
+ LOG.info('MeshReconcile', `Ledger-recorded held ${event.event} for mesh ${meshId} (reason ${reason}) — recoverable from ledger`);
430
+ } catch (e: any) {
431
+ // Failed to persist — drop the dedup marker so the next tick retries.
432
+ heldEventLedgerRecorded.delete(key);
433
+ LOG.warn('MeshReconcile', `Failed to ledger-record held ${event.event} for mesh ${meshId}: ${e?.message || e}`);
434
+ }
435
+ }
436
+ }
437
+
438
+ // PTY-OVERTRUST-DRAIN (Defect B, fix B). Age of the OLDEST queued terminal/force-inject
439
+ // event for a mesh, in ms — the signal the generating-hold age-escape gates on. Returns 0
440
+ // when there is no held terminal event (no escape needed). Best-effort: a peek failure
441
+ // returns 0 (no escape this tick), never throws into the tick.
442
+ function oldestHeldTerminalEventAgeMs(meshId: string, drainDaemonIds: string[]): number {
443
+ let pending: readonly PendingMeshCoordinatorEvent[];
444
+ try {
445
+ pending = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
446
+ } catch {
447
+ return 0;
448
+ }
449
+ const now = Date.now();
450
+ let maxAge = 0;
451
+ for (const event of pending) {
452
+ if (!shouldForceInjectMeshEvent(event.event)) continue; // only terminal events matter
453
+ const queuedAt = typeof event.queuedAt === 'number' ? event.queuedAt : now;
454
+ const age = now - queuedAt;
455
+ if (age > maxAge) maxAge = age;
456
+ }
457
+ return maxAge;
458
+ }
459
+
460
+ // PTY-OVERTRUST-DRAIN (Defect B, fix B). Re-confirm, on the RAW adapter (mask-stripped),
461
+ // which of the held-as-generating coordinators is GENUINELY idle right now. A coordinator
462
+ // whose getDrainStatus() reads 'idle' is a real drain target the time-based escape may
463
+ // deliver into. One that still reads 'generating'/'modal_parked'/'other' stays held — the
464
+ // escape NEVER injects into a genuinely-busy PTY (that is the data-loss force-inject path
465
+ // intentionally removed; re-confirmation is what keeps this safe). Falls back to the
466
+ // coordinator's already-computed `idle` flag when the instance does not expose
467
+ // getDrainStatus() (non-CLI / older) — that flag is itself raw-adapter-derived post-fix-A.
468
+ function reconfirmGenuinelyIdleCoordinators(generating: LiveCoordinator[]): LiveCoordinator[] {
469
+ const out: LiveCoordinator[] = [];
470
+ for (const c of generating) {
471
+ const inst = c.instance as any;
472
+ const drainStatus: string | null = typeof inst?.getDrainStatus === 'function'
473
+ ? inst.getDrainStatus()
474
+ : null;
475
+ const genuinelyIdle = drainStatus !== null ? drainStatus === 'idle' : c.idle;
476
+ if (genuinelyIdle) out.push({ ...c, idle: true });
477
+ }
478
+ return out;
479
+ }
480
+
481
+ // Full-drain the local pending queue for a mesh and inject every event into the given
482
+ // IDLE target coordinators, honouring strict session routing. Shared by the normal idle
483
+ // delivery path and the Defect-B age-escape so both deliver identically (one drain, one
484
+ // inject-per-event, strict-route hold for an unmatched session). Returns the number of
485
+ // events drained (0 when the queue was empty / drain failed). Callers must have already
486
+ // confirmed the targets are genuinely idle.
487
+ function drainAndInjectIntoTargets(
488
+ meshId: string,
489
+ drainDaemonIds: string[],
490
+ localDaemonId: string | undefined,
491
+ targetCoordinators: LiveCoordinator[],
492
+ logLabel: string,
493
+ ): number {
494
+ let pendingEvents: PendingMeshCoordinatorEvent[] = [];
495
+ try {
496
+ pendingEvents = drainPendingMeshCoordinatorEvents(
497
+ meshId,
498
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
499
+ );
500
+ } catch (e: any) {
501
+ LOG.warn('MeshReconcile', `Drain failed for mesh ${meshId}: ${e?.message || e}`);
502
+ return 0;
503
+ }
504
+ if (pendingEvents.length === 0) return 0;
505
+
506
+ LOG.info('MeshReconcile', `Reconcile inject → ${logLabel}: ${pendingEvents.length} pending event(s) → ${targetCoordinators.length} coordinator(s) for mesh ${meshId}`);
507
+ for (const pending of pendingEvents) {
508
+ // Strict session routing (multi-coordinator): when the event names an
509
+ // originating coordinator session, deliver ONLY to the live coordinator whose
510
+ // session id matches — a sibling coordinator on the same daemon must NOT receive
511
+ // another coordinator's completion. When the event carries no session id (legacy /
512
+ // version-skewed / single-coordinator), fall back to the daemon-level set
513
+ // (unchanged behaviour — regression-0 for the common case).
514
+ const wantSession = readNonEmptyString(pending.targetCoordinatorSessionId);
515
+ if (wantSession) {
516
+ // Session ids are single-form; sessionIdsEquivalent is the one canonical
517
+ // exact-match predicate — unlike the daemon-level set below it needs no
518
+ // form expansion.
519
+ const matched = targetCoordinators.filter(c => sessionIdsEquivalent(c.sessionId, wantSession));
520
+ if (matched.length === 0) {
521
+ // The originating coordinator session is not deliverable on this daemon
522
+ // right now (gone, or modal-parked and excluded from targets). Strict mode
523
+ // does NOT broadcast to siblings — hold the event for a later tick, and
524
+ // ledger-expire it past a TTL so it can never wedge forever.
525
+ holdOrExpireStrictUnmatchedEvent(pending, wantSession, meshId);
526
+ continue;
527
+ }
528
+ for (const c of matched) injectPendingIntoCoordinator(c.instance, pending);
529
+ continue;
530
+ }
531
+ for (const c of targetCoordinators) {
532
+ injectPendingIntoCoordinator(c.instance, pending);
533
+ }
534
+ }
535
+ return pendingEvents.length;
536
+ }
537
+
538
+ // APPROVAL-Q1-REALTIME stale guard. An approval nudge is RESOLVED once a real terminal
539
+ // ledger entry (task_completed / task_failed) for the same node/session landed at or
540
+ // after the nudge was queued — the worker either finished or died, so it is no longer
541
+ // waiting on that approval. Delivering the nudge then would falsely tell the coordinator
542
+ // the worker is still blocked (the exact UX inversion this fix must avoid), so a resolved
543
+ // nudge is dropped rather than delivered. Ledger-based so the check is daemon-local and
544
+ // deterministic (no dependence on a possibly-remote worker instance's live state).
545
+ function isApprovalNudgeResolved(meshId: string, pending: PendingMeshCoordinatorEvent): boolean {
546
+ const metadataEvent = (pending.metadataEvent && typeof pending.metadataEvent === 'object')
547
+ ? pending.metadataEvent as Record<string, unknown>
548
+ : {};
549
+ const nodeId = readNonEmptyString(pending.nodeId) || readNonEmptyString(metadataEvent.meshNodeId);
550
+ const sessionId = readNonEmptyString(metadataEvent.targetSessionId) || readNonEmptyString(metadataEvent.sessionId);
551
+ if (!nodeId && !sessionId) return false; // nothing to correlate a terminal against
552
+ const queuedAt = typeof pending.queuedAt === 'number' && Number.isFinite(pending.queuedAt) ? pending.queuedAt : 0;
553
+ let entries: MeshLedgerEntry[];
554
+ try {
555
+ entries = readLedgerEntries(meshId);
556
+ } catch {
557
+ return false; // best-effort — a read failure never blocks delivery
558
+ }
559
+ return entries.some(e => {
560
+ if (e.kind !== 'task_completed' && e.kind !== 'task_failed') return false;
561
+ if (queuedAt > 0) {
562
+ const t = new Date(e.timestamp).getTime();
563
+ if (Number.isFinite(t) && t < queuedAt) return false; // terminal predates the nudge
564
+ }
565
+ const nodeMatch = !!nodeId && !!e.nodeId && daemonIdsEquivalent(e.nodeId, nodeId);
566
+ const sessionMatch = !!sessionId && !!e.sessionId && sessionIdsEquivalent(e.sessionId, sessionId);
567
+ return nodeMatch || sessionMatch;
568
+ });
569
+ }
570
+
571
+ // APPROVAL-Q1-REALTIME. Deliver queued approval nudges to a mesh's coordinators every
572
+ // reconcile tick, EVEN when the only coordinators are busy (generating / modal-parked)
573
+ // and there is no idle drain target. This is the crux of the fix: a completion rides the
574
+ // idle-edge hold below (its payload lives only in the pending event), but an approval is
575
+ // LEVEL-backed (task_approval_needed ledger → mesh_status awaiting_approval) so it must
576
+ // NOT wait for an idle edge — during orchestration a coordinator can stay `generating`
577
+ // awaiting the very worker that is blocked on the approval, so the idle edge (the flush
578
+ // point) may never come, and the coordinator's mesh_approve arrives only after a human
579
+ // resolves it ('Not in approval state'). We drain ONLY approval events (leaving every
580
+ // other event for the unchanged hold), drop any already-resolved (stale) nudge, and
581
+ // deliver the rest into each coordinator's inbox WITHOUT a raw PTY force-write (non-force
582
+ // send_message → adapter pendingOutboundQueue → surfaced at the coordinator's next turn
583
+ // boundary). Dropping the pending copy after delivery is safe and prevents re-nudging
584
+ // every 4s — the level ledger state remains the durable, re-derivable source of truth.
585
+ // Returns the number of nudges delivered (0 when none were queued/deliverable).
586
+ function drainAndDeliverApprovalNudges(
587
+ meshId: string,
588
+ drainDaemonIds: string[],
589
+ localDaemonId: string | undefined,
590
+ meshCoordinators: LiveCoordinator[],
591
+ ): number {
592
+ // O(1) guard: only touch the queue when an approval event is actually present.
593
+ let peeked: readonly PendingMeshCoordinatorEvent[];
594
+ try {
595
+ peeked = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
596
+ } catch {
597
+ return 0;
598
+ }
599
+ if (!peeked.some(e => isMeshApprovalEvent(e.event))) return 0;
600
+
601
+ let drained: PendingMeshCoordinatorEvent[];
602
+ try {
603
+ drained = drainPendingMeshCoordinatorEvents(
604
+ meshId,
605
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
606
+ { onlyEvents: MESH_APPROVAL_EVENTS },
607
+ );
608
+ } catch (e: any) {
609
+ LOG.warn('MeshReconcile', `Approval-nudge drain failed for mesh ${meshId}: ${e?.message || e}`);
610
+ return 0;
611
+ }
612
+
613
+ let delivered = 0;
614
+ for (const pending of drained) {
615
+ if (isApprovalNudgeResolved(meshId, pending)) {
616
+ // Stale: already resolved. Drop without delivery — re-surfacing it would
617
+ // mislead the coordinator into believing the worker is still awaiting approval.
618
+ traceMeshEventDrop('approval_nudge_stale_resolved', {
619
+ taskId: readNonEmptyString((pending.metadataEvent as Record<string, unknown>)?.taskId),
620
+ sessionId: readNonEmptyString((pending.metadataEvent as Record<string, unknown>)?.targetSessionId) ?? pending.targetCoordinatorSessionId,
621
+ nodeId: pending.nodeId,
622
+ meshId,
623
+ event: pending.event,
624
+ }, 'approval already resolved (terminal ledger entry present)');
625
+ LOG.info('MeshReconcile', `Dropped stale approval nudge for mesh ${meshId} (${pending.nodeLabel}) — approval already resolved`);
626
+ continue;
627
+ }
628
+ // Strict session routing (multi-coordinator): deliver only to the originating
629
+ // coordinator session when the nudge names one; otherwise broadcast to every
630
+ // coordinator for this mesh. Absent a live matching coordinator we drop the nudge —
631
+ // the level state (awaiting_approval) still surfaces via mesh_status, so nothing is lost.
632
+ const wantSession = readNonEmptyString(pending.targetCoordinatorSessionId);
633
+ const targets = wantSession
634
+ ? meshCoordinators.filter(c => sessionIdsEquivalent(c.sessionId, wantSession))
635
+ : meshCoordinators;
636
+ if (targets.length === 0) continue;
637
+ for (const c of targets) injectPendingIntoCoordinator(c.instance, pending, { forceOverride: false });
638
+ delivered++;
639
+ LOG.info('MeshReconcile', `Delivered approval nudge (level) for mesh ${meshId} (${pending.nodeLabel}) → ${targets.length} coordinator(s) without waiting for an idle edge`);
640
+ }
641
+ return delivered;
642
+ }
643
+
644
+ // One reconcile tick. Two independent phases:
645
+ //
646
+ // PHASE 1 — Remote queue pull (the fix for remote worktree completions never
647
+ // reaching an MCP/LLM coordinator). For EVERY mesh this daemon hosts/
648
+ // coordinates, pull each remote worker node's pending-events queue over P2P
649
+ // into THIS daemon's local queue. This runs *regardless of whether a live CLI
650
+ // coordinator exists* — the coordinator is usually a pure stdio MCP LLM with
651
+ // no live CLI session, and it can only observe a remote worker's completion
652
+ // once that event has been pulled into the local queue (which it then drains
653
+ // on its next mesh tool call). Previously this pull was gated behind a live
654
+ // CLI coordinator and so never ran for MCP/LLM coordinators — remote
655
+ // completions sat on the remote node's queue until the LLM happened to call
656
+ // mesh_read_chat, which triggered the MCP-side pull. The daemon now does it
657
+ // autonomously on the timer. Standalone (no dispatchMeshCommand) skips this
658
+ // phase entirely — there are no remote nodes to pull from.
659
+ //
660
+ // PHASE 2 — Live CLI inject. For each mesh that has a live CLI coordinator on
661
+ // THIS daemon, drain the local queue and inject pending events into the PTY.
662
+ // Unchanged from before.
663
+ // Bug B: how long a row may sit 'assigned' with an unconfirmed dispatch before the
664
+ // watchdog reclaims it. Must be comfortably larger than the per-dispatch confirm
665
+ // timeout (DISPATCH_CONFIRM_TIMEOUT_MS in mesh-events-coordinator) so a slow-but-live
666
+ // dispatch still inside its normal confirm window is never reclaimed early — this is
667
+ // the durable backstop for the case the in-process confirm timer can't cover (a timer
668
+ // lost to a daemon restart between claim and confirm).
669
+ const ASSIGNED_STRANDED_DEADLINE_MS = 5 * 60_000;
670
+
671
+ // COMPLETION-PROPAGATION F3: how long a row may sit 'assigned' with a CONFIRMED delivery
672
+ // (delivered/acked) but no terminal completion before the watchdog reclaims it as a
673
+ // delivered-but-lost completion. Distinct from — and deliberately larger than —
674
+ // ASSIGNED_STRANDED_DEADLINE_MS: a confirmed-delivered dispatch was genuinely handed to a
675
+ // worker, so the deadline must comfortably exceed any realistic single worker turn (a large
676
+ // generation) before we treat the missing completion as lost and re-open the task. Paired with
677
+ // the non-generating + no-terminal-ledger guards below so a worker still mid-turn is never
678
+ // reclaimed out from under itself.
679
+ const DELIVERED_NO_TURN_DEADLINE_MS = 15 * 60_000;
680
+
681
+ // RECLAIM-FALSEPOS: how many CONSECUTIVE UNKNOWN busy-verdict ticks (past the delivered-no-turn
682
+ // deadline) must accumulate before a delivered row whose worker session cannot be positively
683
+ // observed is reclaimed. An UNKNOWN verdict means the assigned session is not present in THIS
684
+ // daemon's local instance map (remote / gone / id-form skew) — so it may be a REMOTE session that
685
+ // is genuinely mid-turn. Reclaiming it on a single UNKNOWN tick tears a live remote worker off its
686
+ // task and re-launches a near-duplicate (observed live 2026-07-04, session 21e34616 / task
687
+ // a26806c1). We therefore DEFER on UNKNOWN and only reclaim after this bounded grace, so a
688
+ // transient/remote absence never triggers a false reclaim while a genuinely-lost completion is
689
+ // still eventually recovered. A GENERATING or IDLE_CONFIRMED verdict (locally-present positive
690
+ // evidence) resets/bypasses the grace — see recoverStrandedAssignedDispatches.
691
+ const RECLAIM_UNKNOWN_GRACE_TICKS = 3;
692
+
693
+ // Per-row consecutive-UNKNOWN streak for delivered-no-turn reclaim, keyed `${meshId}::${taskId}`.
694
+ // In-memory (per process); pruned each pass to the set of currently-assigned rows so a
695
+ // completed/reclaimed/claimed-elsewhere row's counter is dropped (no unbounded growth).
696
+ const deliveredNoTurnUnknownStreak = new Map<string, number>();
697
+
698
+ // Test hook: clear the delivered-no-turn UNKNOWN streak between cases.
699
+ export function __resetReclaimUnknownStreakForTests(): void {
700
+ deliveredNoTurnUnknownStreak.clear();
701
+ }
702
+
703
+ // PHASE 2.5 — assigned-stranded dispatch watchdog (Bug B). claimNextTask atomically
704
+ // flips a row to 'assigned' BEFORE the fire-and-forget dispatch runs. If that dispatch
705
+ // neither rejects (→ no .catch requeue) nor is confirmed delivered — a relay that hangs
706
+ // without acking, or a confirm timer lost across a restart — the row stays 'assigned'
707
+ // forever: it contributes 0 pending, so PHASE 3 (gated on pendingQueueTaskCount>0) never
708
+ // re-examines it, and nothing but a manual requeue clears it. This is that missing net.
709
+ //
710
+ // Regression guard: a row whose delivery IS confirmed (delivered/acked/completed) is a
711
+ // genuinely in-flight (or completion-lost) task — left to PHASE 4's completion reconcile,
712
+ // never reclaimed here. And the deadline is generous so a slow-but-live dispatch still in
713
+ // its normal confirm window is never reclaimed early. Reclaimed rows return to 'pending'
714
+ // with ownership cleared, so the PHASE 3 trigger below re-dispatches them this same tick.
715
+ function recoverStrandedAssignedDispatches(components: DaemonComponents, meshId: string, store: MeshRuntimeStore): void {
716
+ const assigned = getQueue(meshId, { status: ['assigned'] });
717
+ if (!assigned.length) return;
718
+ const nowMs = Date.now();
719
+ // RECLAIM-FALSEPOS: prune UNKNOWN streaks for rows of THIS mesh that are no longer
720
+ // 'assigned' (completed / reclaimed / claimed elsewhere) so the counter map cannot grow
721
+ // unbounded and a re-used task id starts its grace fresh.
722
+ const assignedKeys = new Set(assigned.map(r => `${meshId}::${r.id}`));
723
+ const meshKeyPrefix = `${meshId}::`;
724
+ for (const key of [...deliveredNoTurnUnknownStreak.keys()]) {
725
+ if (key.startsWith(meshKeyPrefix) && !assignedKeys.has(key)) deliveredNoTurnUnknownStreak.delete(key);
726
+ }
727
+ for (const row of assigned) {
728
+ const dispatchedAtMs = Date.parse(row.dispatchTimestamp ?? '');
729
+ if (!Number.isFinite(dispatchedAtMs)) continue; // no dispatch ts → can't age it
730
+ if (nowMs - dispatchedAtMs < ASSIGNED_STRANDED_DEADLINE_MS) continue; // still in confirm window
731
+ const terminal = findTerminalLedgerEvidenceForTask({
732
+ meshId,
733
+ taskId: row.id,
734
+ });
735
+ if (terminal) {
736
+ const status = terminal.kind === 'task_completed' ? 'completed' : 'failed';
737
+ updateTaskStatus(meshId, row.id, status);
738
+ LOG.warn('MeshReconcile', `Skipped stranded reclaim redispatch for terminal task ${row.id} on mesh ${meshId}; ${terminal.kind} ledger evidence already exists`);
739
+ traceMeshEventDrop('assigned_stranded_terminal_ledger', {
740
+ taskId: row.id,
741
+ sessionId: row.assignedSessionId,
742
+ nodeId: row.assignedNodeId,
743
+ meshId,
744
+ event: 'agent:generating_completed',
745
+ }, terminal.kind);
746
+ continue;
747
+ }
748
+ if (store.taskHasConfirmedDelivery(meshId, row.id)) {
749
+ // COMPLETION-PROPAGATION F3 (delivered-but-lost completion): the dispatch WAS
750
+ // confirmed handed to a worker (delivered/acked) but no terminal completion ever
751
+ // landed and none is in the ledger (checked just above). Normally this is PHASE 4's
752
+ // job, but PHASE 4 only covers direct-dispatch rows / a live re-read; a claim-path
753
+ // queue row whose completion event was lost (the manual-launch flip-miss signature)
754
+ // sits 'assigned' forever.
755
+ //
756
+ // RECLAIM-FALSEPOS tri-state verdict: the reclaim used to gate ONLY on
757
+ // isSessionActivelyGenerating(), whose local instance lookup returns "not generating"
758
+ // for a REMOTE (or id-form-skewed) session that is genuinely mid-turn — so such a
759
+ // worker was reclaimed at the deadline and re-launched same tick (near-duplicate
760
+ // execution; observed live 2026-07-04, session 21e34616 / task a26806c1). Resolve an
761
+ // explicit GENERATING / IDLE_CONFIRMED / UNKNOWN verdict instead:
762
+ // - GENERATING → worker demonstrably alive; never reclaim, reset grace.
763
+ // - IDLE_CONFIRMED → positive LOCAL evidence (present instance, inactive) → reclaim
764
+ // now (past deadline) with the delivered-no-turn reason.
765
+ // - UNKNOWN → session not locally observable (remote / gone / id-skew). Do
766
+ // NOT fold into a definitive idle. DEFER: count consecutive
767
+ // UNKNOWN ticks and only reclaim after RECLAIM_UNKNOWN_GRACE_TICKS
768
+ // so a live remote worker is never torn off its task on a single
769
+ // absent observation; a genuinely-lost completion is still
770
+ // recovered after the bounded grace.
771
+ // reclaimStrandedAssignedTask ends the single-flight window (F4), so a subsequent
772
+ // re-dispatch/requeue is unblocked.
773
+ if (nowMs - dispatchedAtMs < DELIVERED_NO_TURN_DEADLINE_MS) continue; // still within turn budget
774
+ const streakKey = `${meshId}::${row.id}`;
775
+ const verdict = row.assignedSessionId
776
+ ? resolveSessionBusyVerdict(components, row.assignedSessionId)
777
+ : 'IDLE_CONFIRMED'; // no session bound → nothing live to protect
778
+ if (verdict === 'GENERATING') {
779
+ deliveredNoTurnUnknownStreak.delete(streakKey); // demonstrably alive → reset grace
780
+ continue; // worker still working
781
+ }
782
+ let reclaimReason: 'delivered_no_turn_deadline' | 'reclaim_after_unknown_grace';
783
+ if (verdict === 'IDLE_CONFIRMED') {
784
+ deliveredNoTurnUnknownStreak.delete(streakKey);
785
+ reclaimReason = 'delivered_no_turn_deadline';
786
+ } else {
787
+ // UNKNOWN — defer and accumulate the consecutive-UNKNOWN streak.
788
+ const streak = (deliveredNoTurnUnknownStreak.get(streakKey) ?? 0) + 1;
789
+ deliveredNoTurnUnknownStreak.set(streakKey, streak);
790
+ if (streak < RECLAIM_UNKNOWN_GRACE_TICKS) {
791
+ // Still within grace — hold this tick. Content-free trace (ids + streak only).
792
+ traceMeshEventDrop('reclaim_deferred_unknown_verdict', {
793
+ taskId: row.id,
794
+ sessionId: row.assignedSessionId,
795
+ nodeId: row.assignedNodeId,
796
+ meshId,
797
+ event: 'agent:generating_completed',
798
+ }, `unknown ${streak}/${RECLAIM_UNKNOWN_GRACE_TICKS}`);
799
+ continue;
800
+ }
801
+ reclaimReason = 'reclaim_after_unknown_grace';
802
+ }
803
+ const reclaimedLost = reclaimStrandedAssignedTask(meshId, row.id, {
804
+ reason: reclaimReason,
805
+ ageMs: nowMs - dispatchedAtMs,
806
+ });
807
+ if (reclaimedLost) {
808
+ deliveredNoTurnUnknownStreak.delete(streakKey);
809
+ LOG.warn('MeshReconcile', `Reclaimed delivered-but-lost task ${row.id} on mesh ${meshId} `
810
+ + `(node=${row.assignedNodeId ?? '?'} session=${row.assignedSessionId ?? '?'}, delivered but no `
811
+ + `completion in ${Math.round((nowMs - dispatchedAtMs) / 1000)}s, verdict ${verdict} → ${reclaimReason} → ${reclaimedLost.status})`);
812
+ traceMeshEventDrop('assigned_stranded_delivered_no_turn', {
813
+ taskId: row.id,
814
+ sessionId: row.assignedSessionId,
815
+ nodeId: row.assignedNodeId,
816
+ meshId,
817
+ event: 'agent:generating_completed',
818
+ }, `delivered ${Math.round((nowMs - dispatchedAtMs) / 1000)}s ${reclaimReason} → ${reclaimedLost.status}`);
819
+ }
820
+ continue;
821
+ }
822
+ const reclaimed = reclaimStrandedAssignedTask(meshId, row.id, {
823
+ reason: 'assigned_stranded_dispatch_unconfirmed',
824
+ ageMs: nowMs - dispatchedAtMs,
825
+ });
826
+ if (reclaimed) {
827
+ LOG.warn('MeshReconcile', `Reclaimed stranded assigned task ${row.id} on mesh ${meshId} `
828
+ + `(node=${row.assignedNodeId ?? '?'} session=${row.assignedSessionId ?? '?'}, dispatched `
829
+ + `${Math.round((nowMs - dispatchedAtMs) / 1000)}s ago, never confirmed delivered → ${reclaimed.status})`);
830
+ // EVTTRACE: the dispatch for this task was stranded (assigned, never confirmed
831
+ // delivered) and reclaimed (CANON-B) — its expected completion event never
832
+ // arrived. Observation only; the reclaim decision above is unchanged.
833
+ traceMeshEventDrop('assigned_stranded_reclaim', {
834
+ taskId: row.id,
835
+ sessionId: row.assignedSessionId,
836
+ nodeId: row.assignedNodeId,
837
+ meshId,
838
+ event: 'agent:generating_completed',
839
+ }, `unconfirmed ${Math.round((nowMs - dispatchedAtMs) / 1000)}s → ${reclaimed.status}`);
840
+ }
841
+ }
842
+ }
843
+
844
+ export async function runMeshReconcileTick(components: DaemonComponents): Promise<void> {
845
+ const localDaemonId = readNonEmptyString(loadConfig().machineId) || undefined;
846
+ // The id-set used to scope the local queue drain (status id + machineId). See
847
+ // resolveCoordinatorDaemonIds — the status id is what the MCP layer stamps and
848
+ // is mandatory here for a generating CLI coordinator to self-receive completions.
849
+ const drainDaemonIds = resolveCoordinatorDaemonIds(components);
850
+ const dispatchMeshCommand = components.dispatchMeshCommand;
851
+ const store = (() => {
852
+ try { return MeshRuntimeStore.getInstance(); } catch { return undefined; }
853
+ })();
854
+
855
+ // ── PHASE 0: retry the worker-side unresolved-delegate forward outbox ──────
856
+ // Cloud-only (needs dispatchMeshCommand). A worker that is NOT a member of the
857
+ // coordinator's mesh cannot be reached by the coordinator's PHASE 1 pull (it is
858
+ // in no mesh.node), so its completion must be PUSHED to the coordinator. This
859
+ // drains the durable outbox enqueued by forwardUnresolvedDelegateEvent and retries
860
+ // any push that has not yet been acked. See mesh-unresolved-forward-outbox.ts.
861
+ if (dispatchMeshCommand) {
862
+ try {
863
+ await retryUnresolvedDelegateForwards(components);
864
+ } catch (e: any) {
865
+ LOG.warn('MeshReconcile', `Unresolved-delegate forward retry failed: ${e?.message || e}`);
866
+ }
867
+ }
868
+
869
+ // ── PHASE 1: pull remote node queues for every mesh this daemon hosts ──────
870
+ // Cloud-only (dispatchMeshCommand present). Runs whether or not a live CLI
871
+ // coordinator exists — this is what lets an MCP/LLM coordinator ever see a
872
+ // remote worker's completion.
873
+ if (dispatchMeshCommand) {
874
+ for (const mesh of listMeshes()) {
875
+ // Expand to every id-form this daemon answers to for this mesh (runtime
876
+ // drain ids ∪ config-form node/host ids) and use it for BOTH the host gate
877
+ // and the remote pull filter, so a worker stamp in any form is recovered.
878
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
879
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
880
+ try {
881
+ await pullRemoteNodeQueues(components, mesh, localDaemonId, selfIds);
882
+ } catch (e: any) {
883
+ LOG.warn('MeshReconcile', `Remote node pull failed for mesh ${mesh.id}: ${e?.message || e}`);
884
+ }
885
+ }
886
+ }
887
+
888
+ // ── PHASE 2.5: assigned-stranded dispatch watchdog (Bug B) ─────────────────
889
+ // Runs before PHASE 3 so any row it returns to 'pending' is re-dispatched by the
890
+ // PHASE 3 trigger in this same tick. See recoverStrandedAssignedDispatches.
891
+ if (store) {
892
+ for (const mesh of listMeshes()) {
893
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
894
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
895
+ try {
896
+ recoverStrandedAssignedDispatches(components, mesh.id, store);
897
+ } catch (e: any) {
898
+ LOG.warn('MeshReconcile', `Assigned-stranded watchdog failed for mesh ${mesh.id}: ${e?.message || e}`);
899
+ }
900
+ }
901
+ }
902
+
903
+ // ── PHASE 3: recover pending queue claims for newly-idle sessions ──────────
904
+ // The event-driven claim paths (agent:ready / agent:generating_completed in
905
+ // mesh-events-coordinator) re-claim the queue the moment a session goes idle,
906
+ // but that depends on a single event being emitted AND (for a remote node)
907
+ // successfully forwarded to this coordinator. If that event is missed/dropped,
908
+ // a pending task targeting a now-idle session would sit unclaimed forever —
909
+ // there was no periodic safety net. This phase is that net: for every mesh this
910
+ // daemon hosts that has at least one pending task, run one triggerMeshQueue so a
911
+ // session that became idle without a delivered ready-event still gets its work.
912
+ //
913
+ // O(1) guard: skip the (relatively expensive) full idle-session + remote-idle
914
+ // scan entirely when the queue has no pending tasks — a COUNT(*) over the
915
+ // indexed status column, so an idle mesh costs one cheap query per tick.
916
+ // claimNextQueueTask is atomic, so racing the event-driven path can only have
917
+ // one winner; double-claiming is impossible.
918
+ for (const mesh of listMeshes()) {
919
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
920
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
921
+ if (store) {
922
+ try {
923
+ if (store.pendingQueueTaskCount(mesh.id) === 0) continue;
924
+ } catch { /* fall through and let triggerMeshQueue decide */ }
925
+ }
926
+ try {
927
+ await triggerMeshQueue(components, mesh.id);
928
+ } catch (e: any) {
929
+ LOG.warn('MeshReconcile', `Pending-claim recovery trigger failed for mesh ${mesh.id}: ${e?.message || e}`);
930
+ }
931
+ }
932
+
933
+ // ── PHASE 4: synthesize lost completions for unterminated direct dispatches ─
934
+ // Symmetric to PHASE 3 (which recovers a *lost claim* for a newly-idle session)
935
+ // but for the opposite gap: a worker that ALREADY completed, went idle, and
936
+ // whose terminal completion event was never persisted (dropped before reaching
937
+ // the queue/outbox, or its forward was lost). PHASE 1/2/3 can only deliver an
938
+ // event that exists in a queue — they cannot recover a completion that was
939
+ // never recorded, so the coordinator keeps believing the worker is generating.
940
+ //
941
+ // reconcileDirectDispatchCompletionFromTranscript already synthesizes the
942
+ // missing terminal event from the worker's transcript, but until now it ran
943
+ // ONLY when an LLM coordinator polled mesh_status (mcp_mesh_status_transcript_
944
+ // reconciliation). This phase pulls that same correction onto the daemon timer
945
+ // so it no longer depends on the LLM polling. The reconcile is idempotent
946
+ // (hasTerminalLedgerAfterDispatch guards against re-synthesis), so attempting it
947
+ // every tick for the same dispatch is safe — once a terminal exists it no-ops.
948
+ for (const mesh of listMeshes()) {
949
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
950
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
951
+ try {
952
+ await reconcileUnterminatedDirectDispatches(components, mesh, selfIds, localDaemonId);
953
+ } catch (e: any) {
954
+ LOG.warn('MeshReconcile', `Completion reconcile failed for mesh ${mesh.id}: ${e?.message || e}`);
955
+ }
956
+ }
957
+
958
+ // ── PHASE 5: auto-prune orphaned direct dispatch records ───────────────────
959
+ // staleDirectWork (orphaned direct-dispatch rows whose node/session is no longer in the
960
+ // live mesh) otherwise accumulates indefinitely: a removed worktree node or a cleanly
961
+ // terminated session leaves its direct-dispatch row behind, stuck in a non-terminal status
962
+ // (e.g. generating) for days. This is NOT a false-idle bug — it is the separate problem of
963
+ // orphaned records that the only existing cleanup path (manual MCP mesh_prune_stale_direct)
964
+ // never reaches unless an operator runs it by hand.
965
+ //
966
+ // This phase runs the SAME prune core the manual tool calls (pruneStaleDirectDispatches),
967
+ // in execute mode, on the daemon timer. The only difference from the manual path is a
968
+ // conservative age gate (DEFAULT_AUTO_PRUNE_MIN_AGE_MS): a freshly-orphaned record is held
969
+ // back until it is provably stale, so a transient probe miss never auto-prunes live work.
970
+ // Every other safety rule is inherited unchanged from the core — active/pending/generating
971
+ // work and fresh unacknowledged dispatch failures are never pruned, ledger-only audit entries
972
+ // are preserved, and the prune itself is recorded with a direct_dispatch_pruned ledger entry.
973
+ // Idempotent: a pruned row is gone from getActiveDirectDispatches, so the next tick finds
974
+ // nothing to re-prune. Isolated in its own try/catch per mesh so it can never kill the tick.
975
+ {
976
+ const minAgeMs = resolveAutoPruneMinAgeMs();
977
+ for (const mesh of listMeshes()) {
978
+ const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
979
+ if (!daemonHostsMesh(mesh, selfIds)) continue;
980
+ try {
981
+ await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
982
+ } catch (e: any) {
983
+ LOG.warn('MeshReconcile', `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
984
+ }
985
+ }
986
+ }
987
+
988
+ // ── PHASE 2: inject into live CLI coordinators on this daemon ──────────────
989
+ const coordinators = findLiveCoordinators(components);
990
+ if (coordinators.length === 0) {
991
+ // No live CLI coordinator on this daemon — nothing to inject into.
992
+ // (MCP-only LLM coordinators drain the local queue via their own tool
993
+ // calls; PHASE 1 above has already populated it from remote nodes.)
994
+ return;
995
+ }
996
+
997
+ // Group coordinators by mesh; multiple coordinator instances for one mesh is
998
+ // unusual but supported (each gets the same drained events).
999
+ const byMesh = new Map<string, LiveCoordinator[]>();
1000
+ for (const c of coordinators) {
1001
+ const list = byMesh.get(c.meshId);
1002
+ if (list) list.push(c);
1003
+ else byMesh.set(c.meshId, [c]);
1004
+ }
1005
+
1006
+ for (const [meshId, meshCoordinators] of byMesh) {
1007
+ // Drain the local queue scoped to this coordinator daemon and inject.
1008
+ // - If an idle coordinator exists, FULL-drain and deliver every event to it
1009
+ // (the idle input box accepts the prompt as a real next turn). The drain
1010
+ // marks consumed rows drained=1 atomically, so the pull path can't re-deliver.
1011
+ // - If only GENERATING coordinators exist (no idle target), we HOLD: leave the
1012
+ // events queued (drained=0) for the coordinator's next idle/turn-end tick.
1013
+ //
1014
+ // NOTIF-SURFACE-LOCAL (false-idle hold): we used to force-inject terminal events
1015
+ // (completion/approval/stop/refine·bootstrap) straight into a *generating*
1016
+ // coordinator's PTY (forceSendMessage → atomic content+\r write), on the theory it
1017
+ // bypassed the busy send-guard and broke the await-result deadlock. But a raw PTY
1018
+ // write into a claude-cli that is mid-generation is NOT consumed as a new turn — the
1019
+ // bytes land in the terminal input buffer and the LLM never reads them on its next
1020
+ // turn. The `surfaced/force-inject` trace fired, the row was marked drained=1, and the
1021
+ // genuine completion was lost forever (the exact same-daemon local-worktree miss: the
1022
+ // coordinator's OWN session is generating at the moment its worker completes). The
1023
+ // deadlock the force path guarded against does not actually require force: a
1024
+ // coordinator that dispatched a task via mesh_send_task returns to idle when that
1025
+ // tool call resolves (dispatch is fire-and-forget; the worker runs for minutes while
1026
+ // the coordinator is idle/between turns), so the completion lands on the very next
1027
+ // idle tick (≤ one reconcile interval). Holding the event undrained for that idle
1028
+ // tick is therefore the single, reliable delivery — and it is the SAME skip-and-hold
1029
+ // the modal-park branch below already uses. This also makes double-injection
1030
+ // structurally impossible: there is exactly one delivery path (the idle full-drain),
1031
+ // so we never need a surface-time fingerprint to dedup a force-write against a re-drain.
1032
+ const idleCoordinators = meshCoordinators.filter(c => c.idle);
1033
+ // A coordinator parked on a harness modal (waiting_choice / waiting_approval) is
1034
+ // non-idle; it is held under the modal-park branch (a force-inject into a modal would
1035
+ // write raw keystrokes the modal key handler eats, silently selecting a choice the
1036
+ // user never made). A plainly-generating coordinator (non-idle, non-modal-parked) is
1037
+ // ALSO held now — for the false-idle reason above — but separately, so the C1 ledger
1038
+ // audit and the operator-facing skip log can name the right hold reason.
1039
+ const generatingCoordinators = meshCoordinators.filter(c => !c.idle && !c.modalParked);
1040
+ const modalParkedCoordinators = meshCoordinators.filter(c => !c.idle && c.modalParked);
1041
+ // Only an IDLE coordinator is a deliverable target. A generating coordinator's PTY
1042
+ // does not consume an injected prompt as a turn, so it is held (not a target).
1043
+ const targetCoordinators = idleCoordinators;
1044
+
1045
+ // ── no-idle-target short-circuit (MUST precede the drain) ─────────────────
1046
+ // When there is no IDLE coordinator for this mesh — only generating and/or
1047
+ // modal-parked ones — there is nowhere a queued event can land as a real turn.
1048
+ // We skip-and-hold: by NOT draining we leave the events at drained=0 in the queue,
1049
+ // so a later tick (once a coordinator returns to idle) delivers them. This
1050
+ // short-circuit MUST run BEFORE drainPendingMeshCoordinatorEvents — the drain marks
1051
+ // rows drained=1 atomically, which would lose the events for a coordinator that is
1052
+ // only transiently busy (the false-idle local-worktree miss). Both the generating
1053
+ // hold and the modal-park hold record a C1 ledger audit copy so a held completion's
1054
+ // worker summary is recoverable even if the coordinator never returns or the pending
1055
+ // file is later trimmed.
1056
+ if (targetCoordinators.length === 0) {
1057
+ // ── APPROVAL-Q1-REALTIME: level-deliver approval nudges BEFORE the hold ──
1058
+ // Approval events are LEVEL-backed (task_approval_needed ledger →
1059
+ // mesh_status awaiting_approval), so they must not be edge-held like a
1060
+ // completion (whose payload lives only in the pending event). Drain and
1061
+ // deliver them to the busy coordinator's inbox (non-force, next-turn-boundary)
1062
+ // this tick, dropping any already-resolved (stale) nudge — and leave ONLY the
1063
+ // completion/other events in the queue for the existing hold semantics below
1064
+ // (their behaviour is unchanged: shouldForceInjectMeshEvent no longer sees the
1065
+ // approval rows because this drained them). MUST run first so the modal-park
1066
+ // orphan-escape and the generating-hold audit only ever see non-approval events.
1067
+ drainAndDeliverApprovalNudges(meshId, drainDaemonIds, localDaemonId, meshCoordinators);
1068
+ // If approval nudges were the only queued events, nothing remains to hold — skip
1069
+ // the hold branches (and their "holding pending event(s)" log) entirely.
1070
+ if (store) {
1071
+ try { if (store.pendingEventCount(meshId) === 0) continue; } catch { /* fall through */ }
1072
+ }
1073
+ if (modalParkedCoordinators.length > 0) {
1074
+ // ── orphan escape (MUST precede the blanket modal-park hold) ──────────
1075
+ // A modal-parked coordinator with no idle/generating sibling otherwise
1076
+ // wedges EVERY pending event under `modal_parked` until that modal resolves
1077
+ // — including a STRICT-routed completion whose originating coordinator
1078
+ // session is GONE (an orphan: the worktree/session that produced it was
1079
+ // removed, or that coordinator session died). Such an event will never be
1080
+ // deliverable to its target session no matter what the modal-parked sibling
1081
+ // does, so holding it under modal_parked is a permanent-held leak (the very
1082
+ // "data restart re-reproduces it" symptom — the gate is reconstructed live
1083
+ // from the still-parked modal, so a restart does not clear it). Route those
1084
+ // orphan events through the strict-route hold/expire path so the bounded
1085
+ // STRICT_SESSION_MATCH_TTL eventually expires them (recoverable, ledgered)
1086
+ // instead of leaving them held forever. A strict event whose target session
1087
+ // IS live but merely modal-parked is left to the blanket hold below (it is
1088
+ // genuinely transiently blocked, not orphaned).
1089
+ const liveSessionIds = new Set(
1090
+ meshCoordinators.map(c => readNonEmptyString(c.sessionId)).filter(Boolean),
1091
+ );
1092
+ let orphanEscaped = 0;
1093
+ const hasPendingForOrphanPeek = !store
1094
+ || (() => { try { return store.pendingEventCount(meshId) > 0; } catch { return true; } })();
1095
+ if (hasPendingForOrphanPeek) {
1096
+ // Identify which pending event NAMES correspond to orphan-targeted events
1097
+ // (a strict targetCoordinatorSessionId that matches no live coordinator).
1098
+ let peeked: readonly PendingMeshCoordinatorEvent[] = [];
1099
+ try {
1100
+ peeked = getPendingMeshCoordinatorEvents(meshId, drainDaemonIds.length > 0 ? drainDaemonIds : undefined);
1101
+ } catch { peeked = []; }
1102
+ const isOrphan = (e: PendingMeshCoordinatorEvent): boolean => {
1103
+ const want = readNonEmptyString(e.targetCoordinatorSessionId);
1104
+ return !!want && !liveSessionIds.has(want);
1105
+ };
1106
+ const orphanEventNames = new Set(peeked.filter(isOrphan).map(e => e.event));
1107
+ if (orphanEventNames.size > 0) {
1108
+ // The drain filter is event-NAME scoped (not per-row), so draining by the
1109
+ // orphan event names also pulls any non-orphan event sharing that name. Drain
1110
+ // them all, then re-route: orphan-targeted events go through the strict-route
1111
+ // hold/expire path (bounded TTL → eventually ledger-expired, recoverable);
1112
+ // non-orphan events of the same name are re-queued unchanged (queuedAt
1113
+ // preserved) so they remain genuinely held for their still-live, modal-parked
1114
+ // target. This is the same per-event strict routing PHASE 2 does below — just
1115
+ // reached here because the blanket modal-park short-circuit would otherwise
1116
+ // wedge the orphans forever.
1117
+ let drained: PendingMeshCoordinatorEvent[] = [];
1118
+ try {
1119
+ drained = drainPendingMeshCoordinatorEvents(
1120
+ meshId,
1121
+ drainDaemonIds.length > 0 ? drainDaemonIds : localDaemonId,
1122
+ { onlyEvents: orphanEventNames },
1123
+ );
1124
+ } catch (e: any) {
1125
+ LOG.warn('MeshReconcile', `Orphan-escape drain failed for mesh ${meshId}: ${e?.message || e}`);
1126
+ drained = [];
1127
+ }
1128
+ for (const pending of drained) {
1129
+ if (isOrphan(pending)) {
1130
+ holdOrExpireStrictUnmatchedEvent(pending, readNonEmptyString(pending.targetCoordinatorSessionId), meshId);
1131
+ orphanEscaped++;
1132
+ } else {
1133
+ // Still-live (modal-parked) target — re-queue unchanged so it is held
1134
+ // for the next modal-resolved tick, exactly like the blanket hold would.
1135
+ try { queuePendingMeshCoordinatorEvent(pending); } catch { /* best-effort re-queue */ }
1136
+ }
1137
+ }
1138
+ }
1139
+ }
1140
+ 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` : ''})`);
1141
+ // NOTIF (B) diagnostic: name the session(s) classified modal-parked so the
1142
+ // same-tick coordDiag line (paired by sessionId) shows whether the modal-park
1143
+ // overlay is a real human-await or an unreleased mask (the getState_overlay origin).
1144
+ if (getLogLevel() === 'debug') {
1145
+ 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)`);
1146
+ }
1147
+ // C1: mirror held terminal events into the ledger so a held completion's
1148
+ // worker summary is auditable/recoverable even if the modal is never
1149
+ // resolved, the coordinator restarts, or the pending file is later trimmed.
1150
+ // The events stay queued (drained=0) for re-drain on a later tick; this only
1151
+ // adds the durable audit copy. Idempotent per process — only newly-held
1152
+ // events are logged. O(1)-gated: skip the peek when the queue is empty.
1153
+ let hasPending = true;
1154
+ if (store) {
1155
+ try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
1156
+ }
1157
+ if (hasPending) {
1158
+ recordHeldTerminalEventsToLedger(
1159
+ meshId,
1160
+ drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
1161
+ 'modal_parked',
1162
+ modalParkedCoordinators.length,
1163
+ );
1164
+ }
1165
+ } else if (generatingCoordinators.length > 0) {
1166
+ // ── generating hold (NOTIF-SURFACE-LOCAL false-idle fix) ─────────────
1167
+ // The only coordinator(s) for this mesh are plainly generating (no idle, no
1168
+ // modal). A raw force-write into a generating claude-cli PTY is not consumed
1169
+ // as a turn, so we do NOT inject and do NOT drain — the events stay queued
1170
+ // (drained=0) and the next tick that finds the coordinator idle full-drains
1171
+ // them as real turns (the coordinator returns to idle when its current
1172
+ // tool-call/turn resolves; a dispatched worker runs for minutes while the
1173
+ // coordinator is idle, so this lands within one reconcile interval). C1: mirror
1174
+ // any held terminal events into the ledger so a completion's worker summary is
1175
+ // recoverable even before that idle tick. Idempotent per process; O(1)-gated.
1176
+ let hasPending = true;
1177
+ if (store) {
1178
+ try { hasPending = store.pendingEventCount(meshId) > 0; } catch { /* peek below */ }
1179
+ }
1180
+ if (hasPending) {
1181
+ // ── PTY-OVERTRUST-DRAIN (Defect B, fix B): age-based escape ───────────
1182
+ // Fix A already routes the common mask-driven false-busy to the idle path,
1183
+ // so reaching here means the coordinator's RAW adapter reads generating.
1184
+ // That is almost always genuine — but a status-source desync fix A does not
1185
+ // reach can momentarily make the raw adapter read generating while the PTY
1186
+ // is actually at a turn end, stranding the completion across many ticks. As a
1187
+ // TIME-BASED BACKSTOP, once the oldest held terminal event has aged past the
1188
+ // escalate threshold, RE-CONFIRM each held coordinator's raw adapter idle and,
1189
+ // if genuinely idle, drain ONCE into it. The re-confirmation gate is what makes
1190
+ // this safe: it NEVER injects into a genuinely-generating PTY (that is the
1191
+ // data-loss force-inject path intentionally removed). A coordinator still
1192
+ // genuinely generating stays held.
1193
+ const escalateMs = resolvePendingHeldDrainEscalateMs();
1194
+ const heldAgeMs = oldestHeldTerminalEventAgeMs(
1195
+ meshId,
1196
+ drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
1197
+ );
1198
+ if (heldAgeMs >= escalateMs) {
1199
+ const escapeTargets = reconfirmGenuinelyIdleCoordinators(generatingCoordinators);
1200
+ if (escapeTargets.length > 0) {
1201
+ LOG.info('MeshReconcile', `Reconcile age-escape → generating-hold: held terminal event(s) for mesh ${meshId} aged ${Math.round(heldAgeMs / 1000)}s (≥ ${Math.round(escalateMs / 1000)}s) and ${escapeTargets.length} coordinator(s) re-confirmed genuinely idle on the raw adapter — draining once`);
1202
+ const drained = drainAndInjectIntoTargets(meshId, drainDaemonIds, localDaemonId, escapeTargets, 'age-escape');
1203
+ if (drained > 0) continue; // delivered → no hold this tick
1204
+ }
1205
+ }
1206
+ 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)`);
1207
+ // NOTIF (B) diagnostic: this is the hold that strands the completion. Name
1208
+ // the sessionId(s) the loop just classified non-idle/non-modal so the
1209
+ // same-tick coordDiag line above (paired by sessionId) reveals which status
1210
+ // source diverged. If a coordDiag for one of these sessions shows getState
1211
+ // (or lastStatus/adapterRaw) === idle, that is the runtime desync origin.
1212
+ if (getLogLevel() === 'debug') {
1213
+ LOG.debug('MeshReconcile', `coordHoldGenerating mesh=${meshId} heldFor=[${generatingCoordinators.map(c => c.sessionId || '?').join(',')}] (these were classified busy; cross-ref same-tick coordDiag by sessionId)`);
1214
+ }
1215
+ recordHeldTerminalEventsToLedger(
1216
+ meshId,
1217
+ drainDaemonIds.length > 0 ? drainDaemonIds : (localDaemonId ? [localDaemonId] : []),
1218
+ 'generating_no_idle_coordinator',
1219
+ generatingCoordinators.length,
1220
+ );
1221
+ }
1222
+ }
1223
+ continue;
1224
+ }
1225
+
1226
+ // O(1) guard: skip the drain entirely when the queue is empty.
1227
+ if (store) {
1228
+ try {
1229
+ if (store.pendingEventCount(meshId) === 0) continue;
1230
+ } catch { /* fall through to drain */ }
1231
+ }
1232
+
1233
+ // An idle coordinator is present (targetCoordinators.length > 0): FULL-drain every
1234
+ // queued event and deliver it to the idle input box as a real turn. The no-idle case
1235
+ // (generating/modal-only) was already held above and never reaches here, so there is
1236
+ // no force-drain-into-generating path left — the single delivery is the idle drain.
1237
+ drainAndInjectIntoTargets(meshId, drainDaemonIds, localDaemonId, targetCoordinators, 'idle');
1238
+ }
1239
+ }
1240
+
1241
+ // Strict-routing TTL: how long a drained completion whose originating coordinator session
1242
+ // is not currently deliverable is held (re-queued for re-drain) before it is ledger-
1243
+ // expired. Bounded so a coordinator session that never returns cannot wedge the event
1244
+ // forever; broad enough to ride out a transient modal-park / brief restart.
1245
+ const STRICT_SESSION_MATCH_TTL_MS = 60_000;
1246
+
1247
+ // Re-queue (hold) a strict-routed event whose coordinator session is not live, or — once it
1248
+ // has aged past STRICT_SESSION_MATCH_TTL_MS — ledger-expire it (recoverable) and drop it.
1249
+ // We deliberately do NOT broadcast an aged-out event to sibling coordinators: that is the
1250
+ // very misroute strict routing exists to prevent. The drain already marked the row drained=1,
1251
+ // so re-queuing re-persists a fresh undrained copy (dedup keys on drained=0 only); queuedAt is
1252
+ // preserved so the TTL measures the event's true age across re-queues.
1253
+ function holdOrExpireStrictUnmatchedEvent(
1254
+ pending: PendingMeshCoordinatorEvent,
1255
+ wantSession: string,
1256
+ meshId: string,
1257
+ ): void {
1258
+ const queuedAt = typeof pending.queuedAt === 'number' ? pending.queuedAt : Date.now();
1259
+ if (Date.now() - queuedAt <= STRICT_SESSION_MATCH_TTL_MS) {
1260
+ try {
1261
+ queuePendingMeshCoordinatorEvent(pending); // preserves queuedAt → true age retained
1262
+ LOG.info('MeshReconcile', `Strict route hold: coordinator session ${wantSession} not live on mesh ${meshId} — re-queued (${pending.event})`);
1263
+ // EVTTRACE: event held (re-queued) — its originating coordinator session is not
1264
+ // currently deliverable. Held, not dropped; surfaces later or expires past TTL.
1265
+ traceMeshEventDrop('strict_route_hold', {
1266
+ taskId: pending.metadataEvent?.taskId,
1267
+ sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
1268
+ nodeId: pending.nodeId,
1269
+ meshId,
1270
+ event: pending.event,
1271
+ }, `coordinatorSession=${wantSession} not live`);
1272
+ } catch (e: any) {
1273
+ LOG.warn('MeshReconcile', `Strict route re-queue failed for ${pending.event} on mesh ${meshId}: ${e?.message || e}`);
1274
+ }
1275
+ return;
1276
+ }
1277
+ const finalSummary = readMeshCompletionSummary(pending.metadataEvent || {});
1278
+ try {
1279
+ appendLedgerEntry(meshId, {
1280
+ kind: 'event_held',
1281
+ ...(pending.nodeId ? { nodeId: pending.nodeId } : {}),
1282
+ payload: {
1283
+ event: pending.event,
1284
+ reason: 'strict_route_expired',
1285
+ recoverable: true,
1286
+ targetCoordinatorSessionId: wantSession,
1287
+ targetCoordinatorDaemonId: pending.targetCoordinatorDaemonId ?? null,
1288
+ nodeLabel: pending.nodeLabel,
1289
+ ...(pending.workspace ? { workspace: pending.workspace } : {}),
1290
+ queuedAt,
1291
+ ...(finalSummary ? { finalSummary } : {}),
1292
+ },
1293
+ });
1294
+ LOG.warn('MeshReconcile', `Strict route expire: coordinator session ${wantSession} never returned for mesh ${meshId} — recorded to ledger (recoverable), dropped (${pending.event})`);
1295
+ // EVTTRACE: event expired past the strict-route TTL — dropped (recoverable, ledgered).
1296
+ traceMeshEventDrop('strict_route_expired', {
1297
+ taskId: pending.metadataEvent?.taskId,
1298
+ sessionId: pending.metadataEvent?.targetSessionId ?? wantSession,
1299
+ nodeId: pending.nodeId,
1300
+ meshId,
1301
+ event: pending.event,
1302
+ }, `coordinatorSession=${wantSession} never returned`);
1303
+ } catch (e: any) {
1304
+ LOG.warn('MeshReconcile', `Failed to ledger-expire strict-unmatched ${pending.event} for mesh ${meshId}: ${e?.message || e}`);
1305
+ }
1306
+ }
1307
+
1308
+ // Cloud-only: retry the worker-side unresolved-delegate forward outbox. For each
1309
+ // durably-queued entry, push it to its coordinator daemon over P2P (mesh_forward_event)
1310
+ // and ack (mark drained) ONLY on a successful, non-rejected response. A failed or
1311
+ // rejected push leaves the entry queued for the next tick — at-least-once delivery.
1312
+ // Stale entries (coordinator unreachable past the max age) are expired first so the
1313
+ // outbox can't grow without bound. The coordinator dedups duplicate deliveries on its
1314
+ // own fingerprint, so a retry that races the original immediate push is harmless.
1315
+ // RECONCILE-MESHID-DROP: per-entry count of consecutive HARD rejections (the coordinator
1316
+ // returned success:false, e.g. "meshId required"). A rejection means the push was delivered
1317
+ // and deterministically refused — retrying the identical payload every 4s can never succeed,
1318
+ // so it would loop until the 30-minute age expiry, spamming the log the whole time. After
1319
+ // MAX_FORWARD_REJECTIONS such rejections we drop the entry (drain it) with ONE fail-loud
1320
+ // warning. Transient transport failures (the dispatch throws — coordinator momentarily
1321
+ // unreachable) do NOT count here; those legitimately retry until the age expiry. In-memory
1322
+ // (keyed by the durable outbox row id) is sufficient: a daemon restart re-arms the loop, and
1323
+ // the age expiry remains the durable backstop. Cleared whenever an entry is delivered/drained.
1324
+ const unresolvedForwardRejectionCounts = new Map<string, number>();
1325
+ const MAX_FORWARD_REJECTIONS = 5;
1326
+
1327
+ export function __resetUnresolvedForwardRejectionCountsForTests(): void {
1328
+ unresolvedForwardRejectionCounts.clear();
1329
+ }
1330
+
1331
+ async function retryUnresolvedDelegateForwards(components: DaemonComponents): Promise<void> {
1332
+ const dispatchMeshCommand = components.dispatchMeshCommand;
1333
+ if (!dispatchMeshCommand) return;
1334
+
1335
+ // Drop entries that have exhausted their retry budget (fail-loud inside).
1336
+ expireStaleUnresolvedDelegateForwards();
1337
+
1338
+ const entries = peekUnresolvedDelegateForwards();
1339
+ if (entries.length === 0) {
1340
+ // Nothing queued — clear any stale per-entry rejection counters so the map can't grow.
1341
+ if (unresolvedForwardRejectionCounts.size > 0) unresolvedForwardRejectionCounts.clear();
1342
+ return;
1343
+ }
1344
+
1345
+ // Every id-form THIS daemon answers to. A self-addressed outbox entry (coordinator
1346
+ // == this daemon) must never be cross-dialled — see the self-route branch below.
1347
+ const selfIds = resolveCoordinatorDaemonIds(components);
1348
+ const isSelfCoordinatorId = (id: string): boolean =>
1349
+ selfIds.some(self => daemonIdsEquivalent(self, id));
1350
+
1351
+ for (const entry of entries) {
1352
+ // EVTTRACE correlation context for this outbox entry's retry.
1353
+ const entryTraceCtx = {
1354
+ taskId: (entry.payload as Record<string, unknown>).taskId,
1355
+ sessionId: readNonEmptyString(entry.payload.targetSessionId) || readNonEmptyString(entry.payload.sessionId),
1356
+ nodeId: readNonEmptyString(entry.payload.nodeId),
1357
+ event: readNonEmptyString(entry.payload.event),
1358
+ };
1359
+
1360
+ // Self-addressed forward: the coordinator daemon this entry targets IS this
1361
+ // daemon (a self-coordinating / single-node mesh, or a delegate whose coordinator
1362
+ // anchor resolved to our own id). A cross-daemon mesh_forward_event to our own id
1363
+ // is REFUSED by the dispatch self-dial guard ("Refusing to send ... to this
1364
+ // daemon's own id; route via the local router instead") on every retry, so the
1365
+ // entry can never be acked and loops forever (~every tick), spamming the log and
1366
+ // pinning the outbox row permanently undrained. Honour the guard's own advice:
1367
+ // route the event straight through the local receiver (handleMeshForwardEvent —
1368
+ // the same path the coordinator runs on receiving a remote push), then ack it.
1369
+ // We drain regardless of the local result: a cross-daemon dispatch could not have
1370
+ // resolved it either (the guard rejects before the receiver ever runs), so leaving
1371
+ // it queued only re-spams. handleMeshForwardEvent has the BEST recovery chance —
1372
+ // this daemon hosts the mesh, so its workspace/nodeId → meshId recovery applies.
1373
+ if (isSelfCoordinatorId(entry.coordinatorDaemonId)) {
1374
+ let localResult: any;
1375
+ try {
1376
+ traceMeshEventStage('forward_send', entryTraceCtx, `self → local router (${entry.coordinatorDaemonId})`);
1377
+ localResult = handleMeshForwardEvent(components, entry.payload);
1378
+ } catch (e: any) {
1379
+ LOG.warn('MeshReconcile', `Local route of self-addressed forward to ${entry.coordinatorDaemonId} threw: ${e?.message || e} — draining anyway to break the retry loop`);
1380
+ }
1381
+ ackUnresolvedDelegateForward(entry.id);
1382
+ unresolvedForwardRejectionCounts.delete(entry.id);
1383
+ if (localResult && localResult.success === false) {
1384
+ 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`);
1385
+ traceMeshEventDrop('self_forward_local_rejected', entryTraceCtx, readNonEmptyString(localResult.error) || 'no reason');
1386
+ } else {
1387
+ LOG.info('MeshReconcile', `Self-addressed unresolved-delegate ${readNonEmptyString(entry.payload.event)} routed via local router (coordinator ${entry.coordinatorDaemonId} is self) — drained`);
1388
+ }
1389
+ continue;
1390
+ }
1391
+
1392
+ // RECONCILE-MESHID-DROP: the stored forward payload was built when the worker
1393
+ // "couldn't resolve" its meshId, so the coordinator rejects it "meshId required"
1394
+ // when its own workspace/nodeId recovery misses. The worker can usually resolve it
1395
+ // now (member node membership / live-session meshNodeFor) — stamp it on so the
1396
+ // coordinator accepts. Covers entries persisted before this fix AND late-bound
1397
+ // sessions. No-op when the payload already carries a meshId or none is resolvable.
1398
+ let pushPayload = entry.payload;
1399
+ if (!readNonEmptyString(pushPayload.meshId)) {
1400
+ const recoveredMeshId = resolveForwardEventMeshId(components, pushPayload);
1401
+ if (recoveredMeshId) {
1402
+ pushPayload = { ...pushPayload, meshId: recoveredMeshId };
1403
+ traceMeshEventStage('forward_meshid_recovered', entryTraceCtx, `meshId=${recoveredMeshId}`);
1404
+ }
1405
+ }
1406
+
1407
+ let result: any;
1408
+ try {
1409
+ traceMeshEventStage('forward_send', entryTraceCtx, `retry → ${entry.coordinatorDaemonId}`);
1410
+ result = await dispatchMeshCommand(entry.coordinatorDaemonId, 'mesh_forward_event', pushPayload);
1411
+ } catch (e: any) {
1412
+ // Coordinator unreachable (transport threw) — keep the entry queued and try again
1413
+ // next tick. This is NOT a hard rejection, so it does not count toward the cap;
1414
+ // the age expiry bounds a permanently-offline coordinator.
1415
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} failed: ${e?.message || e} — left queued`);
1416
+ traceMeshEventDrop('retry_forward_failed', entryTraceCtx, e?.message || String(e));
1417
+ continue;
1418
+ }
1419
+ if (result && result.success === false) {
1420
+ // Hard rejection: the push was delivered and deterministically refused. Retrying
1421
+ // the identical payload can never succeed, so bound it — after MAX_FORWARD_REJECTIONS
1422
+ // drop (drain) the entry with one fail-loud warning instead of re-spamming every tick.
1423
+ const rejections = (unresolvedForwardRejectionCounts.get(entry.id) || 0) + 1;
1424
+ unresolvedForwardRejectionCounts.set(entry.id, rejections);
1425
+ const reason = readNonEmptyString(result.error) || 'no reason';
1426
+ if (rejections >= MAX_FORWARD_REJECTIONS) {
1427
+ ackUnresolvedDelegateForward(entry.id);
1428
+ unresolvedForwardRejectionCounts.delete(entry.id);
1429
+ 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`);
1430
+ traceMeshEventDrop('retry_forward_exhausted', entryTraceCtx, `${reason} (${rejections} rejections)`);
1431
+ } else {
1432
+ LOG.warn('MeshReconcile', `Retry forward to coordinator ${entry.coordinatorDaemonId} rejected (${reason}) — left queued (attempt ${rejections}/${MAX_FORWARD_REJECTIONS})`);
1433
+ traceMeshEventDrop('retry_forward_rejected', entryTraceCtx, reason);
1434
+ }
1435
+ continue;
1436
+ }
1437
+ // Acked — mark the durable copy delivered.
1438
+ ackUnresolvedDelegateForward(entry.id);
1439
+ unresolvedForwardRejectionCounts.delete(entry.id);
1440
+ LOG.info('MeshReconcile', `Retried+delivered unresolved-delegate ${readNonEmptyString(entry.payload.event)} to coordinator ${entry.coordinatorDaemonId}`);
1441
+ }
1442
+ }
1443
+
1444
+ // The remote P2P pull helpers (pullRemoteNodeQueues + payload/envelope utilities)
1445
+ // live in ./mesh-remote-event-pull.ts, and the PHASE-4 completion-synthesis /
1446
+ // PHASE-5 auto-prune (reconcileUnterminatedDirectDispatches,
1447
+ // autoPruneStaleDirectDispatches) live in ./mesh-completion-synthesis.ts
1448
+ // (A-3 extraction). Both are imported at the top of this file.
1449
+ interface ReconcileLoopHandle {
1450
+ stop(): void;
1451
+ }
1452
+
1453
+ // Start the periodic reconcile loop. Returns a handle with stop() for shutdown.
1454
+ export function setupMeshReconcileLoop(components: DaemonComponents): ReconcileLoopHandle {
1455
+ const intervalMs = resolveReconcileIntervalMs();
1456
+ let running = false;
1457
+ const timer = setInterval(() => {
1458
+ if (running) return; // never overlap ticks
1459
+ running = true;
1460
+ void runMeshReconcileTick(components)
1461
+ .catch((e: any) => LOG.warn('MeshReconcile', `Reconcile tick error: ${e?.message || e}`))
1462
+ .finally(() => { running = false; });
1463
+ }, intervalMs);
1464
+ // Don't keep the process alive solely for this timer.
1465
+ if (typeof timer.unref === 'function') timer.unref();
1466
+ LOG.info('MeshReconcile', `Mesh reconcile loop started (interval ${intervalMs}ms)`);
1467
+ return {
1468
+ stop() {
1469
+ clearInterval(timer);
1470
+ LOG.info('MeshReconcile', 'Mesh reconcile loop stopped');
1471
+ },
1472
+ };
1473
+ }