@adhdev/daemon-core 0.9.82-rc.49 → 0.9.82-rc.490

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