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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (473) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +9 -0
  2. package/dist/boot/process-hardening.d.ts +50 -0
  3. package/dist/build-info.d.ts +37 -0
  4. package/dist/chat/source-machine.d.ts +166 -0
  5. package/dist/chat/source-resolver.d.ts +104 -0
  6. package/dist/chat/subscription-updates.d.ts +1 -0
  7. package/dist/cli-adapter-types.d.ts +68 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +220 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +126 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +5 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +74 -0
  14. package/dist/cli-adapters/pty-write-chunking.d.ts +34 -0
  15. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  16. package/dist/cli-adapters/resolve-executable.d.ts +69 -0
  17. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  18. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  19. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  20. package/dist/commands/chat-commands-debug-bundle.d.ts +14 -0
  21. package/dist/commands/chat-commands-read.d.ts +23 -0
  22. package/dist/commands/chat-commands-scope.d.ts +39 -0
  23. package/dist/commands/chat-commands-shared.d.ts +33 -0
  24. package/dist/commands/chat-commands-write.d.ts +14 -0
  25. package/dist/commands/chat-commands.d.ts +10 -23
  26. package/dist/commands/cli-manager.d.ts +51 -1
  27. package/dist/commands/handler.d.ts +125 -0
  28. package/dist/commands/high-family/index.d.ts +3 -0
  29. package/dist/commands/high-family/mesh-coordinator-launch.d.ts +2 -0
  30. package/dist/commands/high-family/mesh-events.d.ts +2 -0
  31. package/dist/commands/high-family/mesh-status.d.ts +2 -0
  32. package/dist/commands/high-family/types.d.ts +64 -0
  33. package/dist/commands/low-family/coordinator-prompt.d.ts +9 -0
  34. package/dist/commands/low-family/daemon-lifecycle.d.ts +2 -0
  35. package/dist/commands/low-family/diagnostics.d.ts +2 -0
  36. package/dist/commands/low-family/index.d.ts +3 -0
  37. package/dist/commands/low-family/mesh-ledger.d.ts +10 -0
  38. package/dist/commands/low-family/mesh-node-logs.d.ts +2 -0
  39. package/dist/commands/low-family/notification.d.ts +2 -0
  40. package/dist/commands/low-family/refine-config.d.ts +2 -0
  41. package/dist/commands/low-family/session-host.d.ts +2 -0
  42. package/dist/commands/low-family/spec-providerdev.d.ts +11 -0
  43. package/dist/commands/low-family/status-meta.d.ts +2 -0
  44. package/dist/commands/low-family/types.d.ts +33 -0
  45. package/dist/commands/med-family/cli-agent.d.ts +2 -0
  46. package/dist/commands/med-family/fast-forward.d.ts +2 -0
  47. package/dist/commands/med-family/ide.d.ts +10 -0
  48. package/dist/commands/med-family/index.d.ts +3 -0
  49. package/dist/commands/med-family/mesh-crud.d.ts +48 -0
  50. package/dist/commands/med-family/mesh-host-pairing.d.ts +2 -0
  51. package/dist/commands/med-family/mesh-queue.d.ts +2 -0
  52. package/dist/commands/med-family/mesh-restart.d.ts +2 -0
  53. package/dist/commands/med-family/types.d.ts +152 -0
  54. package/dist/commands/mesh-coordinator.d.ts +85 -1
  55. package/dist/commands/router-aggregate-status.d.ts +24 -0
  56. package/dist/commands/router-mesh-session-owner.d.ts +59 -0
  57. package/dist/commands/router-refine.d.ts +137 -0
  58. package/dist/commands/router-worktree-cleanup.d.ts +133 -0
  59. package/dist/commands/router.d.ts +204 -15
  60. package/dist/commands/upgrade-helper.d.ts +41 -1
  61. package/dist/config/chat-history.d.ts +11 -0
  62. package/dist/config/config.d.ts +19 -0
  63. package/dist/config/mesh-config.d.ts +136 -1
  64. package/dist/config/mesh-json-config.d.ts +199 -0
  65. package/dist/config/registry-resolver.d.ts +54 -0
  66. package/dist/config/repo-settings.d.ts +77 -0
  67. package/dist/config/state-store.d.ts +30 -0
  68. package/dist/daemon/dev-server.d.ts +0 -2
  69. package/dist/detection/cli-detector.d.ts +17 -0
  70. package/dist/detection/ide-detector.d.ts +13 -0
  71. package/dist/detection/win32-ide-version.d.ts +37 -0
  72. package/dist/git/change-impact-config.d.ts +159 -0
  73. package/dist/git/git-commands.d.ts +26 -2
  74. package/dist/git/git-diff.d.ts +6 -0
  75. package/dist/git/git-executor.d.ts +11 -0
  76. package/dist/git/git-status.d.ts +57 -0
  77. package/dist/git/git-types.d.ts +2 -50
  78. package/dist/git/git-worktree.d.ts +71 -1
  79. package/dist/git/index.d.ts +3 -1
  80. package/dist/index.d.ts +73 -17
  81. package/dist/index.js +52979 -18657
  82. package/dist/index.js.map +1 -1
  83. package/dist/index.mjs +59496 -25355
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/installer.d.ts +1 -4
  86. package/dist/ipc/local-ipc-server.d.ts +91 -0
  87. package/dist/launch.d.ts +1 -1
  88. package/dist/logging/async-batch-writer.d.ts +10 -0
  89. package/dist/logging/debug-config.d.ts +16 -0
  90. package/dist/logging/log-redactor.d.ts +24 -0
  91. package/dist/logging/log-tail-reader.d.ts +81 -0
  92. package/dist/logging/logger.d.ts +1 -1
  93. package/dist/mesh/contracts.d.ts +230 -0
  94. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  95. package/dist/mesh/coordinator-registry.d.ts +59 -0
  96. package/dist/mesh/mesh-active-work.d.ts +203 -0
  97. package/dist/mesh/mesh-clone-grace.d.ts +8 -0
  98. package/dist/mesh/mesh-completion-synthesis.d.ts +4 -0
  99. package/dist/mesh/mesh-coordinator-config.d.ts +21 -0
  100. package/dist/mesh/mesh-delivery-policy.d.ts +104 -0
  101. package/dist/mesh/mesh-event-classify.d.ts +7 -0
  102. package/dist/mesh/mesh-event-forwarding.d.ts +49 -0
  103. package/dist/mesh/mesh-event-trace.d.ts +21 -0
  104. package/dist/mesh/mesh-events-coordinator.d.ts +4 -0
  105. package/dist/mesh/mesh-events-pending.d.ts +246 -0
  106. package/dist/mesh/mesh-events-stale.d.ts +61 -0
  107. package/dist/mesh/mesh-events-utils.d.ts +75 -0
  108. package/dist/mesh/mesh-events.d.ts +6 -49
  109. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  110. package/dist/mesh/mesh-host-ownership.d.ts +29 -0
  111. package/dist/mesh/mesh-init.d.ts +128 -0
  112. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -4
  113. package/dist/mesh/mesh-ledger.d.ts +139 -1
  114. package/dist/mesh/mesh-magi-status.d.ts +63 -0
  115. package/dist/mesh/mesh-missions.d.ts +281 -0
  116. package/dist/mesh/mesh-node-identity.d.ts +310 -0
  117. package/dist/mesh/mesh-queue-assignment.d.ts +158 -0
  118. package/dist/mesh/mesh-reconcile-acked-hold.d.ts +17 -0
  119. package/dist/mesh/mesh-reconcile-config.d.ts +6 -0
  120. package/dist/mesh/mesh-reconcile-identity.d.ts +6 -0
  121. package/dist/mesh/mesh-reconcile-loop.d.ts +80 -0
  122. package/dist/mesh/mesh-reconcile-v2-backstop.d.ts +16 -0
  123. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  124. package/dist/mesh/mesh-refine-gates.d.ts +428 -0
  125. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  126. package/dist/mesh/mesh-remote-event-pull.d.ts +15 -0
  127. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  128. package/dist/mesh/mesh-routing.d.ts +70 -0
  129. package/dist/mesh/mesh-runtime-store.d.ts +508 -0
  130. package/dist/mesh/mesh-scheduling-runtime.d.ts +78 -0
  131. package/dist/mesh/mesh-task-inflight.d.ts +46 -0
  132. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  133. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  134. package/dist/mesh/mesh-warmup-deadline.d.ts +68 -0
  135. package/dist/mesh/mesh-work-queue.d.ts +363 -5
  136. package/dist/mesh/preview-freshness.d.ts +28 -0
  137. package/dist/mesh/refine-config.d.ts +216 -0
  138. package/dist/mesh/worktree-bootstrap-config.d.ts +219 -0
  139. package/dist/providers/acp-provider-instance.d.ts +5 -0
  140. package/dist/providers/approval-utils.d.ts +46 -0
  141. package/dist/providers/chat-message-normalization.d.ts +58 -1
  142. package/dist/providers/cli-provider-effect-format.d.ts +30 -0
  143. package/dist/providers/cli-provider-history-dedup.d.ts +17 -0
  144. package/dist/providers/cli-provider-input-prompt.d.ts +12 -0
  145. package/dist/providers/cli-provider-instance-types.d.ts +45 -0
  146. package/dist/providers/cli-provider-instance.d.ts +406 -30
  147. package/dist/providers/cli-provider-status-helpers.d.ts +46 -0
  148. package/dist/providers/cli-provider-transcript-merge.d.ts +7 -0
  149. package/dist/providers/contracts.d.ts +149 -6
  150. package/dist/providers/external-sources.d.ts +71 -0
  151. package/dist/providers/manual-attendance.d.ts +79 -0
  152. package/dist/providers/native-history/antigravity-claim-registry.d.ts +39 -0
  153. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +137 -0
  154. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  155. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  156. package/dist/providers/native-history/constants.d.ts +12 -0
  157. package/dist/providers/native-history/dispatcher.d.ts +44 -0
  158. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  159. package/dist/providers/native-history/index.d.ts +13 -0
  160. package/dist/providers/provider-instance-manager.d.ts +29 -0
  161. package/dist/providers/provider-instance.d.ts +30 -1
  162. package/dist/providers/provider-loader.d.ts +42 -5
  163. package/dist/providers/provider-trust.d.ts +31 -0
  164. package/dist/providers/read-chat-contract.d.ts +29 -0
  165. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  166. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +86 -0
  167. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  168. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  169. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  170. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  171. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  172. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  173. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  174. package/dist/providers/sdk/v1/index.d.ts +30 -0
  175. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  176. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  177. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  178. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  179. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  180. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  181. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  182. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  183. package/dist/providers/spec/adapter.d.ts +98 -0
  184. package/dist/providers/spec/cli-adapter.d.ts +223 -0
  185. package/dist/providers/spec/evaluator.d.ts +45 -0
  186. package/dist/providers/spec/fsm-driver.d.ts +449 -0
  187. package/dist/providers/spec/fsm-evaluator.d.ts +93 -0
  188. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  189. package/dist/providers/spec/fsm-types.d.ts +202 -0
  190. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  191. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  192. package/dist/providers/spec/route.d.ts +4 -0
  193. package/dist/providers/spec/types.d.ts +244 -0
  194. package/dist/providers/status-monitor.d.ts +7 -7
  195. package/dist/providers/transcript-v2.d.ts +176 -0
  196. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  197. package/dist/providers/working-dir.d.ts +17 -0
  198. package/dist/repo-mesh-types.d.ts +629 -12
  199. package/dist/runtime-defaults.d.ts +2 -0
  200. package/dist/session-host/managed-host.d.ts +64 -0
  201. package/dist/session-host/runtime-surface.d.ts +10 -16
  202. package/dist/sessions/registry.d.ts +26 -0
  203. package/dist/shared-types-extra.d.ts +2 -4
  204. package/dist/shared-types.d.ts +98 -55
  205. package/dist/status/chat-tail-hot-sessions.d.ts +40 -0
  206. package/dist/status/normalize.d.ts +1 -1
  207. package/dist/status/normalize.js +1 -0
  208. package/dist/status/normalize.js.map +1 -1
  209. package/dist/status/normalize.mjs +1 -0
  210. package/dist/status/normalize.mjs.map +1 -1
  211. package/dist/status/reporter.d.ts +2 -0
  212. package/dist/status/snapshot.d.ts +26 -0
  213. package/dist/system/hash.d.ts +8 -0
  214. package/dist/system/load-better-sqlite3.d.ts +21 -0
  215. package/dist/types.d.ts +5 -0
  216. package/package.json +11 -4
  217. package/src/agent-stream/poller.ts +2 -3
  218. package/src/agent-stream/provider-adapter.ts +1 -1
  219. package/src/boot/daemon-lifecycle.ts +80 -14
  220. package/src/boot/process-hardening.ts +89 -0
  221. package/src/build-info.ts +73 -0
  222. package/src/chat/source-machine.ts +534 -0
  223. package/src/chat/source-resolver.ts +0 -0
  224. package/src/chat/subscription-updates.ts +20 -1
  225. package/src/cli-adapter-types.d.ts +3 -1
  226. package/src/cli-adapter-types.ts +68 -2
  227. package/src/cli-adapters/cli-script-runner.ts +421 -0
  228. package/src/cli-adapters/cli-state-engine.ts +1282 -0
  229. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  230. package/src/cli-adapters/provider-cli-adapter.ts +954 -1144
  231. package/src/cli-adapters/provider-cli-parse.d.ts +2 -0
  232. package/src/cli-adapters/provider-cli-parse.ts +19 -0
  233. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  234. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  235. package/src/cli-adapters/provider-cli-shared.ts +121 -11
  236. package/src/cli-adapters/pty-transport.ts +2 -1
  237. package/src/cli-adapters/pty-write-chunking.ts +106 -0
  238. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  239. package/src/cli-adapters/resolve-executable.ts +204 -0
  240. package/src/cli-adapters/session-host-transport.ts +2 -1
  241. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +63 -29
  242. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  243. package/src/cli-adapters/terminal-screen.ts +16 -81
  244. package/src/commands/chat-commands-debug-bundle.ts +398 -0
  245. package/src/commands/chat-commands-read.ts +2767 -0
  246. package/src/commands/chat-commands-scope.ts +54 -0
  247. package/src/commands/chat-commands-shared.ts +114 -0
  248. package/src/commands/chat-commands-write.ts +891 -0
  249. package/src/commands/chat-commands.ts +19 -1841
  250. package/src/commands/cli-manager.d.ts +2 -0
  251. package/src/commands/cli-manager.ts +659 -27
  252. package/src/commands/handler.ts +845 -2
  253. package/src/commands/high-family/index.ts +28 -0
  254. package/src/commands/high-family/mesh-coordinator-launch.ts +680 -0
  255. package/src/commands/high-family/mesh-events.ts +102 -0
  256. package/src/commands/high-family/mesh-status.ts +849 -0
  257. package/src/commands/high-family/types.ts +80 -0
  258. package/src/commands/low-family/coordinator-prompt.ts +72 -0
  259. package/src/commands/low-family/daemon-lifecycle.ts +120 -0
  260. package/src/commands/low-family/diagnostics.ts +57 -0
  261. package/src/commands/low-family/index.ts +37 -0
  262. package/src/commands/low-family/mesh-ledger.ts +62 -0
  263. package/src/commands/low-family/mesh-node-logs.ts +87 -0
  264. package/src/commands/low-family/notification.ts +116 -0
  265. package/src/commands/low-family/refine-config.ts +106 -0
  266. package/src/commands/low-family/session-host.ts +282 -0
  267. package/src/commands/low-family/spec-providerdev.ts +217 -0
  268. package/src/commands/low-family/status-meta.ts +112 -0
  269. package/src/commands/low-family/types.ts +39 -0
  270. package/src/commands/med-family/cli-agent.ts +241 -0
  271. package/src/commands/med-family/fast-forward.ts +230 -0
  272. package/src/commands/med-family/ide.ts +163 -0
  273. package/src/commands/med-family/index.ts +37 -0
  274. package/src/commands/med-family/mesh-crud.ts +1287 -0
  275. package/src/commands/med-family/mesh-host-pairing.ts +234 -0
  276. package/src/commands/med-family/mesh-queue.ts +167 -0
  277. package/src/commands/med-family/mesh-restart.ts +92 -0
  278. package/src/commands/med-family/types.ts +153 -0
  279. package/src/commands/mesh-coordinator.ts +334 -124
  280. package/src/commands/router-aggregate-status.ts +209 -0
  281. package/src/commands/router-mesh-session-owner.ts +114 -0
  282. package/src/commands/router-refine.ts +1711 -0
  283. package/src/commands/router-worktree-cleanup.ts +870 -0
  284. package/src/commands/router.ts +795 -4143
  285. package/src/commands/stream-commands.ts +8 -0
  286. package/src/commands/upgrade-helper.ts +310 -45
  287. package/src/config/chat-history.ts +517 -24
  288. package/src/config/config.ts +30 -0
  289. package/src/config/mesh-config.ts +632 -23
  290. package/src/config/mesh-json-config.ts +376 -0
  291. package/src/config/recent-activity.ts +8 -2
  292. package/src/config/registry-resolver.ts +100 -0
  293. package/src/config/repo-settings.ts +111 -0
  294. package/src/config/state-store.ts +55 -0
  295. package/src/daemon/dev-auto-implement.ts +3 -2
  296. package/src/daemon/dev-cli-debug.ts +10 -1
  297. package/src/daemon/dev-server.ts +0 -541
  298. package/src/detection/cli-detector.ts +94 -9
  299. package/src/detection/ide-detector.ts +55 -16
  300. package/src/detection/win32-ide-version.ts +106 -0
  301. package/src/git/change-impact-config.ts +354 -0
  302. package/src/git/git-commands.ts +112 -16
  303. package/src/git/git-diff.ts +81 -11
  304. package/src/git/git-executor.ts +12 -0
  305. package/src/git/git-status.ts +767 -48
  306. package/src/git/git-types.ts +14 -62
  307. package/src/git/git-worktree.ts +261 -4
  308. package/src/git/index.ts +17 -0
  309. package/src/index.ts +213 -13
  310. package/src/installer.d.ts +1 -1
  311. package/src/installer.ts +8 -6
  312. package/src/ipc/local-ipc-server.ts +278 -0
  313. package/src/launch.d.ts +1 -1
  314. package/src/launch.ts +37 -28
  315. package/src/logging/async-batch-writer.ts +55 -0
  316. package/src/logging/command-log.ts +7 -5
  317. package/src/logging/debug-config.ts +25 -0
  318. package/src/logging/debug-trace.ts +7 -2
  319. package/src/logging/log-redactor.ts +100 -0
  320. package/src/logging/log-tail-reader.ts +341 -0
  321. package/src/logging/logger.ts +14 -7
  322. package/src/mesh/contracts.ts +469 -0
  323. package/src/mesh/coordinator-prompt.ts +572 -34
  324. package/src/mesh/coordinator-registry.ts +121 -0
  325. package/src/mesh/mesh-active-work.ts +706 -0
  326. package/src/mesh/mesh-clone-grace.ts +68 -0
  327. package/src/mesh/mesh-completion-synthesis.ts +416 -0
  328. package/src/mesh/mesh-coordinator-config.ts +97 -0
  329. package/src/mesh/mesh-delivery-policy.ts +284 -0
  330. package/src/mesh/mesh-event-classify.ts +78 -0
  331. package/src/mesh/mesh-event-forwarding.ts +2002 -0
  332. package/src/mesh/mesh-event-trace.ts +67 -0
  333. package/src/mesh/mesh-events-coordinator.ts +32 -0
  334. package/src/mesh/mesh-events-pending.ts +1494 -0
  335. package/src/mesh/mesh-events-stale.ts +452 -0
  336. package/src/mesh/mesh-events-utils.ts +443 -0
  337. package/src/mesh/mesh-events.ts +43 -1035
  338. package/src/mesh/mesh-fast-forward.ts +856 -0
  339. package/src/mesh/mesh-host-ownership.ts +111 -0
  340. package/src/mesh/mesh-init.ts +350 -0
  341. package/src/mesh/mesh-ledger-reconciliation.ts +12 -7
  342. package/src/mesh/mesh-ledger.ts +898 -102
  343. package/src/mesh/mesh-magi-status.ts +223 -0
  344. package/src/mesh/mesh-missions.ts +695 -0
  345. package/src/mesh/mesh-node-identity.ts +2065 -0
  346. package/src/mesh/mesh-queue-assignment.ts +2263 -0
  347. package/src/mesh/mesh-reconcile-acked-hold.ts +230 -0
  348. package/src/mesh/mesh-reconcile-config.ts +66 -0
  349. package/src/mesh/mesh-reconcile-identity.ts +103 -0
  350. package/src/mesh/mesh-reconcile-loop.ts +1473 -0
  351. package/src/mesh/mesh-reconcile-v2-backstop.ts +62 -0
  352. package/src/mesh/mesh-refine-batch.ts +205 -0
  353. package/src/mesh/mesh-refine-gates.ts +1686 -0
  354. package/src/mesh/mesh-refine-status.ts +231 -0
  355. package/src/mesh/mesh-remote-event-pull.ts +279 -0
  356. package/src/mesh/mesh-review-inbox.ts +308 -0
  357. package/src/mesh/mesh-routing.ts +291 -0
  358. package/src/mesh/mesh-runtime-store.ts +2150 -0
  359. package/src/mesh/mesh-scheduling-runtime.ts +198 -0
  360. package/src/mesh/mesh-task-inflight.ts +70 -0
  361. package/src/mesh/mesh-task-stats.ts +161 -0
  362. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  363. package/src/mesh/mesh-warmup-deadline.ts +152 -0
  364. package/src/mesh/mesh-work-queue.ts +1437 -147
  365. package/src/mesh/preview-freshness.ts +163 -0
  366. package/src/mesh/refine-config.ts +423 -0
  367. package/src/mesh/worktree-bootstrap-config.ts +599 -0
  368. package/src/providers/acp-provider-instance.ts +43 -10
  369. package/src/providers/approval-utils.d.ts +5 -0
  370. package/src/providers/approval-utils.ts +100 -6
  371. package/src/providers/chat-message-normalization.ts +126 -4
  372. package/src/providers/cli-provider-effect-format.ts +53 -0
  373. package/src/providers/cli-provider-history-dedup.ts +75 -0
  374. package/src/providers/cli-provider-input-prompt.ts +133 -0
  375. package/src/providers/cli-provider-instance-types.ts +131 -0
  376. package/src/providers/cli-provider-instance.ts +2709 -499
  377. package/src/providers/cli-provider-status-helpers.ts +123 -0
  378. package/src/providers/cli-provider-transcript-merge.ts +114 -0
  379. package/src/providers/contracts.d.ts +55 -0
  380. package/src/providers/contracts.ts +160 -6
  381. package/src/providers/extension-provider-instance.ts +12 -7
  382. package/src/providers/external-sources.ts +218 -0
  383. package/src/providers/ide-provider-instance.ts +35 -12
  384. package/src/providers/manual-attendance.ts +105 -0
  385. package/src/providers/native-history/antigravity-claim-registry.ts +138 -0
  386. package/src/providers/native-history/antigravity-cli-transcript.ts +1275 -0
  387. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  388. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  389. package/src/providers/native-history/constants.ts +19 -0
  390. package/src/providers/native-history/dispatcher.ts +617 -0
  391. package/src/providers/native-history/hermes-cli-transcript.ts +312 -0
  392. package/src/providers/native-history/index.ts +30 -0
  393. package/src/providers/provider-instance-manager.ts +71 -0
  394. package/src/providers/provider-instance.ts +24 -1
  395. package/src/providers/provider-loader.ts +700 -55
  396. package/src/providers/provider-schema.ts +87 -14
  397. package/src/providers/provider-trust.ts +114 -0
  398. package/src/providers/read-chat-contract.ts +76 -16
  399. package/src/providers/sdk/README.md +49 -0
  400. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  401. package/src/providers/sdk/v1/builders/cli/detect-status.ts +313 -0
  402. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  403. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +261 -0
  404. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  405. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  406. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  407. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  408. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  409. package/src/providers/sdk/v1/index.ts +152 -0
  410. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  411. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  412. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  413. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +509 -0
  414. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  415. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  416. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  417. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  418. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  419. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  420. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  421. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  422. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  423. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  424. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  425. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  426. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  427. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  428. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  429. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  430. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  431. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  432. package/src/providers/sdk/v1/validators/index.ts +19 -0
  433. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  434. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  435. package/src/providers/spec/adapter.ts +246 -0
  436. package/src/providers/spec/cli-adapter.ts +1064 -0
  437. package/src/providers/spec/evaluator.ts +407 -0
  438. package/src/providers/spec/fsm-driver.ts +1528 -0
  439. package/src/providers/spec/fsm-evaluator.ts +290 -0
  440. package/src/providers/spec/fsm-loader.ts +128 -0
  441. package/src/providers/spec/fsm-types.ts +301 -0
  442. package/src/providers/spec/native-history-executor.ts +1241 -0
  443. package/src/providers/spec/pre-launch-trust.ts +104 -0
  444. package/src/providers/spec/route.ts +51 -0
  445. package/src/providers/spec/types.ts +284 -0
  446. package/src/providers/status-monitor.d.ts +7 -7
  447. package/src/providers/status-monitor.ts +37 -22
  448. package/src/providers/transcript-v2.ts +567 -0
  449. package/src/providers/types/interactive-prompt.ts +536 -0
  450. package/src/providers/version-archive.ts +64 -24
  451. package/src/providers/working-dir.ts +23 -0
  452. package/src/repo-mesh-types.ts +868 -13
  453. package/src/runtime-defaults.ts +39 -0
  454. package/src/session-host/managed-host.ts +218 -0
  455. package/src/session-host/runtime-surface.ts +20 -80
  456. package/src/sessions/registry.ts +44 -0
  457. package/src/shared-types-extra.ts +2 -4
  458. package/src/shared-types.d.ts +8 -0
  459. package/src/shared-types.ts +136 -55
  460. package/src/status/builders.ts +26 -6
  461. package/src/status/chat-tail-hot-sessions.ts +117 -2
  462. package/src/status/normalize.ts +2 -0
  463. package/src/status/reporter.ts +19 -1
  464. package/src/status/snapshot.ts +95 -26
  465. package/src/system/hash.ts +23 -0
  466. package/src/system/host-memory.ts +29 -12
  467. package/src/system/load-better-sqlite3.ts +68 -0
  468. package/src/types.ts +5 -0
  469. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  470. package/dist/mesh/mesh-sync.d.ts +0 -53
  471. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  472. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  473. package/src/mesh/mesh-sync.ts +0 -111
@@ -0,0 +1,1494 @@
1
+ import { appendFileSync, existsSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { randomUUID } from 'crypto';
4
+ import { LOG } from '../logging/logger.js';
5
+ import { loadConfig } from '../config/config.js';
6
+ import { getLedgerDir, readLedgerEntries, appendLedgerEntry } from './mesh-ledger.js';
7
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
8
+ import { buildMeshSystemMessage, readNonEmptyString, readRecord, resolveEventSessionId, readMeshCompletionSummary, isWeakCompletionMetadata } from './mesh-events-utils.js';
9
+ import { daemonIdsEquivalent, expandDaemonIdForms } from '@adhdev/mesh-shared';
10
+ import {
11
+ assertPendingMeshCoordinatorEventV2,
12
+ buildPendingEventEmitStamp,
13
+ coordinatorIdentityEquals,
14
+ coordinatorIdentityFromEmitFields,
15
+ coordinatorIdentityKey,
16
+ isMeshEventScope,
17
+ MESH_PROTOCOL_VERSION_V2,
18
+ shouldDeliverPendingEventToCoordinator,
19
+ type CoordinatorIdentity,
20
+ type MeshEventScope,
21
+ type PendingMeshCoordinatorEventV2,
22
+ } from './contracts.js';
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // MCP coordinator pending-event queue — FILE-BASED PERSISTENCE
26
+ // ---------------------------------------------------------------------------
27
+ // When a mesh event fires but no CLI coordinator session is registered (e.g.
28
+ // the coordinator is Claude Code running via MCP), we persist the event to a
29
+ // per-mesh JSONL file so it survives daemon restarts. The 50-entry hard cap
30
+ // is removed; the file is drained atomically on each get_pending_mesh_events
31
+ // call and limited to 100 KB to prevent runaway growth.
32
+ //
33
+ // File: <ledgerDir>/<meshId>.pending-events.jsonl
34
+ // ---------------------------------------------------------------------------
35
+
36
+ export interface PendingMeshCoordinatorEvent {
37
+ event: string;
38
+ meshId: string;
39
+ nodeLabel: string;
40
+ nodeId?: string;
41
+ workspace?: string;
42
+ metadataEvent: Record<string, unknown>;
43
+ coordinatorMessage?: string;
44
+ queuedAt: number;
45
+ /**
46
+ * When set, this event is intended for a specific coordinator daemon.
47
+ * Coordinators on other daemons should ignore it during drain.
48
+ * Absent on legacy events — treated as broadcast to any coordinator.
49
+ */
50
+ targetCoordinatorDaemonId?: string;
51
+ /**
52
+ * When set, this event is intended for a specific coordinator SESSION on the
53
+ * target daemon (the session that originally dispatched the work). PHASE 2 inject
54
+ * strict-matches the live coordinator by this session id so a sibling coordinator
55
+ * session on the same daemon does not receive another coordinator's completion.
56
+ * Absent on legacy / version-skewed events → daemon-level broadcast (no regression).
57
+ * Rides inside the event payload, so it survives the SQLite payload round-trip and
58
+ * the JSONL file without a dedicated column; it is NOT a drain-scoping key.
59
+ */
60
+ targetCoordinatorSessionId?: string;
61
+
62
+ // ─── v2 protocol envelope (B2a) — additive, populated at emit time ────────
63
+ // Stamped by queuePendingMeshCoordinatorEvent from the fields above plus an
64
+ // optional emit hint. A v1 reader that ignores these is unaffected (the v2
65
+ // shape is a strict superset). Absent → the event is a v1 event, treated as
66
+ // broadcast during rollout.
67
+ /** '2.0' once stamped. Absent on v1 events. */
68
+ protocolVersion?: typeof MESH_PROTOCOL_VERSION_V2;
69
+ /** Idempotency key (UUID). The receiver's authoritative dedup key (B3). */
70
+ eventId?: string;
71
+ /** Routing scope. Defaulted from the event name unless the emit hint overrides. */
72
+ scope?: MeshEventScope;
73
+ /** Identity of the coordinator that dispatched the work this event reports. */
74
+ dispatchedBy?: CoordinatorIdentity;
75
+ /** Present only for unicast scope: the coordinator this event is addressed to. */
76
+ intendedFor?: CoordinatorIdentity;
77
+ }
78
+
79
+ /**
80
+ * Optional emit-time hint passed to queuePendingMeshCoordinatorEvent so a call
81
+ * site can override the name-defaulted scope or supply richer coordinator
82
+ * identity (e.g. a coordinatorRunId the base event fields don't carry). Every
83
+ * field is optional; when omitted the stamp is derived entirely from the
84
+ * event's own targetCoordinatorDaemonId / targetCoordinatorSessionId. Kept
85
+ * separate from the event so existing single-arg callers are untouched.
86
+ */
87
+ export interface PendingEventEmitHint {
88
+ scope?: MeshEventScope;
89
+ /** Overrides the coordinator identity derived from the event's target fields. */
90
+ dispatchedBy?: CoordinatorIdentity;
91
+ /** Overrides the unicast target derived from the event's target fields. */
92
+ intendedFor?: CoordinatorIdentity;
93
+ /** coordinatorRunId to fold into the derived identity when the event lacks one. */
94
+ coordinatorRunId?: string;
95
+ }
96
+
97
+ const REFINE_TERMINAL_EVENTS = new Set(['refine:completed', 'refine:failed']);
98
+
99
+ /** Normalise a coordinator-daemon-id argument (single id, list, or undefined) into a
100
+ * de-duplicated list of non-empty strings, EXPANDED to every equivalent daemon-id
101
+ * form (bare `mach_X` ≡ `daemon_mach_X` ≡ `standalone_mach_X`).
102
+ *
103
+ * A coordinator resolves its own id through one path (status instanceId, the config-
104
+ * form node daemonId, or the bare machineId) but a worker stamps a completion's
105
+ * `coordinator_daemon_id` through another, so the two are routinely in DIFFERENT
106
+ * forms of the SAME machine. The scope filter is an exact-string match, so without
107
+ * expansion a `daemon_mach_X`-scoped completion is silently skipped by a coordinator
108
+ * that only knows itself as bare `mach_X` (the base-node completion-surface bug).
109
+ * Expanding here fixes every drain/peek/surface caller uniformly. The first ORIGINAL
110
+ * id stays at [0] so per-daemon JSONL file naming keeps its primary; expansion stays
111
+ * within one machine core so a different coordinator's events are never claimed. */
112
+ function normalizeCoordinatorDaemonIds(
113
+ coordinatorDaemonId?: string | null | ReadonlyArray<string>,
114
+ ): string[] {
115
+ return expandDaemonIdForms(coordinatorDaemonId);
116
+ }
117
+
118
+ // ─── B3a: drain-side v2 routing (accept-and-warn) ────────────────────────────
119
+ //
120
+ // Stage-1 of the v2 receive path. The drain scope is still primarily gated by the
121
+ // SQLite/JSONL `coordinator_daemon_id` filter (v1 mechanism, untouched here), so
122
+ // this layer runs on top of an already daemon-scoped candidate set and adds:
123
+ //
124
+ // 1. v2 unicast routing — an event whose intendedFor addresses a DIFFERENT
125
+ // coordinator on THIS daemon (a sibling CLI/MCP session) is skipped, so a
126
+ // completion doesn't cross-surface. Broadcast/system-as-broadcast pass.
127
+ // 2. eventId idempotency — a v2 event whose eventId was already drained is
128
+ // skipped (durable, via MeshRuntimeStore.hasDrainedEventId) plus a per-drain
129
+ // batch guard against same-batch duplicates.
130
+ // 3. accept-and-warn — a v2 event that FAILS validation, or has NO version, is
131
+ // NOT dropped: it passes through (no v1 regression) with a one-shot WARN and
132
+ // a counter bump. Hard rejection is T6 (enforce mode), not here.
133
+ // 4. re-attribution fallback — a unicast event whose intendedFor does not match
134
+ // the drainer by identity is NOT dropped when its intendedFor.daemonId is the
135
+ // SAME machine as the drainer (a coordinatorRunId change from a restart
136
+ // orphaned it): it is delivered to the current coordinator on that daemon.
137
+
138
+ /**
139
+ * T6 (B3c) enforce switch. When ON, the drain path stops passing an unversioned
140
+ * (v1) or a validation-failing v2 event through to the coordinator — it QUARANTINES
141
+ * it instead (excluded from the delivered batch + WARN + counter), and unicast
142
+ * routing is the only delivery path (there is no v1 broadcast fallback). On by
143
+ * default; set MESH_PROTOCOL_V2_ENFORCE=0/false/off/no to disable and restore the
144
+ * accept-and-warn rollout behaviour exactly.
145
+ *
146
+ * Per the rollout plan (§1 decision 4): enforce is `MESH_PROTOCOL_V2_ENFORCE` (env).
147
+ * Now that every node emits v2 (§배포 게이트 1 / risk §4), the code default is ON —
148
+ * a manual env injection is no longer required to get enforce behaviour. Rollback to
149
+ * accept mode is a pure-env step: set `MESH_PROTOCOL_V2_ENFORCE=0` (or `false`/`off`/
150
+ * `no`) — no code change, no data migration (the schema is additive). Read at call
151
+ * time so a test / operator can toggle it without a restart.
152
+ *
153
+ * Quarantine (not drop) keeps the loss-free invariant. The DESTRUCTIVE drain has
154
+ * already consumed the event from its store by the time routing runs, so "held
155
+ * back" here means: excluded from the delivered batch AND mirrored into the mesh
156
+ * ledger as a recoverable `event_held` entry (the same recovery channel the
157
+ * pending-trim path uses). It is observable via the counters + the ledger, so an
158
+ * operator can requeue it after fixing the producer. The non-destructive PEEK path
159
+ * (countMetrics=false) merely omits the event from the returned list — it never
160
+ * consumed it and must not ledger-record on every status poll.
161
+ */
162
+ export function isMeshProtocolV2EnforceEnabled(): boolean {
163
+ const raw = readNonEmptyString(process.env.MESH_PROTOCOL_V2_ENFORCE);
164
+ if (!raw) return true; // unset/blank = default ON
165
+ const v = raw.trim().toLowerCase();
166
+ return !(v === '0' || v === 'false' || v === 'off' || v === 'no'); // only explicit off = false
167
+ }
168
+
169
+ /**
170
+ * Record a v2-enforce-quarantined event into the mesh ledger as recoverable, so a
171
+ * destructively-drained event held back by enforce is auditable and requeue-able
172
+ * (loss-free invariant). Mirrors the pending-trim `event_held` shape. Best-effort:
173
+ * a ledger write failure must not break the drain. Called ONLY on the destructive
174
+ * drain path (the peek path never consumed the event, so nothing to recover).
175
+ */
176
+ function ledgerRecordQuarantinedEvent(event: PendingMeshCoordinatorEvent, reason: string): void {
177
+ try {
178
+ const finalSummary = readMeshCompletionSummary(event.metadataEvent || {});
179
+ appendLedgerEntry(event.meshId, {
180
+ kind: 'event_held',
181
+ ...(event.nodeId ? { nodeId: event.nodeId } : {}),
182
+ payload: {
183
+ event: event.event,
184
+ reason,
185
+ recoverable: true,
186
+ nodeLabel: event.nodeLabel,
187
+ ...(event.workspace ? { workspace: event.workspace } : {}),
188
+ targetCoordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
189
+ ...(readNonEmptyString(event.eventId) ? { eventId: event.eventId } : {}),
190
+ queuedAt: event.queuedAt,
191
+ ...(finalSummary ? { finalSummary } : {}),
192
+ // Full original event so mesh_requeue_held_events can restore it
193
+ // losslessly (event_held→pending). The summary/label fields above stay
194
+ // for human-readable audit; `heldEvent` is the machine recovery copy.
195
+ heldEvent: event,
196
+ },
197
+ });
198
+ } catch (e: any) {
199
+ LOG.warn('MeshEventsV2', `Failed to ledger-record v2-quarantined ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
200
+ }
201
+ }
202
+
203
+ /** Observability counters for the v2 drain path. Read by tests and surfaced in
204
+ * mesh_status (B4/T6). Process-lifetime totals — never reset in production. */
205
+ const meshV2DrainCounters = {
206
+ /** v2 events that passed validation and unicast/broadcast routing → delivered. */
207
+ v2Delivered: 0,
208
+ /** v2 unicast events skipped because intendedFor addressed another coordinator. */
209
+ v2RoutedAway: 0,
210
+ /** v2 events skipped because their eventId was already drained (idempotency). */
211
+ v2DedupSkipped: 0,
212
+ /** v2 events that failed assertPendingMeshCoordinatorEventV2 but were PASSED
213
+ * THROUGH (accept mode). Non-zero here is the rollout signal that a producer
214
+ * emits a malformed envelope. */
215
+ v2ValidationFailedAccepted: 0,
216
+ /** unicast events re-attributed to the drainer via daemon-core match (a
217
+ * coordinatorRunId change orphaned them). */
218
+ v2ReattributedToDrainer: 0,
219
+ /** v1 (unversioned) events passed through as broadcast (rollout baseline). */
220
+ v1BroadcastAccepted: 0,
221
+ /** T6 enforce: v2 events that FAILED validation and were QUARANTINED (held back
222
+ * from delivery, not dropped). Non-zero here means a producer is still emitting a
223
+ * malformed envelope after enforce was turned on. */
224
+ v2ValidationFailedQuarantined: 0,
225
+ /** T6 enforce: v1 (unversioned) events QUARANTINED because no v2 envelope could be
226
+ * derived at emit time. Non-zero here means a producer path still emits v1 after
227
+ * enforce — it should reach 0 once every node is on a v2-stamping build. */
228
+ v1UnversionedQuarantined: 0,
229
+ };
230
+
231
+ /** Test/observability accessor for the v2 drain counters (snapshot copy). */
232
+ export function getMeshV2DrainCounters(): Readonly<typeof meshV2DrainCounters> {
233
+ return { ...meshV2DrainCounters };
234
+ }
235
+
236
+ /** Test helper: zero the v2 drain counters so a test starts from a clean slate. */
237
+ export function __resetMeshV2DrainCountersForTests(): void {
238
+ for (const k of Object.keys(meshV2DrainCounters) as Array<keyof typeof meshV2DrainCounters>) {
239
+ meshV2DrainCounters[k] = 0;
240
+ }
241
+ }
242
+
243
+ // One-shot WARN dedup: an accept-mode warning is logged once per (meshId, eventId)
244
+ // so a re-polled malformed event doesn't spam the log every 4s reconcile tick.
245
+ const warnedV2Violations = new Set<string>();
246
+ function warnV2Once(key: string, message: string): void {
247
+ if (warnedV2Violations.has(key)) return;
248
+ warnedV2Violations.add(key);
249
+ // Bound the set so a long-lived daemon churning many distinct eventIds can't leak.
250
+ if (warnedV2Violations.size > 2000) {
251
+ const first = warnedV2Violations.values().next().value;
252
+ if (first !== undefined) warnedV2Violations.delete(first);
253
+ }
254
+ LOG.warn('MeshEventsV2', message);
255
+ }
256
+
257
+ /** Test helper: clear the one-shot WARN dedup set. */
258
+ export function __resetMeshV2WarnDedupForTests(): void {
259
+ warnedV2Violations.clear();
260
+ }
261
+
262
+ /**
263
+ * Resolve the drainer's CoordinatorIdentity for v2 routing from the daemon-id
264
+ * argument the (untouchable) reconcile-loop already passes. The daemon ids are the
265
+ * dual/expanded self-identity forms from resolveCoordinatorDaemonIds; the FIRST is
266
+ * the primary. coordinatorRunId is not threaded through the drain call yet, so it
267
+ * falls back to the daemonId exactly as the emit side does
268
+ * (coordinatorIdentityFromEmitFields) — this keeps drain-side identity CONSISTENT
269
+ * with how v1→v2 events were stamped, and unicast equality then reduces to the
270
+ * daemon-core match, which is the correct rollout-window granularity. A caller that
271
+ * knows the full identity (with a real coordinatorRunId) may pass it explicitly to
272
+ * override. Returns undefined when no daemon id is known (→ v2 routing is a no-op,
273
+ * everything passes as-is).
274
+ */
275
+ function resolveDrainerIdentity(
276
+ daemonIds: ReadonlyArray<string>,
277
+ explicit?: CoordinatorIdentity,
278
+ ): CoordinatorIdentity | undefined {
279
+ if (explicit) return explicit;
280
+ return coordinatorIdentityFromEmitFields({ daemonId: daemonIds[0] });
281
+ }
282
+
283
+ /** A v2 event carries a '2.0' protocolVersion. Everything else is a v1 event. */
284
+ function isV2Event(event: PendingMeshCoordinatorEvent): boolean {
285
+ return event.protocolVersion === MESH_PROTOCOL_VERSION_V2;
286
+ }
287
+
288
+ /**
289
+ * True when an identity's coordinatorRunId is merely its own daemonId form (the
290
+ * B2a fallback in coordinatorIdentityFromEmitFields — no real coordinatorRunId was
291
+ * threaded through the emit/drain site yet). For such an identity the runId carries
292
+ * NO information beyond the daemon, so two different daemon-id FORMS of the same
293
+ * machine (mach_ vs daemon_mach_) must not be treated as different coordinators.
294
+ */
295
+ function runIdIsDaemonFormFallback(identity: CoordinatorIdentity): boolean {
296
+ return daemonIdsEquivalent(identity.coordinatorRunId, identity.daemonId);
297
+ }
298
+
299
+ /**
300
+ * Delivery equality for the rollout window. When BOTH sides carry only a
301
+ * daemon-form-fallback runId (no real coordinatorRunId wired yet), a match reduces
302
+ * to same-machine — so a completion stamped `daemon_mach_X` is delivered to a
303
+ * coordinator that knows itself as bare `mach_X` (the canon-identity heterogeneous-
304
+ * form case). The session is compared ONLY when BOTH sides carry one: a session-less
305
+ * drainer is a daemon-level drain (what the reconcile loop passes) that accepts any
306
+ * session's events on that machine — targetCoordinatorSessionId is a PHASE-2 inject
307
+ * key, not a drain-scoping key (see the v1 field comment). When only the drainer AND
308
+ * the event both name a session do we require them to match, so a session-specific
309
+ * coordinator does not receive a sibling session's unicast event.
310
+ *
311
+ * When EITHER side has a real (non-daemon-form) runId, fall back to strict
312
+ * coordinatorIdentityEquals so two genuinely distinct coordinators on the same
313
+ * daemon (different real runIds) stay separated.
314
+ */
315
+ function identityDeliversTo(intendedFor: CoordinatorIdentity, drainer: CoordinatorIdentity): boolean {
316
+ if (runIdIsDaemonFormFallback(intendedFor) && runIdIsDaemonFormFallback(drainer)) {
317
+ if (!daemonIdsEquivalent(intendedFor.daemonId, drainer.daemonId)) return false;
318
+ // Session filter applies only when the drainer itself is session-specific.
319
+ if (intendedFor.sessionId && drainer.sessionId) {
320
+ return intendedFor.sessionId === drainer.sessionId;
321
+ }
322
+ return true;
323
+ }
324
+ return coordinatorIdentityEquals(intendedFor, drainer);
325
+ }
326
+
327
+ /**
328
+ * Apply v2 receive-side routing + idempotency to a merged, already daemon-scoped
329
+ * candidate list (accept-and-warn — never drops on validation failure).
330
+ *
331
+ * - `drainer` undefined → routing is skipped, list returned unchanged (safety).
332
+ * - Marks each surviving v2 event's eventId in `batchSeen` so a same-batch dup is
333
+ * skipped; a caller that persists drains uses `alreadyDrained` for the durable
334
+ * check (getPending peek passes a no-op so a peek never dedups against itself).
335
+ */
336
+ function routeV2EventsForDrainer(
337
+ events: PendingMeshCoordinatorEvent[],
338
+ drainer: CoordinatorIdentity | undefined,
339
+ ctx: {
340
+ alreadyDrained: (eventId: string) => boolean;
341
+ batchSeen: Set<string>;
342
+ /** false for a non-destructive peek so the frequent status-poll path does
343
+ * not inflate the delivery counters (only the real drain counts). */
344
+ countMetrics: boolean;
345
+ },
346
+ ): PendingMeshCoordinatorEvent[] {
347
+ if (!drainer) return events;
348
+ // Read the enforce flag ONCE per drain so the whole batch is classified under a
349
+ // single, consistent policy (a mid-batch env flip cannot split one drain).
350
+ const enforce = isMeshProtocolV2EnforceEnabled();
351
+ const bump = (k: keyof typeof meshV2DrainCounters) => { if (ctx.countMetrics) meshV2DrainCounters[k]++; };
352
+ const kept: PendingMeshCoordinatorEvent[] = [];
353
+ for (const event of events) {
354
+ if (!isV2Event(event)) {
355
+ // v1 / unversioned event. ACCEPT MODE: broadcast during rollout (existing
356
+ // policy). ENFORCE MODE: quarantine — an unversioned event has no scope, so
357
+ // there is no safe unicast target; hold it back (not delivered) and mirror
358
+ // it to the ledger as recoverable, with a one-shot WARN + counter.
359
+ if (enforce) {
360
+ bump('v1UnversionedQuarantined');
361
+ if (ctx.countMetrics) ledgerRecordQuarantinedEvent(event, 'v2_enforce_unversioned_quarantined');
362
+ warnV2Once(
363
+ `${event.meshId}::${event.eventId ?? event.event}::v1-quarantined`,
364
+ `v2 ENFORCE: unversioned ${event.event} on mesh ${event.meshId} QUARANTINED (no v2 envelope — held back, not delivered; ledger-recorded recoverable). A producer path still emits v1.`,
365
+ );
366
+ continue;
367
+ }
368
+ bump('v1BroadcastAccepted');
369
+ kept.push(event);
370
+ continue;
371
+ }
372
+
373
+ // Validate the v2 envelope. ACCEPT MODE: a validation failure does NOT drop
374
+ // the event — it passes through with a one-shot WARN + counter. ENFORCE MODE:
375
+ // a validation failure is QUARANTINED (held back, not delivered) — the malformed
376
+ // envelope carries no trustworthy scope/target, so delivering it risks a
377
+ // cross-surface. It is ledger-recorded recoverable on the destructive path.
378
+ let validated: PendingMeshCoordinatorEventV2;
379
+ try {
380
+ validated = assertPendingMeshCoordinatorEventV2(event);
381
+ } catch (e: any) {
382
+ if (enforce) {
383
+ bump('v2ValidationFailedQuarantined');
384
+ if (ctx.countMetrics) ledgerRecordQuarantinedEvent(event, 'v2_enforce_validation_failed_quarantined');
385
+ warnV2Once(
386
+ `${event.meshId}::${event.eventId ?? event.event}::invalid-quarantined`,
387
+ `v2 ENFORCE: envelope validation failed for ${event.event} on mesh ${event.meshId} — QUARANTINED (held back, not delivered; ledger-recorded recoverable): ${e?.message || e}`,
388
+ );
389
+ continue;
390
+ }
391
+ bump('v2ValidationFailedAccepted');
392
+ warnV2Once(
393
+ `${event.meshId}::${event.eventId ?? event.event}::invalid`,
394
+ `v2 envelope validation failed for ${event.event} on mesh ${event.meshId} — PASSED THROUGH (accept mode): ${e?.message || e}`,
395
+ );
396
+ kept.push(event);
397
+ continue;
398
+ }
399
+
400
+ // eventId idempotency: skip if already drained (durable) or already seen in
401
+ // this same batch (guards the SQLite+JSONL dual-store merge duplicate).
402
+ const eventId = validated.eventId;
403
+ if (ctx.batchSeen.has(eventId) || ctx.alreadyDrained(eventId)) {
404
+ bump('v2DedupSkipped');
405
+ continue;
406
+ }
407
+
408
+ // Broadcast → any coordinator; system → daemon handler only (never a
409
+ // coordinator). Delegates to the contract helper for those two scopes.
410
+ if (validated.scope !== 'unicast') {
411
+ if (shouldDeliverPendingEventToCoordinator(validated, drainer)) {
412
+ ctx.batchSeen.add(eventId);
413
+ bump('v2Delivered');
414
+ kept.push(event);
415
+ } else {
416
+ // system scope → not for any coordinator.
417
+ bump('v2RoutedAway');
418
+ }
419
+ continue;
420
+ }
421
+
422
+ // Unicast: deliver iff intendedFor addresses THIS drainer. identityDeliversTo
423
+ // treats a daemon-form-fallback runId (no real coordinatorRunId wired yet) as
424
+ // form-agnostic so a `daemon_mach_X`-addressed event reaches a bare-`mach_X`
425
+ // drainer (heterogeneous-form same coordinator), while keeping two REAL
426
+ // distinct runIds on one daemon separated.
427
+ if (validated.intendedFor && identityDeliversTo(validated.intendedFor, drainer)) {
428
+ ctx.batchSeen.add(eventId);
429
+ bump('v2Delivered');
430
+ kept.push(event);
431
+ continue;
432
+ }
433
+
434
+ // Not delivered by identity. Apply the re-attribution fallback (plan risk
435
+ // §4): if intendedFor addresses the SAME MACHINE as the drainer AND the
436
+ // mismatch is a genuine coordinatorRunId change (a restart minted a fresh
437
+ // runId), deliver it to the current coordinator rather than orphaning it.
438
+ //
439
+ // Guard: when BOTH sides carry only a daemon-form-fallback runId, a mismatch
440
+ // that survived identityDeliversTo is a SESSION mismatch (a sibling
441
+ // coordinator on the same daemon) — that is a legitimate route-away, NOT an
442
+ // orphaned event, so re-attribution must not fire. Re-attribution requires a
443
+ // REAL runId difference, which means at least one side carries a real runId.
444
+ const realRunIdMismatch = !runIdIsDaemonFormFallback(validated.intendedFor!)
445
+ || !runIdIsDaemonFormFallback(drainer);
446
+ if (
447
+ validated.intendedFor
448
+ && realRunIdMismatch
449
+ && daemonIdsEquivalent(validated.intendedFor.daemonId, drainer.daemonId)
450
+ ) {
451
+ ctx.batchSeen.add(eventId);
452
+ bump('v2ReattributedToDrainer');
453
+ warnV2Once(
454
+ `${event.meshId}::${eventId}::reattributed`,
455
+ `v2 unicast ${event.event} on mesh ${event.meshId} re-attributed to current coordinator ${coordinatorIdentityKey(drainer)} (originating coordinatorRunId no longer live)`,
456
+ );
457
+ kept.push(event);
458
+ continue;
459
+ }
460
+
461
+ // Addressed to a genuinely different coordinator (different machine, or
462
+ // system scope) → not for this drainer. Skipped (left for its own drainer).
463
+ bump('v2RoutedAway');
464
+ }
465
+ return kept;
466
+ }
467
+
468
+ export function readRefineJobId(event: { metadataEvent?: Record<string, unknown> } | Record<string, unknown>): string {
469
+ const metadata = readRecord((event as any).metadataEvent) || event as Record<string, unknown>;
470
+ const result = readRecord(metadata.result);
471
+ const refineJob = readRecord(result?.refineJob);
472
+ return readNonEmptyString(metadata.jobId) || readNonEmptyString(refineJob?.jobId);
473
+ }
474
+
475
+ function buildRefineTerminalEventFingerprint(meshId: string, eventName: string, metadataEvent: Record<string, unknown>): string {
476
+ const jobId = readRefineJobId({ metadataEvent });
477
+ return jobId && REFINE_TERMINAL_EVENTS.has(eventName) ? `${meshId}::${eventName}::${jobId}` : '';
478
+ }
479
+
480
+ function hasPendingRefineTerminalEventDuplicate(event: PendingMeshCoordinatorEvent): boolean {
481
+ if (!REFINE_TERMINAL_EVENTS.has(event.event)) return false;
482
+ const jobId = readRefineJobId(event);
483
+ if (!jobId) return false;
484
+ return readPendingMeshCoordinatorEventsFromDisk(event.meshId).some((pending) =>
485
+ pending.event === event.event && readRefineJobId(pending) === jobId,
486
+ );
487
+ }
488
+
489
+ // CANON-B / DUPNOTIF: terminal completion events that the coordinator surfaces as a
490
+ // notification. The native completion path (handleMeshCoordinatorEvent) and the transcript
491
+ // reconciliation fallback (reconcileDirectDispatchCompletionFromTranscript) BOTH queue one of
492
+ // these for the same finished task — with DIFFERENT timestamps — so a timestamp-bearing
493
+ // fingerprint lets both surface and the coordinator notifies twice. When the event carries a
494
+ // taskId we anchor the fingerprint on the taskId (dropping the timestamp), collapsing the two
495
+ // paths into a single surface. A weakness marker keeps a tentative false-idle completion
496
+ // distinct from the genuine completion that supersedes it, so the genuine one is never
497
+ // swallowed by the earlier weak one.
498
+ const TERMINAL_COMPLETION_EVENTS = new Set(['agent:generating_completed', 'agent:stopped']);
499
+
500
+ export function buildPendingEventFingerprint(event: PendingMeshCoordinatorEvent): string {
501
+ const metadata = readRecord(event.metadataEvent) || {};
502
+ // Bootstrap events are node-scoped: dedup by meshId+event+nodeId only.
503
+ // They carry no sessionId/taskId/timestamp — using those fields would produce
504
+ // an empty fingerprint that defeats dedup entirely.
505
+ if (event.event === 'worktree_bootstrap_complete' || event.event === 'worktree_bootstrap_failed') {
506
+ return [event.meshId, event.event, event.nodeId || ''].join('::');
507
+ }
508
+ // DUPNOTIF: a terminal completion carrying a taskId is deduped by taskId (+ weakness),
509
+ // NOT by timestamp — the native and transcript-reconciliation paths timestamp the same
510
+ // completion differently, and only taskId is stable across both.
511
+ if (TERMINAL_COMPLETION_EVENTS.has(event.event)) {
512
+ const terminalTaskId = readNonEmptyString(metadata.taskId) || readNonEmptyString(readRecord(metadata.payload)?.taskId);
513
+ if (terminalTaskId) {
514
+ return [
515
+ event.meshId,
516
+ event.event,
517
+ terminalTaskId,
518
+ isWeakCompletionMetadata(metadata) ? 'weak' : 'genuine',
519
+ ].join('::');
520
+ }
521
+ }
522
+ // MAGI consensus-group exemption: a consensusGroupId marks an INTENTIONAL
523
+ // same-prompt fan-out across N replicas — the exact opposite of the accidental
524
+ // duplicates this dedup collapses. Anchor the fingerprint on the unique
525
+ // (taskId, consensusGroupId) so grouped replicas can NEVER be collapsed by any
526
+ // future prompt-content-based tightening of this builder. Mirrors the
527
+ // bootstrap-event exemption above and serves as the explicit fan-out marker.
528
+ // (Today this is belt-and-suspenders: each replica already gets a distinct
529
+ // taskId, so the generic key below would not collapse them either.)
530
+ const consensusGroupId = readNonEmptyString(metadata.consensusGroupId)
531
+ || readNonEmptyString(readRecord(metadata.payload)?.consensusGroupId);
532
+ if (consensusGroupId) {
533
+ const groupTaskId = readNonEmptyString(metadata.taskId)
534
+ || readNonEmptyString(readRecord(metadata.payload)?.taskId);
535
+ return [event.meshId, event.event, groupTaskId || '', consensusGroupId, 'group'].join('::');
536
+ }
537
+ const sessionId = resolveEventSessionId(metadata);
538
+ const providerSessionId = readNonEmptyString(metadata.providerSessionId);
539
+ const taskId = readNonEmptyString(metadata.taskId) || readNonEmptyString(readRecord(metadata.payload)?.taskId);
540
+ const jobId = readRefineJobId(event);
541
+ const timestamp = metadata.timestamp !== undefined && metadata.timestamp !== null ? String(metadata.timestamp) : '';
542
+ return [
543
+ event.meshId,
544
+ event.event,
545
+ event.nodeId || '',
546
+ sessionId || '',
547
+ providerSessionId || '',
548
+ taskId || '',
549
+ jobId || '',
550
+ timestamp || '',
551
+ ].join('::');
552
+ }
553
+
554
+ // NOTE: the former R3 "direct-delivered" marker (markMeshCoordinatorEventDirectDelivered /
555
+ // wasDirectDeliveredToCoordinator) was removed when spontaneous PTY direct-inject was retired.
556
+ // Delivery is now queue-drain-only: an event is consumed by exactly one drainer via the atomic
557
+ // SQLite drained=1 marking, so there is no PTY-vs-poll double-delivery left to dedup against.
558
+ // The dormant mesh_direct_delivered_events table that backed it was dropped in
559
+ // MeshRuntimeStore.migrateMeshIsolationColumns (DROP TABLE IF EXISTS, migration step 5).
560
+
561
+ export function hasPendingCoordinatorEventDuplicate(event: PendingMeshCoordinatorEvent): boolean {
562
+ const fingerprint = buildPendingEventFingerprint(event);
563
+ if (!fingerprint.trim()) return false;
564
+ // Check SQLite inbox first (G3 primary path)
565
+ try {
566
+ if (MeshRuntimeStore.getInstance().hasPendingEventFingerprint(event.meshId, fingerprint)) return true;
567
+ } catch { /* fall through to JSONL check */ }
568
+ return readPendingMeshCoordinatorEventsFromDisk(event.meshId).some((pending) => buildPendingEventFingerprint(pending) === fingerprint);
569
+ }
570
+
571
+ function getPendingEventsPath(meshId: string, coordinatorDaemonId?: string): string {
572
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
573
+ if (coordinatorDaemonId) {
574
+ const safeDaemon = coordinatorDaemonId.replace(/[^a-zA-Z0-9_-]/g, '_');
575
+ return join(getLedgerDir(), `${safe}-${safeDaemon}.pending-events.jsonl`);
576
+ }
577
+ return join(getLedgerDir(), `${safe}.pending-events.jsonl`);
578
+ }
579
+
580
+ function readPendingMeshCoordinatorEventsFromDisk(meshId?: string, coordinatorDaemonId?: string | ReadonlyArray<string>): PendingMeshCoordinatorEvent[] {
581
+ if (!meshId) return [];
582
+ const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
583
+ const primaryDaemonId = daemonIds[0];
584
+ // Read coordinator-scoped file first; fall back to legacy shared file.
585
+ const paths = primaryDaemonId
586
+ ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)]
587
+ : [getPendingEventsPath(meshId)];
588
+ const events: PendingMeshCoordinatorEvent[] = [];
589
+ for (const path of paths) {
590
+ if (!existsSync(path)) continue;
591
+ try {
592
+ const raw = readFileSync(path, 'utf-8');
593
+ const parsed = raw.split('\n').filter(Boolean).flatMap(line => {
594
+ try { return [JSON.parse(line) as PendingMeshCoordinatorEvent]; } catch { return []; }
595
+ });
596
+ // If reading the shared file, filter to events that target this coordinator or are unscoped.
597
+ const filtered = (primaryDaemonId && path === getPendingEventsPath(meshId))
598
+ ? parsed.filter(e => !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId))
599
+ : parsed;
600
+ events.push(...filtered);
601
+ } catch { /* skip unreadable files */ }
602
+ }
603
+ return events;
604
+ }
605
+
606
+ function refineTerminalEventFromLedger(meshId: string, pending: readonly PendingMeshCoordinatorEvent[]): PendingMeshCoordinatorEvent[] {
607
+ const acceptedJobIds = new Set(
608
+ pending
609
+ .filter(event => event.event === 'refine:accepted')
610
+ .map(event => readRefineJobId(event))
611
+ .filter(Boolean),
612
+ );
613
+ if (acceptedJobIds.size === 0) return [];
614
+ const existingTerminalJobIds = new Set(
615
+ pending
616
+ .filter(event => REFINE_TERMINAL_EVENTS.has(event.event))
617
+ .map(event => `${event.event}:${readRefineJobId(event)}`)
618
+ .filter(value => !value.endsWith(':')),
619
+ );
620
+ const backfilled: PendingMeshCoordinatorEvent[] = [];
621
+ const entries = readLedgerEntries(meshId, { tail: 200 });
622
+ for (let i = entries.length - 1; i >= 0; i--) {
623
+ const entry = entries[i];
624
+ if (entry.kind !== 'task_completed' && entry.kind !== 'task_failed') continue;
625
+ const payload = readRecord(entry.payload);
626
+ if (payload?.source !== 'refine_mesh_node_async_job') continue;
627
+ const refineJob = readRecord(payload.refineJob);
628
+ const jobId = readNonEmptyString(refineJob?.jobId);
629
+ if (!jobId || !acceptedJobIds.has(jobId)) continue;
630
+ const eventName = entry.kind === 'task_completed' ? 'refine:completed' : 'refine:failed';
631
+ if (existingTerminalJobIds.has(`${eventName}:${jobId}`)) continue;
632
+ existingTerminalJobIds.add(`${eventName}:${jobId}`);
633
+ const result = readRecord(payload.result);
634
+ const metadataEvent = {
635
+ source: 'refine_mesh_node_async_job',
636
+ jobId,
637
+ interactionId: readNonEmptyString(refineJob?.interactionId),
638
+ meshId,
639
+ nodeId: readNonEmptyString(refineJob?.nodeId) || entry.nodeId,
640
+ targetDaemonId: readNonEmptyString(refineJob?.targetDaemonId),
641
+ workspace: readNonEmptyString(refineJob?.workspace),
642
+ status: eventName === 'refine:completed' ? 'completed' : 'failed',
643
+ startedAt: readNonEmptyString(refineJob?.startedAt),
644
+ completedAt: readNonEmptyString(refineJob?.completedAt) || entry.timestamp,
645
+ retryOfJobId: readNonEmptyString(refineJob?.retryOfJobId) || readNonEmptyString(payload.retryOfJobId),
646
+ ...(result ? { result } : {}),
647
+ };
648
+ const nodeLabel = readNonEmptyString(refineJob?.nodeId) || entry.nodeId || 'refine job';
649
+ backfilled.push({
650
+ event: eventName,
651
+ meshId,
652
+ nodeLabel,
653
+ nodeId: readNonEmptyString(refineJob?.nodeId) || entry.nodeId,
654
+ workspace: readNonEmptyString(refineJob?.workspace),
655
+ metadataEvent,
656
+ coordinatorMessage: buildMeshSystemMessage({ event: eventName, nodeLabel, metadataEvent }),
657
+ queuedAt: Date.now(),
658
+ });
659
+ }
660
+ return backfilled.reverse();
661
+ }
662
+
663
+ function reconcilePendingMeshCoordinatorEvents(meshId: string, events: PendingMeshCoordinatorEvent[]): PendingMeshCoordinatorEvent[] {
664
+ const backfilled = refineTerminalEventFromLedger(meshId, events);
665
+ // A refine:accepted event is a provisional "job accepted, result to follow" signal.
666
+ // Once its terminal (completed/failed) counterpart for the same jobId exists — whether
667
+ // already direct-queued into the pending store OR backfilled from the ledger here — the
668
+ // accepted is superseded and is dropped so the coordinator isn't shown stale duplicate
669
+ // noise alongside the terminal outcome.
670
+ const terminalJobIds = new Set(
671
+ [...events.filter(event => REFINE_TERMINAL_EVENTS.has(event.event)), ...backfilled]
672
+ .map(event => readRefineJobId(event))
673
+ .filter(Boolean),
674
+ );
675
+ const reconciled = terminalJobIds.size === 0
676
+ ? events
677
+ : events.filter(event => !(event.event === 'refine:accepted' && terminalJobIds.has(readRefineJobId(event))));
678
+ return backfilled.length === 0 ? reconciled : [...reconciled, ...backfilled];
679
+ }
680
+
681
+ const MAX_PENDING_EVENTS_BYTES = 100 * 1024; // 100 KB — keep the pending file small
682
+ const MAX_PENDING_EVENTS_KEEP = 50; // keep the last 50 events when trimming
683
+
684
+ // ─── SQLite pending-event retention ─────────────────────────────────────────
685
+ // mesh_pending_events had no lifecycle GC: drained rows are retained forever (the
686
+ // durable v2-eventId dedup baseline drainedEventIdsForMesh reads them), and an
687
+ // undrained row for a coordinator identity that never returns stays queued forever.
688
+ // Both accumulate without bound. These windows bound that growth while preserving
689
+ // the two things the rows exist for — recent-re-delivery idempotency and delivery
690
+ // to a returning coordinator. A drained event older than the drained window cannot
691
+ // be re-delivered (its producer session is long gone), so keeping it buys nothing;
692
+ // an undrained event is kept far longer so a genuinely-offline coordinator's backlog
693
+ // survives, and only unrecoverable orphans are swept.
694
+ const PENDING_EVENTS_DRAINED_RETENTION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
695
+ const PENDING_EVENTS_UNDRAINED_RETENTION_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
696
+
697
+ /**
698
+ * Retention sweep for the SQLite mesh_pending_events inbox. Deletes long-drained
699
+ * rows (past the idempotency-useful window) and long-orphaned undrained rows (a
700
+ * coordinator identity that never returned). Best-effort and idempotent: a store
701
+ * failure or an empty table is a cheap no-op. Called from the periodic mesh-event
702
+ * maintenance sweep. Returns the number of rows pruned (0 when nothing to do).
703
+ */
704
+ export function prunePendingMeshCoordinatorEventsRetention(): number {
705
+ try {
706
+ const removed = MeshRuntimeStore.getInstance().prunePendingEvents({
707
+ drainedOlderThanMs: PENDING_EVENTS_DRAINED_RETENTION_MS,
708
+ undrainedOlderThanMs: PENDING_EVENTS_UNDRAINED_RETENTION_MS,
709
+ });
710
+ if (removed > 0) {
711
+ LOG.info('MeshEvents', `Pruned ${removed} stale pending-event row(s) (drained >7d / undrained >30d)`);
712
+ }
713
+ return removed;
714
+ } catch (e: any) {
715
+ LOG.warn('MeshEvents', `Pending-event retention prune failed: ${e?.message || e}`);
716
+ return 0;
717
+ }
718
+ }
719
+
720
+ function trimPendingEventsIfNeeded(path: string): void {
721
+ try {
722
+ if (!existsSync(path)) return;
723
+ if (statSync(path).size <= MAX_PENDING_EVENTS_BYTES) return;
724
+ const lines = readFileSync(path, 'utf-8').split('\n').filter(Boolean);
725
+ if (lines.length <= MAX_PENDING_EVENTS_KEEP) return;
726
+ // C1 (data safety): this trim discards the OLDEST queued lines to keep the file
727
+ // bounded. An undelivered terminal completion among them would otherwise lose its
728
+ // worker summary silently (the JSONL is the only copy when the SQLite dual-write
729
+ // failed). Before dropping, mirror any meaningful (coordinator-facing / summary-
730
+ // bearing) dropped event into the ledger so it stays auditable and recoverable,
731
+ // and LOG.warn so the drop is observable instead of silent.
732
+ const dropped = lines.slice(0, lines.length - MAX_PENDING_EVENTS_KEEP);
733
+ for (const line of dropped) {
734
+ let event: PendingMeshCoordinatorEvent | undefined;
735
+ try { event = JSON.parse(line) as PendingMeshCoordinatorEvent; } catch { continue; }
736
+ if (!event || !event.meshId) continue;
737
+ const finalSummary = readMeshCompletionSummary(event.metadataEvent || {});
738
+ // "Meaningful" = would have been delivered to a coordinator (carries a message)
739
+ // or carries worker output worth preserving. Silent lifecycle events are not
740
+ // logged — losing them on trim is harmless (they re-drive nothing once stale).
741
+ if (!readNonEmptyString(event.coordinatorMessage) && !finalSummary) continue;
742
+ try {
743
+ appendLedgerEntry(event.meshId, {
744
+ kind: 'event_held',
745
+ ...(event.nodeId ? { nodeId: event.nodeId } : {}),
746
+ payload: {
747
+ event: event.event,
748
+ reason: 'pending_trim_dropped',
749
+ recoverable: true,
750
+ nodeLabel: event.nodeLabel,
751
+ ...(event.workspace ? { workspace: event.workspace } : {}),
752
+ targetCoordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
753
+ ...(readNonEmptyString(event.eventId) ? { eventId: event.eventId } : {}),
754
+ queuedAt: event.queuedAt,
755
+ ...(finalSummary ? { finalSummary } : {}),
756
+ // Full original event for lossless mesh_requeue_held_events restore.
757
+ heldEvent: event,
758
+ },
759
+ });
760
+ LOG.warn('MeshEvents', `Pending-events trim dropping undelivered ${event.event} for mesh ${event.meshId} — recorded to ledger (recoverable)`);
761
+ } catch (e: any) {
762
+ LOG.warn('MeshEvents', `Failed to ledger-record trim-dropped ${event.event} for mesh ${event.meshId}: ${e?.message || e}`);
763
+ }
764
+ }
765
+ writeFileSync(path, lines.slice(-MAX_PENDING_EVENTS_KEEP).join('\n') + '\n', 'utf-8');
766
+ } catch { /* best-effort; if trim fails, append still proceeds */ }
767
+ }
768
+
769
+ /**
770
+ * Stamp the v2 protocol envelope onto a pending event at emit time (B2a).
771
+ *
772
+ * Non-breaking: returns a NEW event object with protocolVersion/eventId/scope/
773
+ * dispatchedBy/intendedFor added when a coordinator identity can be derived,
774
+ * otherwise returns the input unchanged (a v1 event, broadcast-treated during
775
+ * rollout). Identity and the unicast target are derived from the event's own
776
+ * targetCoordinatorDaemonId / targetCoordinatorSessionId (already carried by
777
+ * every producer), so most call sites need no change; the optional `hint`
778
+ * overrides scope/identity where a site knows better.
779
+ *
780
+ * The eventId is generated here (randomUUID) exactly once, so re-queues that
781
+ * pass an already-stamped event keep their original eventId — the idempotency
782
+ * key is stable across re-delivery. An already-stamped event is returned as-is.
783
+ */
784
+ export function stampPendingEventV2(
785
+ event: PendingMeshCoordinatorEvent,
786
+ hint?: PendingEventEmitHint,
787
+ ): PendingMeshCoordinatorEvent {
788
+ // Preserve idempotency across re-queues: never re-stamp an event that already
789
+ // carries a v2 eventId (mesh-reconcile-loop / flushPendingForMeshIdleCoordinators
790
+ // re-queue built events verbatim).
791
+ if (event.protocolVersion === MESH_PROTOCOL_VERSION_V2 && readNonEmptyString(event.eventId)) {
792
+ return event;
793
+ }
794
+
795
+ const coordinatorIdentity = hint?.dispatchedBy ?? coordinatorIdentityFromEmitFields({
796
+ daemonId: event.targetCoordinatorDaemonId,
797
+ coordinatorRunId: hint?.coordinatorRunId,
798
+ sessionId: event.targetCoordinatorSessionId,
799
+ });
800
+
801
+ // A/C ROOT FIX: an emit site with NO coordinator identity (direct-dispatch /
802
+ // refine notification / any path where the worker session never carried a
803
+ // meshCoordinatorDaemonId) used to leave the event UNVERSIONED (v1). Under v2
804
+ // enforce (default ON) routeV2EventsForDrainer QUARANTINES every unversioned
805
+ // event — so a summary-less completion (agent:generating_completed) and every
806
+ // refine terminal notification (refine:accepted/completed/failed) were held
807
+ // back and never reached the coordinator; only the backstop papered over it.
808
+ //
809
+ // Fall back to THIS daemon's own id as the dispatcher so a v2 envelope can
810
+ // still be minted. There is no addressable coordinator, so we intentionally
811
+ // leave intendedFor empty and let buildPendingEventEmitStamp downgrade the
812
+ // (unicast-defaulting) terminal event to a BROADCAST — deliverable to whatever
813
+ // coordinator drains on this machine, instead of an undeliverable v1 event.
814
+ // When a real coordinator identity DOES exist the unicast path below is
815
+ // unchanged (no regression). loadConfig().machineId is the same self-id source
816
+ // resolveCoordinatorDaemonIds / the local queue-assignment stamp use, so the
817
+ // broadcast dispatcher matches the drainer's own identity form.
818
+ const selfFallback = !coordinatorIdentity;
819
+ const dispatchedBy = coordinatorIdentity ?? coordinatorIdentityFromEmitFields({
820
+ daemonId: readNonEmptyString(loadConfig().machineId),
821
+ });
822
+ // The unicast target is, by default, the same coordinator the event is already
823
+ // routed to (its originating coordinator). A hint may override it. In the
824
+ // self-fallback case there is no originating coordinator to address, so leave
825
+ // it empty → broadcast (never a self-unicast that a sibling session's drainer
826
+ // would skip).
827
+ const intendedFor: CoordinatorIdentity | undefined = hint?.intendedFor
828
+ ?? (selfFallback ? undefined : coordinatorIdentity);
829
+
830
+ const stamp = buildPendingEventEmitStamp({
831
+ eventName: event.event,
832
+ eventId: randomUUID(),
833
+ dispatchedBy,
834
+ intendedFor,
835
+ // Force broadcast for the self-fallback so a unicast-defaulting terminal
836
+ // event isn't addressed to this daemon alone; an explicit hint still wins.
837
+ scope: hint?.scope ?? (selfFallback ? 'broadcast' : undefined),
838
+ });
839
+ if (!stamp) return event; // no coordinator identity at all (no self id) → stays a v1 event
840
+
841
+ return {
842
+ ...event,
843
+ protocolVersion: stamp.protocolVersion,
844
+ eventId: stamp.eventId,
845
+ scope: stamp.scope,
846
+ dispatchedBy: stamp.dispatchedBy,
847
+ ...(stamp.intendedFor ? { intendedFor: stamp.intendedFor } : {}),
848
+ };
849
+ }
850
+
851
+ // ─── v2 envelope: remote (P2P) boundary preservation (B3b/T4) ─────────────
852
+ //
853
+ // The remote pull round-trip (mesh-reconcile-loop pullRemoteNodeQueues →
854
+ // get_pending_mesh_events → buildForwardPayloadFromPending → handleMeshForwardEvent
855
+ // → queuePendingMeshCoordinatorEvent) flattens a queued PendingMeshCoordinatorEvent
856
+ // into a flat wire payload and rebuilds it on the receiving daemon. The v2 envelope
857
+ // fields (protocolVersion / eventId / scope / dispatchedBy / intendedFor) live at the
858
+ // TOP LEVEL of the event, not inside metadataEvent, so the flatten/rebuild whitelist
859
+ // dropped them: the re-queue then re-stamped a FRESH eventId, breaking cross-machine
860
+ // idempotency and downgrading the relayed completion to v1 (broadcast) routing.
861
+ //
862
+ // These two helpers are the single serialization/deserialization pair for that
863
+ // boundary. serializeV2EnvelopeToWire copies the present v2 fields onto the flat
864
+ // payload; readV2EnvelopeFromWire validates and restores them for the re-queue. The
865
+ // eventId is carried verbatim so stampPendingEventV2's already-stamped short-circuit
866
+ // preserves it (no new UUID). Kept pure + exported so the round-trip is unit-testable.
867
+
868
+ /** Read a CoordinatorIdentity off an untrusted wire object, or undefined if malformed. */
869
+ function readCoordinatorIdentityFromWire(raw: unknown): CoordinatorIdentity | undefined {
870
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
871
+ const obj = raw as Record<string, unknown>;
872
+ const daemonId = readNonEmptyString(obj.daemonId);
873
+ const coordinatorRunId = readNonEmptyString(obj.coordinatorRunId);
874
+ if (!daemonId || !coordinatorRunId) return undefined;
875
+ const sessionId = readNonEmptyString(obj.sessionId);
876
+ return { daemonId, coordinatorRunId, ...(sessionId ? { sessionId } : {}) };
877
+ }
878
+
879
+ /**
880
+ * Copy the v2 envelope fields that are present on `event` onto a flat wire
881
+ * payload. Only sets a field when it is present, so a v1 event contributes
882
+ * nothing (the payload stays v1-shaped and version-skew safe).
883
+ */
884
+ export function serializeV2EnvelopeToWire(event: PendingMeshCoordinatorEvent): Record<string, unknown> {
885
+ const out: Record<string, unknown> = {};
886
+ if (event.protocolVersion) out.protocolVersion = event.protocolVersion;
887
+ if (readNonEmptyString(event.eventId)) out.eventId = event.eventId;
888
+ if (event.scope) out.scope = event.scope;
889
+ if (event.dispatchedBy) out.dispatchedBy = event.dispatchedBy;
890
+ if (event.intendedFor) out.intendedFor = event.intendedFor;
891
+ return out;
892
+ }
893
+
894
+ /**
895
+ * Restore the v2 envelope fields from a flat wire payload for a re-queue. Only
896
+ * returns fields that survive validation; a payload missing/malforming a field
897
+ * yields a partial (or empty) object so the re-queue path stays v1-safe. The
898
+ * eventId is returned verbatim — its preservation is the idempotency guarantee.
899
+ */
900
+ export function readV2EnvelopeFromWire(payload: Record<string, unknown>): Partial<Pick<
901
+ PendingMeshCoordinatorEvent,
902
+ 'protocolVersion' | 'eventId' | 'scope' | 'dispatchedBy' | 'intendedFor'
903
+ >> {
904
+ const out: Partial<Pick<
905
+ PendingMeshCoordinatorEvent,
906
+ 'protocolVersion' | 'eventId' | 'scope' | 'dispatchedBy' | 'intendedFor'
907
+ >> = {};
908
+ if (payload.protocolVersion === MESH_PROTOCOL_VERSION_V2) out.protocolVersion = MESH_PROTOCOL_VERSION_V2;
909
+ const eventId = readNonEmptyString(payload.eventId);
910
+ if (eventId) out.eventId = eventId;
911
+ if (isMeshEventScope(payload.scope)) out.scope = payload.scope;
912
+ const dispatchedBy = readCoordinatorIdentityFromWire(payload.dispatchedBy);
913
+ if (dispatchedBy) out.dispatchedBy = dispatchedBy;
914
+ const intendedFor = readCoordinatorIdentityFromWire(payload.intendedFor);
915
+ if (intendedFor) out.intendedFor = intendedFor;
916
+ return out;
917
+ }
918
+
919
+ export function queuePendingMeshCoordinatorEvent(
920
+ rawEvent: PendingMeshCoordinatorEvent,
921
+ hint?: PendingEventEmitHint,
922
+ ): boolean {
923
+ // B2a: stamp the v2 envelope before dedup/persist so the eventId/scope ride
924
+ // into both stores and the fingerprint/dedup logic sees the final shape.
925
+ const event = stampPendingEventV2(rawEvent, hint);
926
+ return persistPendingMeshCoordinatorEvent(event);
927
+ }
928
+
929
+ /**
930
+ * Persist an ALREADY-STAMPED pending event to both stores (dedup + SQLite + JSONL),
931
+ * without re-running the emit stamp. queuePendingMeshCoordinatorEvent stamps then
932
+ * calls this; the only other caller is the test helper below, which needs to inject
933
+ * a genuinely-unversioned (v1) row to exercise the drain-side v1 handling now that
934
+ * the emit path never produces one (self-daemon fallback stamps every local emit).
935
+ */
936
+ function persistPendingMeshCoordinatorEvent(event: PendingMeshCoordinatorEvent): boolean {
937
+ try {
938
+ if (hasPendingRefineTerminalEventDuplicate(event)) {
939
+ LOG.info('MeshEvents', `Suppressed duplicate pending ${event.event} for refine job ${readRefineJobId(event)}`);
940
+ return true;
941
+ }
942
+ if (hasPendingCoordinatorEventDuplicate(event)) {
943
+ LOG.info('MeshEvents', `Suppressed duplicate pending ${event.event} for mesh ${event.meshId}`);
944
+ return true;
945
+ }
946
+
947
+ const fingerprint = buildPendingEventFingerprint(event);
948
+
949
+ // G3: Write to SQLite inbox (primary path going forward)
950
+ let sqliteOk = false;
951
+ try {
952
+ MeshRuntimeStore.getInstance().insertPendingEvent({
953
+ id: randomUUID(),
954
+ meshId: event.meshId,
955
+ coordinatorDaemonId: event.targetCoordinatorDaemonId ?? null,
956
+ event: event.event,
957
+ payload: event,
958
+ fingerprint: fingerprint || null,
959
+ queuedAt: event.queuedAt,
960
+ // v2 envelope columns (B2a) — all nullable so v1 rows coexist. The
961
+ // authoritative copy still rides inside `payload`; these columns exist
962
+ // for queryable idempotency (event_id) and scope-based drain filtering
963
+ // (scope / intended_for) without JSON-parsing every row.
964
+ protocolVersion: event.protocolVersion ?? null,
965
+ eventId: event.eventId ?? null,
966
+ scope: event.scope ?? null,
967
+ dispatchedBy: event.dispatchedBy ? JSON.stringify(event.dispatchedBy) : null,
968
+ intendedFor: event.intendedFor ? JSON.stringify(event.intendedFor) : null,
969
+ });
970
+ sqliteOk = true;
971
+ } catch {
972
+ // SQLite write failure is non-fatal; JSONL fallback below still works.
973
+ }
974
+
975
+ // Also write to JSONL (retained as legacy/export artifact). Best-effort once
976
+ // SQLite (the primary store) has the event: a JSONL append failure (disk full,
977
+ // permissions) must NOT report the whole persist as failed when SQLite holds it.
978
+ try {
979
+ const path = getPendingEventsPath(event.meshId, event.targetCoordinatorDaemonId);
980
+ trimPendingEventsIfNeeded(path);
981
+ appendFileSync(path, JSON.stringify(event) + '\n', 'utf-8');
982
+ } catch (e: any) {
983
+ if (!sqliteOk) throw e; // neither store has it — surface as a real failure
984
+ LOG.warn('MeshEvents', `JSONL append failed for mesh ${event.meshId}; SQLite holds the event: ${e?.message || e}`);
985
+ }
986
+ return true;
987
+ } catch (e: any) {
988
+ LOG.warn('MeshEvents', `Failed to persist pending coordinator event: ${e?.message || e}`);
989
+ return false;
990
+ }
991
+ }
992
+
993
+ // Atomically rename the file before reading so concurrent drains can't both consume
994
+ // the same events. renameSync is atomic on POSIX (same filesystem); only one caller
995
+ // wins the rename — the other gets ENOENT and returns null, preventing duplicate delivery.
996
+ function atomicDrainFile(path: string): string | null {
997
+ const tmpPath = `${path}.draining`;
998
+ try {
999
+ renameSync(path, tmpPath);
1000
+ } catch {
1001
+ return null; // another drain already renamed it, or file doesn't exist
1002
+ }
1003
+ try {
1004
+ const content = readFileSync(tmpPath, 'utf-8');
1005
+ try { unlinkSync(tmpPath); } catch { /* already cleaned up */ }
1006
+ return content;
1007
+ } catch {
1008
+ try { unlinkSync(tmpPath); } catch { /* best-effort cleanup */ }
1009
+ return null;
1010
+ }
1011
+ }
1012
+
1013
+ // Selectively drain a JSONL pending-events file: atomically claim it (rename), then
1014
+ // consume only the lines whose parsed event matches `predicate` and rewrite the
1015
+ // remaining (kept) lines back to the original path. Unparseable lines are kept
1016
+ // untouched. Returns the consumed events. The rename makes claiming exclusive —
1017
+ // only one concurrent caller wins, so there is no double-consume of the same lines.
1018
+ function selectiveDrainFile(
1019
+ path: string,
1020
+ predicate: (event: PendingMeshCoordinatorEvent) => boolean,
1021
+ ): PendingMeshCoordinatorEvent[] {
1022
+ const tmpPath = `${path}.draining`;
1023
+ try {
1024
+ renameSync(path, tmpPath);
1025
+ } catch {
1026
+ return []; // another drain claimed it, or the file doesn't exist
1027
+ }
1028
+ let content: string;
1029
+ try {
1030
+ content = readFileSync(tmpPath, 'utf-8');
1031
+ } catch {
1032
+ try { unlinkSync(tmpPath); } catch { /* best-effort */ }
1033
+ return [];
1034
+ }
1035
+
1036
+ const consumed: PendingMeshCoordinatorEvent[] = [];
1037
+ const keptLines: string[] = [];
1038
+ for (const line of content.split('\n')) {
1039
+ if (!line) continue;
1040
+ let parsed: PendingMeshCoordinatorEvent | undefined;
1041
+ try { parsed = JSON.parse(line) as PendingMeshCoordinatorEvent; } catch { parsed = undefined; }
1042
+ if (parsed && predicate(parsed)) {
1043
+ consumed.push(parsed);
1044
+ } else {
1045
+ keptLines.push(line); // non-matching or unparseable → leave queued
1046
+ }
1047
+ }
1048
+
1049
+ try {
1050
+ if (keptLines.length > 0) {
1051
+ writeFileSync(path, keptLines.join('\n') + '\n', 'utf-8');
1052
+ }
1053
+ unlinkSync(tmpPath);
1054
+ } catch {
1055
+ // If the rewrite/cleanup fails, restore the claimed file so no events are
1056
+ // lost — the next drain retries the whole file.
1057
+ try { if (existsSync(tmpPath) && !existsSync(path)) renameSync(tmpPath, path); } catch { /* best-effort */ }
1058
+ return [];
1059
+ }
1060
+ return consumed;
1061
+ }
1062
+
1063
+ /**
1064
+ * Drain and return pending coordinator events for meshId, removing the drained
1065
+ * ones from both the SQLite inbox and the JSONL legacy file.
1066
+ *
1067
+ * When `opts.onlyEvents` is supplied, ONLY events whose name is in that set are
1068
+ * drained; every other event stays queued (undrained in SQLite, rewritten back to
1069
+ * the JSONL file). The reconcile loop uses this to force-drain terminal/force-inject
1070
+ * events into a *generating* coordinator while leaving non-force progress events for
1071
+ * the coordinator's next idle transition. The atomic SQLite drained=1 marking and the
1072
+ * atomic JSONL rename keep force-drain and a concurrent full drain from double-consuming.
1073
+ */
1074
+ export function drainPendingMeshCoordinatorEvents(
1075
+ meshId?: string,
1076
+ coordinatorDaemonId?: string | ReadonlyArray<string>,
1077
+ opts?: { onlyEvents?: ReadonlySet<string>; drainerIdentity?: CoordinatorIdentity },
1078
+ ): PendingMeshCoordinatorEvent[] {
1079
+ if (!meshId) return [];
1080
+
1081
+ // A daemon may answer to more than one coordinator-id form (its canonical
1082
+ // status id like `standalone_<machineId>` AND the bare machineId). Normalise
1083
+ // to a list so both the SQLite IN-filter and the JSONL targeting predicate
1084
+ // accept any of them.
1085
+ const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
1086
+ const primaryDaemonId = daemonIds[0];
1087
+
1088
+ // B3a: the drainer's v2 identity, for unicast routing + eventId dedup. Derived
1089
+ // from the daemon ids the (untouchable) reconcile-loop already passes, so no
1090
+ // caller change is required; a caller may still pass the full identity.
1091
+ const drainer = resolveDrainerIdentity(daemonIds, opts?.drainerIdentity);
1092
+ // Snapshot the ALREADY-drained v2 eventIds BEFORE the SQLite drain marks this
1093
+ // batch drained=1 — the re-delivery dedup baseline. Reading it after would
1094
+ // self-match the batch's own rows.
1095
+ let priorDrainedEventIds = new Set<string>();
1096
+ try {
1097
+ priorDrainedEventIds = MeshRuntimeStore.getInstance().drainedEventIdsForMesh(meshId);
1098
+ } catch { /* store unavailable — no durable baseline; batch guard still applies */ }
1099
+
1100
+ const onlyEvents = opts?.onlyEvents;
1101
+ const matchesFilter = (eventName: string): boolean => !onlyEvents || onlyEvents.has(eventName);
1102
+
1103
+ // Dual-write means SQLite and JSONL hold the same events. Both stores must be
1104
+ // emptied in one drain call — draining only one leaves the other to re-deliver
1105
+ // the same events on the next call. Merge with fingerprint dedup.
1106
+ const merged: PendingMeshCoordinatorEvent[] = [];
1107
+ const seenFingerprints = new Set<string>();
1108
+ const pushUnique = (event: PendingMeshCoordinatorEvent) => {
1109
+ const fingerprint = buildPendingEventFingerprint(event);
1110
+ if (fingerprint.trim()) {
1111
+ if (seenFingerprints.has(fingerprint)) return;
1112
+ seenFingerprints.add(fingerprint);
1113
+ }
1114
+ merged.push(event);
1115
+ };
1116
+
1117
+ // G3: SQLite inbox
1118
+ try {
1119
+ const store = MeshRuntimeStore.getInstance();
1120
+ if (store.pendingEventCount(meshId) > 0) {
1121
+ for (const row of store.drainPendingEvents(meshId, daemonIds.length > 0 ? daemonIds : undefined, onlyEvents ? { onlyEvents } : undefined)) {
1122
+ const event = row.payload as PendingMeshCoordinatorEvent;
1123
+ if (event) pushUnique(event);
1124
+ }
1125
+ }
1126
+ } catch (e: any) {
1127
+ // SQLite drain failed — JSONL below still drains. Surface it: a silent
1128
+ // failure here means the JSONL copy is emptied while the SQLite rows
1129
+ // survive undrained, so the next drain re-delivers the same events to the
1130
+ // coordinator (duplicate refine:completed etc.) with no diagnostic trail.
1131
+ LOG.warn('MeshEvents', `SQLite pending-event drain failed for mesh ${meshId}; JSONL fallback only: ${e?.message || e}`);
1132
+ }
1133
+
1134
+ // JSONL (legacy / migration path) — always drained alongside SQLite.
1135
+ // The scoped per-daemon file is keyed by a single id; use the primary. The
1136
+ // shared (unscoped) file's targeting predicate accepts ANY of this daemon's ids.
1137
+ const paths = primaryDaemonId
1138
+ ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)]
1139
+ : [getPendingEventsPath(meshId)];
1140
+ for (const path of paths) {
1141
+ const isSharedFile = !!primaryDaemonId && path === getPendingEventsPath(meshId);
1142
+ // Targeting predicate for the shared (unscoped) file: only this coordinator's
1143
+ // events (or legacy untargeted ones) are eligible.
1144
+ const targets = (e: PendingMeshCoordinatorEvent): boolean =>
1145
+ !isSharedFile || !e.targetCoordinatorDaemonId || daemonIds.includes(e.targetCoordinatorDaemonId);
1146
+
1147
+ if (onlyEvents) {
1148
+ // Selective JSONL drain: consume only matching events, rewrite the rest back.
1149
+ for (const event of selectiveDrainFile(path, e => targets(e) && matchesFilter(e.event))) {
1150
+ pushUnique(event);
1151
+ }
1152
+ continue;
1153
+ }
1154
+ const content = atomicDrainFile(path);
1155
+ if (!content) continue;
1156
+ const parsed = content.split('\n').filter(Boolean).flatMap(line => {
1157
+ try { return [JSON.parse(line) as PendingMeshCoordinatorEvent]; } catch { return []; }
1158
+ });
1159
+ // If reading the shared file, filter to events that target this coordinator or are unscoped.
1160
+ const filtered = isSharedFile ? parsed.filter(targets) : parsed;
1161
+ for (const event of filtered) pushUnique(event);
1162
+ }
1163
+ if (merged.length === 0) return [];
1164
+ // (Former R3 direct-delivered dedup removed.) Spontaneous PTY direct-inject no
1165
+ // longer exists — delivery is now queue-drain-only (reconcile loop or MCP pull),
1166
+ // so an event is consumed by exactly one drainer via the atomic SQLite drained=1
1167
+ // marking. There is no PTY-vs-poll double path left to dedup against.
1168
+ //
1169
+ // B3a: v2 receive-side routing (accept-and-warn) — unicast targeting, eventId
1170
+ // idempotency, malformed-envelope pass-through-with-warn. v1 events broadcast.
1171
+ // Runs AFTER the merge/reconcile so a single eventId dedup batch covers both
1172
+ // stores. Non-destructive to v1 behaviour when no drainer identity is known.
1173
+ const routed = routeV2EventsForDrainer(merged, drainer, {
1174
+ alreadyDrained: (eventId) => priorDrainedEventIds.has(eventId),
1175
+ batchSeen: new Set<string>(),
1176
+ countMetrics: true,
1177
+ });
1178
+ return reconcilePendingMeshCoordinatorEvents(meshId, routed);
1179
+ }
1180
+
1181
+ /**
1182
+ * FALSE-BLOCKER-CLONE-QUEUE: retract any still-UNDELIVERED `mesh:dispatch_blocked`
1183
+ * actionable-skip event for a task whose blocker has since resolved (the task was
1184
+ * claimed, or its skip transitioned to a self-resolving transient reason). Without
1185
+ * this, a `target_node_id_unmatched` blocker paged during the brief clone/bootstrap
1186
+ * propagation window would linger in the coordinator's pending queue and surface as a
1187
+ * false "actionable blocker — will NOT clear on its own" even after the task dispatched.
1188
+ *
1189
+ * Only removes events that have NOT yet been drained/delivered to the coordinator — an
1190
+ * already-delivered message cannot be unsent, but de-dup re-arm (caller side) plus this
1191
+ * retraction guarantee no NEW stale blocker accumulates. Best-effort across both the
1192
+ * SQLite inbox and the JSONL legacy files (scoped + shared). Returns rows removed.
1193
+ */
1194
+ export function retractPendingDispatchBlockedEvent(
1195
+ meshId: string | undefined,
1196
+ taskId: string | undefined,
1197
+ coordinatorDaemonId?: string,
1198
+ ): number {
1199
+ if (!meshId || !taskId) return 0;
1200
+ let removed = 0;
1201
+ const matchesTask = (event: PendingMeshCoordinatorEvent | undefined): boolean => {
1202
+ if (!event || event.event !== 'mesh:dispatch_blocked') return false;
1203
+ const rowTaskId = readNonEmptyString((event.metadataEvent as Record<string, unknown> | undefined)?.taskId);
1204
+ return rowTaskId === taskId;
1205
+ };
1206
+
1207
+ // SQLite inbox: peek undrained rows for the mesh, hard-delete the matching ones by id.
1208
+ try {
1209
+ const store = MeshRuntimeStore.getInstance();
1210
+ const ids: string[] = [];
1211
+ for (const row of store.peekPendingEvents(meshId)) {
1212
+ if (row.event !== 'mesh:dispatch_blocked') continue;
1213
+ if (matchesTask(row.payload as PendingMeshCoordinatorEvent)) ids.push(row.id);
1214
+ }
1215
+ if (ids.length) removed += store.deletePendingEventsById(ids);
1216
+ } catch { /* best-effort — JSONL retraction below still runs */ }
1217
+
1218
+ // JSONL legacy files: selectively drop matching lines (rewrites the rest back).
1219
+ const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
1220
+ const primaryDaemonId = daemonIds[0];
1221
+ const paths = primaryDaemonId
1222
+ ? [getPendingEventsPath(meshId, primaryDaemonId), getPendingEventsPath(meshId)]
1223
+ : [getPendingEventsPath(meshId)];
1224
+ for (const path of paths) {
1225
+ try {
1226
+ removed += selectiveDrainFile(path, matchesTask).length;
1227
+ } catch { /* best-effort */ }
1228
+ }
1229
+ return removed;
1230
+ }
1231
+
1232
+ /** Peek at pending coordinator events without draining (non-destructive). */
1233
+ export function getPendingMeshCoordinatorEvents(
1234
+ meshId?: string,
1235
+ coordinatorDaemonId?: string | ReadonlyArray<string>,
1236
+ opts?: { drainerIdentity?: CoordinatorIdentity },
1237
+ ): readonly PendingMeshCoordinatorEvent[] {
1238
+ if (!meshId) return [];
1239
+ const daemonIds = normalizeCoordinatorDaemonIds(coordinatorDaemonId);
1240
+ // B3a: same v2 routing the destructive drain applies, so a peek (mesh_status
1241
+ // count, reconcile pre-check) sees the SAME set the drain would deliver — a
1242
+ // unicast event for another coordinator is not counted for this one.
1243
+ const drainer = resolveDrainerIdentity(daemonIds, opts?.drainerIdentity);
1244
+ let priorDrainedEventIds = new Set<string>();
1245
+ try {
1246
+ priorDrainedEventIds = MeshRuntimeStore.getInstance().drainedEventIdsForMesh(meshId);
1247
+ } catch { /* store unavailable — batch guard still applies */ }
1248
+
1249
+ // Merge SQLite (primary) + JSONL (legacy) with fingerprint dedup.
1250
+ const merged: PendingMeshCoordinatorEvent[] = [];
1251
+ const seenFingerprints = new Set<string>();
1252
+ const pushUnique = (event: PendingMeshCoordinatorEvent) => {
1253
+ const fingerprint = buildPendingEventFingerprint(event);
1254
+ if (fingerprint.trim()) {
1255
+ if (seenFingerprints.has(fingerprint)) return;
1256
+ seenFingerprints.add(fingerprint);
1257
+ }
1258
+ merged.push(event);
1259
+ };
1260
+
1261
+ // G3: SQLite inbox (non-destructive peek at undrained rows)
1262
+ try {
1263
+ const store = MeshRuntimeStore.getInstance();
1264
+ if (store.pendingEventCount(meshId) > 0) {
1265
+ for (const row of store.peekPendingEvents(meshId, daemonIds.length > 0 ? daemonIds : undefined)) {
1266
+ const event = row.payload as PendingMeshCoordinatorEvent;
1267
+ if (event) pushUnique(event);
1268
+ }
1269
+ }
1270
+ } catch { /* SQLite unavailable — JSONL fallback below */ }
1271
+
1272
+ // JSONL (legacy)
1273
+ for (const event of readPendingMeshCoordinatorEventsFromDisk(meshId, daemonIds)) {
1274
+ pushUnique(event);
1275
+ }
1276
+
1277
+ // (Former R3 direct-delivered filter removed — no PTY direct-inject path exists
1278
+ // anymore, so a peeked pending event has genuinely not yet been consumed.)
1279
+ // B3a: apply the SAME v2 routing the drain applies (non-destructive: no counter
1280
+ // inflation on the frequent status-poll path).
1281
+ const routed = routeV2EventsForDrainer(merged, drainer, {
1282
+ alreadyDrained: (eventId) => priorDrainedEventIds.has(eventId),
1283
+ batchSeen: new Set<string>(),
1284
+ countMetrics: false,
1285
+ });
1286
+ return reconcilePendingMeshCoordinatorEvents(meshId, routed);
1287
+ }
1288
+
1289
+ /**
1290
+ * Test helper: purge all pending-event state for a mesh — SQLite rows
1291
+ * (including drained fingerprint history) and JSONL files.
1292
+ */
1293
+ export function __clearMeshPendingEventsForTests(meshId: string): void {
1294
+ try {
1295
+ MeshRuntimeStore.getInstance().clearPendingEventsForMesh(meshId);
1296
+ } catch { /* store unavailable — nothing to clear */ }
1297
+ clearPendingMeshCoordinatorEvents(meshId);
1298
+ }
1299
+
1300
+ /**
1301
+ * Test helper: persist a pending event VERBATIM, skipping the emit-time v2 stamp.
1302
+ * The local emit path (queuePendingMeshCoordinatorEvent → stampPendingEventV2) now
1303
+ * always mints a v2 envelope (self-daemon broadcast fallback when no coordinator
1304
+ * identity is present), so a genuinely-unversioned (v1) row can no longer be produced
1305
+ * through the normal queue. The drain-side v1 handling (accept-broadcast / enforce-
1306
+ * quarantine) still matters for durable v1 rows written by a pre-v2 daemon and for
1307
+ * version-skewed remote relays, so tests inject those rows directly through this.
1308
+ */
1309
+ export function __persistUnstampedPendingEventForTests(event: PendingMeshCoordinatorEvent): boolean {
1310
+ return persistPendingMeshCoordinatorEvent(event);
1311
+ }
1312
+
1313
+ // ---------------------------------------------------------------------------
1314
+ // event_held → pending requeue (T6 recovery path)
1315
+ // ---------------------------------------------------------------------------
1316
+ // T6 quarantine (v2 enforce) and the pending-events trim both mirror a
1317
+ // destructively-drained-but-undelivered event into the ledger as a recoverable
1318
+ // `event_held` entry. Until now that recovery channel was audit-only: the comment
1319
+ // said "an operator can requeue it" but no code path did. This restores those held
1320
+ // events to the pending queue so a coordinator drains them on its next poll.
1321
+ //
1322
+ // No-loss + no-double-requeue invariants:
1323
+ // • The full original event rides on the held payload as `heldEvent`, so the
1324
+ // restore is byte-for-byte (metadataEvent, coordinatorMessage, v2 envelope).
1325
+ // • queuePendingMeshCoordinatorEvent runs the normal dedup (fingerprint / eventId),
1326
+ // so an event still live in the queue is not duplicated.
1327
+ // • Every held entry that has ALREADY been requeued is marked with an
1328
+ // `event_held_requeued` ledger entry keyed by the source held-entry id; a later
1329
+ // pass skips those ids, so calling the tool twice does not requeue the same held
1330
+ // event twice.
1331
+
1332
+ /** Narrowing filter for {@link requeueHeldMeshCoordinatorEvents}, scoped within one mesh. */
1333
+ export interface MeshHeldEventRequeueFilter {
1334
+ /** Restore only held events whose worker task id matches (from the held event's metadata/taskId). */
1335
+ taskId?: string;
1336
+ /** Restore only held events originating from this node. */
1337
+ nodeId?: string;
1338
+ /** Restore only held events of this event name (e.g. 'session:completed'). */
1339
+ event?: string;
1340
+ /** Restore only held entries recorded at/after this ISO timestamp. */
1341
+ since?: string;
1342
+ /** Restore only held entries with this hold reason (e.g. 'pending_trim_dropped'). */
1343
+ reason?: string;
1344
+ }
1345
+
1346
+ export interface MeshHeldEventRequeueResult {
1347
+ meshId: string;
1348
+ /** event_held entries considered after the filter. */
1349
+ matched: number;
1350
+ /** entries skipped because a prior requeue already recovered them. */
1351
+ alreadyRequeued: number;
1352
+ /** entries skipped because they carried no restorable original event / were not recoverable. */
1353
+ unrecoverable: number;
1354
+ /** entries handed to the pending queue (some may have been dedup-suppressed downstream). */
1355
+ requeued: number;
1356
+ /** of `requeued`, how many the pending-queue dedup collapsed onto a live event. */
1357
+ dedupSuppressed: number;
1358
+ entries: Array<{
1359
+ heldEntryId: string;
1360
+ event: string;
1361
+ nodeId?: string;
1362
+ taskId?: string;
1363
+ reason?: string;
1364
+ outcome: 'requeued' | 'already_requeued' | 'unrecoverable';
1365
+ }>;
1366
+ }
1367
+
1368
+ /** Read the taskId a held event carried, checking the restored event then the audit payload. */
1369
+ function readHeldTaskId(restored: PendingMeshCoordinatorEvent | undefined, payload: Record<string, unknown>): string {
1370
+ const fromMeta = restored?.metadataEvent && typeof restored.metadataEvent === 'object'
1371
+ ? readNonEmptyString((restored.metadataEvent as Record<string, unknown>).taskId)
1372
+ : '';
1373
+ return fromMeta || readNonEmptyString(payload.taskId) || '';
1374
+ }
1375
+
1376
+ /**
1377
+ * Restore recoverable `event_held` ledger entries back to the pending coordinator
1378
+ * queue for `meshId`. See the block comment above for the no-loss / no-double-requeue
1379
+ * invariants. Returns per-entry outcomes for the caller to surface.
1380
+ */
1381
+ export function requeueHeldMeshCoordinatorEvents(
1382
+ meshId: string,
1383
+ filter?: MeshHeldEventRequeueFilter,
1384
+ ): MeshHeldEventRequeueResult {
1385
+ const result: MeshHeldEventRequeueResult = {
1386
+ meshId,
1387
+ matched: 0,
1388
+ alreadyRequeued: 0,
1389
+ unrecoverable: 0,
1390
+ requeued: 0,
1391
+ dedupSuppressed: 0,
1392
+ entries: [],
1393
+ };
1394
+
1395
+ const all = readLedgerEntries(meshId);
1396
+ // held-entry ids already recovered by a prior requeue pass (dedup key = source id).
1397
+ const requeuedIds = new Set<string>();
1398
+ for (const entry of all) {
1399
+ if (entry.kind !== 'event_held_requeued') continue;
1400
+ const id = readNonEmptyString(entry.payload?.heldEntryId);
1401
+ if (id) requeuedIds.add(id);
1402
+ }
1403
+
1404
+ const sinceMs = filter?.since ? new Date(filter.since).getTime() : NaN;
1405
+ const wantEvent = readNonEmptyString(filter?.event);
1406
+ const wantNode = readNonEmptyString(filter?.nodeId);
1407
+ const wantTask = readNonEmptyString(filter?.taskId);
1408
+ const wantReason = readNonEmptyString(filter?.reason);
1409
+
1410
+ for (const entry of all) {
1411
+ if (entry.kind !== 'event_held') continue;
1412
+ const payload = (entry.payload && typeof entry.payload === 'object') ? entry.payload : {};
1413
+ if (payload.recoverable !== true) continue;
1414
+
1415
+ // Reconstruct the original event: prefer the full `heldEvent` copy; fall back to
1416
+ // the flat audit fields for entries written before the copy was embedded.
1417
+ const restored: PendingMeshCoordinatorEvent | undefined =
1418
+ (payload.heldEvent && typeof payload.heldEvent === 'object')
1419
+ ? { ...(payload.heldEvent as PendingMeshCoordinatorEvent) }
1420
+ : undefined;
1421
+
1422
+ const eventName = restored?.event || readNonEmptyString(payload.event);
1423
+ const nodeId = restored?.nodeId || entry.nodeId || readNonEmptyString((payload as any).nodeId) || undefined;
1424
+ const taskId = readHeldTaskId(restored, payload as Record<string, unknown>);
1425
+ const reason = readNonEmptyString(payload.reason) || undefined;
1426
+
1427
+ // Apply the caller filter within the mesh scope.
1428
+ if (wantEvent && eventName !== wantEvent) continue;
1429
+ if (wantNode && nodeId !== wantNode) continue;
1430
+ if (wantTask && taskId !== wantTask) continue;
1431
+ if (wantReason && reason !== wantReason) continue;
1432
+ if (filter?.since && !Number.isNaN(sinceMs) && new Date(entry.timestamp).getTime() < sinceMs) continue;
1433
+
1434
+ result.matched++;
1435
+
1436
+ if (requeuedIds.has(entry.id)) {
1437
+ result.alreadyRequeued++;
1438
+ result.entries.push({ heldEntryId: entry.id, event: eventName, ...(nodeId ? { nodeId } : {}), ...(taskId ? { taskId } : {}), ...(reason ? { reason } : {}), outcome: 'already_requeued' });
1439
+ continue;
1440
+ }
1441
+
1442
+ if (!restored || !readNonEmptyString(restored.event) || !readNonEmptyString(restored.meshId)) {
1443
+ result.unrecoverable++;
1444
+ result.entries.push({ heldEntryId: entry.id, event: eventName, ...(nodeId ? { nodeId } : {}), ...(taskId ? { taskId } : {}), ...(reason ? { reason } : {}), outcome: 'unrecoverable' });
1445
+ continue;
1446
+ }
1447
+
1448
+ // Restore to pending. queuePendingMeshCoordinatorEvent re-stamps/dedups; a live
1449
+ // duplicate is suppressed there (returns true) so we never double-deliver.
1450
+ const beforeDup = hasPendingCoordinatorEventDuplicate(restored);
1451
+ let ok = false;
1452
+ try {
1453
+ ok = queuePendingMeshCoordinatorEvent(restored);
1454
+ } catch (e: any) {
1455
+ LOG.warn('MeshEvents', `Requeue of held ${eventName} for mesh ${meshId} failed: ${e?.message || e}`);
1456
+ }
1457
+
1458
+ // Mark the source held entry so a second pass skips it, regardless of whether the
1459
+ // queue dedup collapsed it (the recovery attempt is what we dedup on, not delivery).
1460
+ appendLedgerEntry(meshId, {
1461
+ kind: 'event_held_requeued',
1462
+ ...(nodeId ? { nodeId } : {}),
1463
+ payload: {
1464
+ heldEntryId: entry.id,
1465
+ event: eventName,
1466
+ requeued: ok,
1467
+ ...(taskId ? { taskId } : {}),
1468
+ ...(reason ? { reason } : {}),
1469
+ ...(beforeDup ? { dedupSuppressed: true } : {}),
1470
+ },
1471
+ });
1472
+ requeuedIds.add(entry.id);
1473
+
1474
+ result.requeued++;
1475
+ if (beforeDup) result.dedupSuppressed++;
1476
+ result.entries.push({ heldEntryId: entry.id, event: eventName, ...(nodeId ? { nodeId } : {}), ...(taskId ? { taskId } : {}), ...(reason ? { reason } : {}), outcome: 'requeued' });
1477
+ }
1478
+
1479
+ return result;
1480
+ }
1481
+
1482
+ /** Explicitly clear all pending coordinator events for a mesh (and coordinator if scoped). */
1483
+ export function clearPendingMeshCoordinatorEvents(meshId?: string, coordinatorDaemonId?: string): void {
1484
+ if (!meshId) return;
1485
+ // Clear SQLite rows
1486
+ try { MeshRuntimeStore.getInstance().clearPendingEventsForMesh(meshId); } catch { /* store unavailable */ }
1487
+ // Clear JSONL files
1488
+ const paths = coordinatorDaemonId
1489
+ ? [getPendingEventsPath(meshId, coordinatorDaemonId), getPendingEventsPath(meshId)]
1490
+ : [getPendingEventsPath(meshId)];
1491
+ for (const path of paths) {
1492
+ if (existsSync(path)) try { unlinkSync(path); } catch { /* already removed */ }
1493
+ }
1494
+ }