@adhdev/daemon-core 0.9.82-rc.35 → 0.9.82-rc.350

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 (318) hide show
  1. package/dist/boot/daemon-lifecycle.d.ts +8 -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 +46 -2
  8. package/dist/cli-adapters/cli-script-runner.d.ts +117 -0
  9. package/dist/cli-adapters/cli-state-engine.d.ts +198 -0
  10. package/dist/cli-adapters/provider-cli-adapter.d.ts +116 -64
  11. package/dist/cli-adapters/provider-cli-parse.d.ts +4 -0
  12. package/dist/cli-adapters/provider-cli-runtime.d.ts +34 -0
  13. package/dist/cli-adapters/provider-cli-shared.d.ts +53 -0
  14. package/dist/cli-adapters/raw-terminal-io.d.ts +37 -0
  15. package/dist/cli-adapters/resolve-executable.d.ts +14 -0
  16. package/dist/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +6 -3
  17. package/dist/cli-adapters/terminal-backends/types.d.ts +10 -2
  18. package/dist/cli-adapters/terminal-screen.d.ts +4 -11
  19. package/dist/commands/cli-manager.d.ts +2 -1
  20. package/dist/commands/handler.d.ts +110 -0
  21. package/dist/commands/mesh-coordinator.d.ts +85 -1
  22. package/dist/commands/router.d.ts +324 -1
  23. package/dist/commands/upgrade-helper.d.ts +12 -0
  24. package/dist/config/chat-history.d.ts +9 -0
  25. package/dist/config/config.d.ts +5 -0
  26. package/dist/config/mesh-config.d.ts +77 -1
  27. package/dist/detection/ide-detector.d.ts +13 -0
  28. package/dist/detection/win32-ide-version.d.ts +37 -0
  29. package/dist/git/change-impact-config.d.ts +159 -0
  30. package/dist/git/git-commands.d.ts +11 -1
  31. package/dist/git/git-diff.d.ts +6 -0
  32. package/dist/git/git-executor.d.ts +11 -0
  33. package/dist/git/git-status.d.ts +23 -0
  34. package/dist/git/git-types.d.ts +2 -50
  35. package/dist/git/index.d.ts +2 -0
  36. package/dist/index.d.ts +52 -13
  37. package/dist/index.js +39739 -14302
  38. package/dist/index.js.map +1 -1
  39. package/dist/index.mjs +41369 -16055
  40. package/dist/index.mjs.map +1 -1
  41. package/dist/installer.d.ts +1 -4
  42. package/dist/ipc/local-ipc-server.d.ts +91 -0
  43. package/dist/launch.d.ts +1 -1
  44. package/dist/logging/async-batch-writer.d.ts +10 -0
  45. package/dist/logging/log-redactor.d.ts +24 -0
  46. package/dist/logging/log-tail-reader.d.ts +46 -0
  47. package/dist/mesh/contracts.d.ts +164 -0
  48. package/dist/mesh/coordinator-prompt.d.ts +36 -0
  49. package/dist/mesh/coordinator-registry.d.ts +59 -0
  50. package/dist/mesh/mesh-active-work.d.ts +174 -0
  51. package/dist/mesh/mesh-delivery-policy.d.ts +131 -0
  52. package/dist/mesh/mesh-events-coordinator.d.ts +169 -0
  53. package/dist/mesh/mesh-events-pending.d.ts +55 -0
  54. package/dist/mesh/mesh-events-stale.d.ts +40 -0
  55. package/dist/mesh/mesh-events-utils.d.ts +62 -0
  56. package/dist/mesh/mesh-events.d.ts +6 -49
  57. package/dist/mesh/mesh-fast-forward.d.ts +81 -0
  58. package/dist/mesh/mesh-host-ownership.d.ts +9 -0
  59. package/dist/mesh/mesh-init.d.ts +86 -0
  60. package/dist/mesh/mesh-ledger-reconciliation.d.ts +23 -3
  61. package/dist/mesh/mesh-ledger.d.ts +77 -1
  62. package/dist/mesh/mesh-missions.d.ts +164 -0
  63. package/dist/mesh/mesh-reconcile-loop.d.ts +7 -0
  64. package/dist/mesh/mesh-refine-batch.d.ts +68 -0
  65. package/dist/mesh/mesh-refine-status.d.ts +62 -0
  66. package/dist/mesh/mesh-review-inbox.d.ts +90 -0
  67. package/dist/mesh/mesh-routing.d.ts +70 -0
  68. package/dist/mesh/mesh-runtime-store.d.ts +419 -0
  69. package/dist/mesh/mesh-task-stats.d.ts +49 -0
  70. package/dist/mesh/mesh-unresolved-forward-outbox.d.ts +30 -0
  71. package/dist/mesh/mesh-work-queue.d.ts +218 -5
  72. package/dist/mesh/preview-freshness.d.ts +18 -0
  73. package/dist/mesh/refine-config.d.ts +216 -0
  74. package/dist/mesh/worktree-bootstrap-config.d.ts +135 -0
  75. package/dist/providers/acp-provider-instance.d.ts +2 -0
  76. package/dist/providers/approval-utils.d.ts +13 -0
  77. package/dist/providers/chat-message-normalization.d.ts +12 -0
  78. package/dist/providers/cli-provider-instance.d.ts +77 -3
  79. package/dist/providers/contracts.d.ts +139 -6
  80. package/dist/providers/external-sources.d.ts +71 -0
  81. package/dist/providers/native-history/antigravity-cli-transcript.d.ts +100 -0
  82. package/dist/providers/native-history/claude-cli-transcript.d.ts +70 -0
  83. package/dist/providers/native-history/codex-cli-transcript.d.ts +73 -0
  84. package/dist/providers/native-history/dispatcher.d.ts +27 -0
  85. package/dist/providers/native-history/hermes-cli-transcript.d.ts +30 -0
  86. package/dist/providers/native-history/index.d.ts +13 -0
  87. package/dist/providers/provider-instance-manager.d.ts +14 -0
  88. package/dist/providers/provider-instance.d.ts +15 -1
  89. package/dist/providers/provider-loader.d.ts +26 -4
  90. package/dist/providers/provider-trust.d.ts +31 -0
  91. package/dist/providers/read-chat-contract.d.ts +29 -0
  92. package/dist/providers/sdk/v1/builders/acp/detect-status.d.ts +68 -0
  93. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +85 -0
  94. package/dist/providers/sdk/v1/builders/cli/parse-approval-squash.d.ts +59 -0
  95. package/dist/providers/sdk/v1/builders/cli/parse-approval.d.ts +65 -0
  96. package/dist/providers/sdk/v1/builders/cli/parse-session.d.ts +91 -0
  97. package/dist/providers/sdk/v1/builders/cli/visible-region.d.ts +42 -0
  98. package/dist/providers/sdk/v1/fixture-tooling/format.d.ts +126 -0
  99. package/dist/providers/sdk/v1/fixture-tooling/index.d.ts +8 -0
  100. package/dist/providers/sdk/v1/fixture-tooling/replay.d.ts +38 -0
  101. package/dist/providers/sdk/v1/index.d.ts +30 -0
  102. package/dist/providers/sdk/v1/sandbox/README-design.d.ts +193 -0
  103. package/dist/providers/sdk/v1/sandbox/require-whitelist.d.ts +74 -0
  104. package/dist/providers/sdk/v1/sandbox/script-runner.d.ts +98 -0
  105. package/dist/providers/sdk/v1/types/cli/index.d.ts +277 -0
  106. package/dist/providers/sdk/v1/types/common/index.d.ts +203 -0
  107. package/dist/providers/sdk/v1/validators/index.d.ts +5 -0
  108. package/dist/providers/sdk/v1/validators/manifest.d.ts +40 -0
  109. package/dist/providers/sdk/v1/validators/taint.d.ts +52 -0
  110. package/dist/providers/spec/adapter.d.ts +69 -0
  111. package/dist/providers/spec/cli-adapter.d.ts +217 -0
  112. package/dist/providers/spec/evaluator.d.ts +23 -0
  113. package/dist/providers/spec/fsm-driver.d.ts +322 -0
  114. package/dist/providers/spec/fsm-evaluator.d.ts +72 -0
  115. package/dist/providers/spec/fsm-loader.d.ts +14 -0
  116. package/dist/providers/spec/fsm-types.d.ts +144 -0
  117. package/dist/providers/spec/native-history-executor.d.ts +41 -0
  118. package/dist/providers/spec/pre-launch-trust.d.ts +16 -0
  119. package/dist/providers/spec/route.d.ts +4 -0
  120. package/dist/providers/spec/types.d.ts +180 -0
  121. package/dist/providers/status-monitor.d.ts +7 -7
  122. package/dist/providers/transcript-v2.d.ts +176 -0
  123. package/dist/providers/types/interactive-prompt.d.ts +84 -0
  124. package/dist/providers/working-dir.d.ts +17 -0
  125. package/dist/repo-mesh-types.d.ts +295 -13
  126. package/dist/sessions/registry.d.ts +6 -0
  127. package/dist/shared-types-extra.d.ts +2 -4
  128. package/dist/shared-types.d.ts +59 -2
  129. package/dist/status/normalize.d.ts +1 -1
  130. package/dist/status/normalize.js +1 -0
  131. package/dist/status/normalize.js.map +1 -1
  132. package/dist/status/normalize.mjs +1 -0
  133. package/dist/status/normalize.mjs.map +1 -1
  134. package/dist/status/reporter.d.ts +2 -0
  135. package/dist/status/snapshot.d.ts +26 -0
  136. package/dist/system/load-better-sqlite3.d.ts +21 -0
  137. package/dist/types.d.ts +5 -0
  138. package/package.json +7 -3
  139. package/src/agent-stream/poller.ts +2 -3
  140. package/src/agent-stream/provider-adapter.ts +1 -1
  141. package/src/boot/daemon-lifecycle.ts +55 -12
  142. package/src/boot/process-hardening.ts +89 -0
  143. package/src/build-info.ts +73 -0
  144. package/src/chat/source-machine.ts +534 -0
  145. package/src/chat/source-resolver.ts +0 -0
  146. package/src/chat/subscription-updates.ts +20 -1
  147. package/src/cli-adapter-types.d.ts +1 -0
  148. package/src/cli-adapter-types.ts +47 -2
  149. package/src/cli-adapters/cli-script-runner.ts +421 -0
  150. package/src/cli-adapters/cli-state-engine.ts +1215 -0
  151. package/src/cli-adapters/provider-cli-adapter.d.ts +1 -1
  152. package/src/cli-adapters/provider-cli-adapter.ts +774 -1141
  153. package/src/cli-adapters/provider-cli-parse.d.ts +1 -0
  154. package/src/cli-adapters/provider-cli-parse.ts +13 -0
  155. package/src/cli-adapters/provider-cli-runtime.ts +56 -7
  156. package/src/cli-adapters/provider-cli-shared.d.ts +4 -0
  157. package/src/cli-adapters/provider-cli-shared.ts +100 -11
  158. package/src/cli-adapters/pty-transport.ts +2 -1
  159. package/src/cli-adapters/raw-terminal-io.ts +252 -0
  160. package/src/cli-adapters/resolve-executable.ts +90 -0
  161. package/src/cli-adapters/session-host-transport.ts +2 -1
  162. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.ts +53 -29
  163. package/src/cli-adapters/terminal-backends/types.ts +10 -3
  164. package/src/cli-adapters/terminal-screen.ts +16 -81
  165. package/src/commands/chat-commands.ts +1823 -62
  166. package/src/commands/cli-manager.ts +304 -14
  167. package/src/commands/handler.ts +809 -2
  168. package/src/commands/mesh-coordinator.ts +332 -122
  169. package/src/commands/router.ts +7505 -1311
  170. package/src/commands/stream-commands.ts +8 -0
  171. package/src/commands/upgrade-helper.ts +81 -30
  172. package/src/config/chat-history.ts +483 -24
  173. package/src/config/config.ts +12 -0
  174. package/src/config/mesh-config.ts +388 -6
  175. package/src/config/recent-activity.ts +8 -2
  176. package/src/daemon/dev-auto-implement.ts +3 -2
  177. package/src/daemon/dev-cli-debug.ts +10 -1
  178. package/src/detection/cli-detector.ts +28 -9
  179. package/src/detection/ide-detector.ts +55 -16
  180. package/src/detection/win32-ide-version.ts +106 -0
  181. package/src/git/change-impact-config.ts +354 -0
  182. package/src/git/git-commands.ts +55 -14
  183. package/src/git/git-diff.ts +53 -0
  184. package/src/git/git-executor.ts +12 -0
  185. package/src/git/git-status.ts +574 -43
  186. package/src/git/git-types.ts +14 -62
  187. package/src/git/git-worktree.ts +8 -1
  188. package/src/git/index.ts +16 -0
  189. package/src/index.ts +146 -12
  190. package/src/installer.d.ts +1 -1
  191. package/src/installer.ts +8 -6
  192. package/src/ipc/local-ipc-server.ts +278 -0
  193. package/src/launch.d.ts +1 -1
  194. package/src/launch.ts +37 -28
  195. package/src/logging/async-batch-writer.ts +55 -0
  196. package/src/logging/log-redactor.ts +100 -0
  197. package/src/logging/log-tail-reader.ts +220 -0
  198. package/src/logging/logger.ts +2 -1
  199. package/src/mesh/contracts.ts +329 -0
  200. package/src/mesh/coordinator-prompt.ts +234 -31
  201. package/src/mesh/coordinator-registry.ts +121 -0
  202. package/src/mesh/mesh-active-work.ts +623 -0
  203. package/src/mesh/mesh-delivery-policy.ts +315 -0
  204. package/src/mesh/mesh-events-coordinator.ts +2224 -0
  205. package/src/mesh/mesh-events-pending.ts +558 -0
  206. package/src/mesh/mesh-events-stale.ts +290 -0
  207. package/src/mesh/mesh-events-utils.ts +381 -0
  208. package/src/mesh/mesh-events.ts +30 -1035
  209. package/src/mesh/mesh-fast-forward.ts +839 -0
  210. package/src/mesh/mesh-host-ownership.ts +73 -0
  211. package/src/mesh/mesh-init.ts +260 -0
  212. package/src/mesh/mesh-ledger-reconciliation.ts +12 -5
  213. package/src/mesh/mesh-ledger.ts +590 -102
  214. package/src/mesh/mesh-missions.ts +322 -0
  215. package/src/mesh/mesh-reconcile-loop.ts +989 -0
  216. package/src/mesh/mesh-refine-batch.ts +197 -0
  217. package/src/mesh/mesh-refine-status.ts +231 -0
  218. package/src/mesh/mesh-review-inbox.ts +307 -0
  219. package/src/mesh/mesh-routing.ts +291 -0
  220. package/src/mesh/mesh-runtime-store.ts +1660 -0
  221. package/src/mesh/mesh-task-stats.ts +154 -0
  222. package/src/mesh/mesh-unresolved-forward-outbox.ts +185 -0
  223. package/src/mesh/mesh-work-queue.ts +901 -141
  224. package/src/mesh/preview-freshness.ts +118 -0
  225. package/src/mesh/refine-config.ts +423 -0
  226. package/src/mesh/worktree-bootstrap-config.ts +331 -0
  227. package/src/providers/acp-provider-instance.ts +25 -9
  228. package/src/providers/approval-utils.d.ts +4 -0
  229. package/src/providers/approval-utils.ts +47 -5
  230. package/src/providers/chat-message-normalization.ts +45 -5
  231. package/src/providers/cli-provider-instance.ts +1041 -99
  232. package/src/providers/contracts.d.ts +55 -0
  233. package/src/providers/contracts.ts +150 -6
  234. package/src/providers/extension-provider-instance.ts +12 -7
  235. package/src/providers/external-sources.ts +218 -0
  236. package/src/providers/ide-provider-instance.ts +35 -12
  237. package/src/providers/native-history/antigravity-cli-transcript.ts +643 -0
  238. package/src/providers/native-history/claude-cli-transcript.ts +396 -0
  239. package/src/providers/native-history/codex-cli-transcript.ts +479 -0
  240. package/src/providers/native-history/dispatcher.ts +340 -0
  241. package/src/providers/native-history/hermes-cli-transcript.ts +230 -0
  242. package/src/providers/native-history/index.ts +30 -0
  243. package/src/providers/provider-instance-manager.ts +30 -0
  244. package/src/providers/provider-instance.ts +10 -1
  245. package/src/providers/provider-loader.ts +670 -50
  246. package/src/providers/provider-schema.ts +87 -14
  247. package/src/providers/provider-trust.ts +114 -0
  248. package/src/providers/read-chat-contract.ts +76 -16
  249. package/src/providers/sdk/README.md +49 -0
  250. package/src/providers/sdk/v1/builders/acp/detect-status.ts +144 -0
  251. package/src/providers/sdk/v1/builders/cli/detect-status.ts +262 -0
  252. package/src/providers/sdk/v1/builders/cli/parse-approval-squash.ts +158 -0
  253. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +250 -0
  254. package/src/providers/sdk/v1/builders/cli/parse-session.ts +276 -0
  255. package/src/providers/sdk/v1/builders/cli/visible-region.ts +143 -0
  256. package/src/providers/sdk/v1/fixture-tooling/format.ts +130 -0
  257. package/src/providers/sdk/v1/fixture-tooling/index.ts +22 -0
  258. package/src/providers/sdk/v1/fixture-tooling/replay.ts +352 -0
  259. package/src/providers/sdk/v1/index.ts +152 -0
  260. package/src/providers/sdk/v1/sandbox/README-design.ts +195 -0
  261. package/src/providers/sdk/v1/sandbox/require-whitelist.ts +472 -0
  262. package/src/providers/sdk/v1/sandbox/script-runner.ts +150 -0
  263. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +504 -0
  264. package/src/providers/sdk/v1/schemas/primitives/acp-session-protocol-v1.json +131 -0
  265. package/src/providers/sdk/v1/schemas/primitives/native-history-codex-rollout-v1.json +66 -0
  266. package/src/providers/sdk/v1/schemas/primitives/tui-approval-squash-v1.json +91 -0
  267. package/src/providers/sdk/v1/schemas/primitives/tui-assistant-block-v1.json +91 -0
  268. package/src/providers/sdk/v1/schemas/primitives/tui-cue-ordering-v1.json +47 -0
  269. package/src/providers/sdk/v1/schemas/primitives/tui-dispatch-order-v1.json +32 -0
  270. package/src/providers/sdk/v1/schemas/primitives/tui-footer-chrome-v1.json +42 -0
  271. package/src/providers/sdk/v1/schemas/primitives/tui-index-finder-v1.json +27 -0
  272. package/src/providers/sdk/v1/schemas/primitives/tui-modal-v1.json +125 -0
  273. package/src/providers/sdk/v1/schemas/primitives/tui-prompt-marker-v1.json +45 -0
  274. package/src/providers/sdk/v1/schemas/primitives/tui-session-id-extraction-v1.json +46 -0
  275. package/src/providers/sdk/v1/schemas/primitives/tui-settled-prompt-v1.json +71 -0
  276. package/src/providers/sdk/v1/schemas/primitives/tui-spinner-v1.json +83 -0
  277. package/src/providers/sdk/v1/schemas/primitives/tui-transcript-pty-v1.json +83 -0
  278. package/src/providers/sdk/v1/schemas/primitives/tui-visible-region-v1.json +57 -0
  279. package/src/providers/sdk/v1/schemas/primitives/tui-welcome-screen-v1.json +35 -0
  280. package/src/providers/sdk/v1/types/cli/index.ts +365 -0
  281. package/src/providers/sdk/v1/types/common/index.ts +229 -0
  282. package/src/providers/sdk/v1/validators/index.ts +19 -0
  283. package/src/providers/sdk/v1/validators/manifest.ts +110 -0
  284. package/src/providers/sdk/v1/validators/taint.ts +309 -0
  285. package/src/providers/spec/adapter.ts +168 -0
  286. package/src/providers/spec/cli-adapter.ts +986 -0
  287. package/src/providers/spec/evaluator.ts +345 -0
  288. package/src/providers/spec/fsm-driver.ts +1065 -0
  289. package/src/providers/spec/fsm-evaluator.ts +255 -0
  290. package/src/providers/spec/fsm-loader.ts +120 -0
  291. package/src/providers/spec/fsm-types.ts +238 -0
  292. package/src/providers/spec/native-history-executor.ts +1136 -0
  293. package/src/providers/spec/pre-launch-trust.ts +104 -0
  294. package/src/providers/spec/route.ts +51 -0
  295. package/src/providers/spec/types.ts +226 -0
  296. package/src/providers/status-monitor.d.ts +7 -7
  297. package/src/providers/status-monitor.ts +37 -22
  298. package/src/providers/transcript-v2.ts +567 -0
  299. package/src/providers/types/interactive-prompt.ts +536 -0
  300. package/src/providers/version-archive.ts +64 -24
  301. package/src/providers/working-dir.ts +23 -0
  302. package/src/repo-mesh-types.ts +378 -14
  303. package/src/sessions/registry.ts +6 -0
  304. package/src/shared-types-extra.ts +2 -4
  305. package/src/shared-types.d.ts +8 -0
  306. package/src/shared-types.ts +64 -1
  307. package/src/status/builders.ts +26 -6
  308. package/src/status/normalize.ts +2 -0
  309. package/src/status/reporter.ts +19 -1
  310. package/src/status/snapshot.ts +95 -26
  311. package/src/system/host-memory.ts +29 -12
  312. package/src/system/load-better-sqlite3.ts +68 -0
  313. package/src/types.ts +5 -0
  314. package/dist/cli-adapters/terminal-backends/xterm-backend.d.ts +0 -17
  315. package/dist/mesh/mesh-sync.d.ts +0 -53
  316. package/src/cli-adapters/terminal-backends/ghostty-vt-backend.d.ts +0 -16
  317. package/src/cli-adapters/terminal-backends/xterm-backend.ts +0 -97
  318. package/src/mesh/mesh-sync.ts +0 -111
@@ -13,11 +13,12 @@
13
13
  * Safety: mode 0o600, atomic append via appendFileSync
14
14
  */
15
15
 
16
- import { existsSync, mkdirSync, readFileSync, appendFileSync, statSync, renameSync } from 'fs';
16
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, renameSync, writeFileSync } from 'fs';
17
17
  import { join } from 'path';
18
18
  import { randomUUID } from 'crypto';
19
19
  import { getConfigDir } from '../config/config.js';
20
20
  import { EventEmitter } from 'events';
21
+ import { MeshRuntimeStore } from './mesh-runtime-store.js';
21
22
  // ─── Types ──────────────────────────────────────
22
23
 
23
24
  export type MeshLedgerKind =
@@ -26,16 +27,22 @@ export type MeshLedgerKind =
26
27
  | 'task_failed'
27
28
  | 'task_stalled'
28
29
  | 'task_approval_needed'
30
+ | 'p2p_dispatch_failed'
29
31
  | 'session_launched'
30
32
  | 'session_auto_launch'
31
33
  | 'session_stopped'
32
34
  | 'checkpoint_created'
33
35
  | 'node_cloned'
36
+ | 'node_joined'
34
37
  | 'node_removed'
35
38
  | 'coordinator_started'
36
39
  | 'recovery_attempted'
37
40
  | 'ledger_replicated'
38
41
  | 'ledger_reconciled'
42
+ | 'direct_fast_forward'
43
+ | 'delivery_unroutable'
44
+ | 'direct_dispatch_pruned'
45
+ | 'event_held'
39
46
  ;
40
47
 
41
48
  export interface MeshLedgerEntry {
@@ -61,6 +68,44 @@ export function isIntentionalCleanupStopEntry(entry: Pick<MeshLedgerEntry, 'kind
61
68
  || payload.source === 'mesh_remove_node');
62
69
  }
63
70
 
71
+ export type MeshWorkerResultStatus = 'completed' | 'failed' | 'blocked' | 'partial' | 'unknown';
72
+ export type MeshProcessArtifactKind = 'process' | 'log' | 'port' | 'window' | 'session' | 'file' | 'url' | 'other';
73
+
74
+ export interface MeshValidationResultArtifact {
75
+ command?: string;
76
+ status: 'passed' | 'failed' | 'skipped' | 'unknown';
77
+ durationMs?: number;
78
+ outputPath?: string;
79
+ summary?: string;
80
+ }
81
+
82
+ export interface MeshProcessArtifact {
83
+ kind: MeshProcessArtifactKind;
84
+ id?: string;
85
+ label?: string;
86
+ locator?: string;
87
+ pid?: number;
88
+ port?: number;
89
+ url?: string;
90
+ path?: string;
91
+ sessionId?: string;
92
+ keepRunning?: boolean;
93
+ metadata?: Record<string, unknown>;
94
+ }
95
+
96
+ export interface MeshWorkerResultArtifact {
97
+ status: MeshWorkerResultStatus;
98
+ classification?: string;
99
+ changedFiles: string[];
100
+ validationResults: MeshValidationResultArtifact[];
101
+ gitStatus?: Record<string, unknown>;
102
+ processArtifacts: MeshProcessArtifact[];
103
+ errors: string[];
104
+ nextAction?: string;
105
+ requiresUserAction: boolean;
106
+ source: 'explicit_metadata' | 'final_summary_json' | 'default';
107
+ }
108
+
64
109
  export interface MeshTaskCompletionEvidence {
65
110
  source: 'agent_status_event';
66
111
  event: 'agent:generating_completed' | 'agent:ready';
@@ -74,6 +119,7 @@ export interface MeshTaskCompletionEvidence {
74
119
  providerSessionId?: string;
75
120
  finalSummaryAvailable: boolean;
76
121
  };
122
+ workerResult: MeshWorkerResultArtifact;
77
123
  git: {
78
124
  status: 'deferred';
79
125
  reason: string;
@@ -96,6 +142,7 @@ export interface BuildTaskCompletionEvidenceOptions {
96
142
  providerType?: string;
97
143
  providerSessionId?: string;
98
144
  finalSummary?: string;
145
+ workerResult?: Record<string, unknown>;
99
146
  completedAt?: string;
100
147
  }
101
148
 
@@ -160,8 +207,19 @@ export interface AppendRemoteLedgerResult {
160
207
  // ─── Constants ──────────────────────────────────
161
208
 
162
209
  const LEDGER_DIR_NAME = 'mesh-ledger';
163
- const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
210
+ const MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB — full rotation threshold
211
+ const COMPACT_THRESHOLD_BYTES = 2 * 1024 * 1024; // 2 MB — compaction threshold
212
+ const ARCHIVE_TERMINAL_OLDER_THAN_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
164
213
  const RECENT_FAILURE_WINDOW_MS = 30 * 60 * 1000; // 30 minutes
214
+
215
+ // Kinds that accumulate indefinitely and are safe to archive after ARCHIVE_TERMINAL_OLDER_THAN_MS.
216
+ // Non-terminal kinds (dispatched, sessions, nodes, checkpoints) are always kept in the active file.
217
+ const ARCHIVABLE_KINDS: ReadonlySet<MeshLedgerKind> = new Set([
218
+ 'task_completed',
219
+ 'task_failed',
220
+ 'task_stalled',
221
+ 'recovery_attempted',
222
+ ] as MeshLedgerKind[]);
165
223
  const DEFAULT_LEDGER_SLICE_LIMIT = 100;
166
224
  export const MAX_LEDGER_SLICE_LIMIT = 500;
167
225
 
@@ -186,8 +244,258 @@ function getRotatedPath(meshId: string, index: number): string {
186
244
  return join(getLedgerDir(), `${safe}.${index}.jsonl`);
187
245
  }
188
246
 
247
+ function getArchivePath(meshId: string): string {
248
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
249
+ return join(getLedgerDir(), `${safe}.archive.jsonl`);
250
+ }
251
+
252
+ function getRotatedArchivePath(meshId: string, index: number): string {
253
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
254
+ return join(getLedgerDir(), `${safe}.archive.${index}.jsonl`);
255
+ }
256
+
257
+ function getArchivedCountsPath(meshId: string): string {
258
+ const safe = meshId.replace(/[^a-zA-Z0-9_-]/g, '_');
259
+ return join(getLedgerDir(), `${safe}.archived-counts.json`);
260
+ }
261
+
262
+ function rotateArchiveFile(meshId: string, archivePath: string): void {
263
+ let index = 1;
264
+ while (existsSync(getRotatedArchivePath(meshId, index))) {
265
+ index++;
266
+ if (index > 5) break;
267
+ }
268
+ if (index > 5) index = 5;
269
+ try {
270
+ renameSync(archivePath, getRotatedArchivePath(meshId, index));
271
+ } catch (e: any) {
272
+ process.stderr.write(`[adhdev-mesh] Archive rotation failed for mesh ${meshId}: ${e?.message || e}\n`);
273
+ }
274
+ }
275
+
276
+ interface LedgerArchivedCounts {
277
+ taskCompleted: number;
278
+ taskFailed: number;
279
+ taskStalled: number;
280
+ recoveryAttempted: number;
281
+ totalArchived: number;
282
+ lastArchivedAt: string;
283
+ }
284
+
285
+ function readArchivedCounts(meshId: string): LedgerArchivedCounts {
286
+ const path = getArchivedCountsPath(meshId);
287
+ if (!existsSync(path)) return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: '' };
288
+ try { return JSON.parse(readFileSync(path, 'utf-8')) as LedgerArchivedCounts; } catch { return { taskCompleted: 0, taskFailed: 0, taskStalled: 0, recoveryAttempted: 0, totalArchived: 0, lastArchivedAt: '' }; }
289
+ }
290
+
291
+ function updateArchivedCounts(meshId: string, archived: MeshLedgerEntry[]): void {
292
+ const counts = readArchivedCounts(meshId);
293
+ for (const e of archived) {
294
+ if (e.kind === 'task_completed') counts.taskCompleted++;
295
+ else if (e.kind === 'task_failed') counts.taskFailed++;
296
+ else if (e.kind === 'task_stalled') counts.taskStalled++;
297
+ else if (e.kind === 'recovery_attempted') counts.recoveryAttempted++;
298
+ }
299
+ counts.totalArchived += archived.length;
300
+ counts.lastArchivedAt = new Date().toISOString();
301
+ try { writeFileSync(getArchivedCountsPath(meshId), JSON.stringify(counts), { encoding: 'utf-8', mode: 0o600 }); } catch { /* best-effort */ }
302
+ }
303
+
304
+ // ─── Worker Result Footer ───────────────────────
305
+
306
+ /**
307
+ * Footer to append to worker task messages so workers output structured results
308
+ * that the daemon parses via extractJsonObjectFromSummary / normalizeMeshWorkerResult.
309
+ *
310
+ * Usage: append buildWorkerTaskFooter() to the task message in mesh_send_task /
311
+ * mesh_enqueue_task. The coordinator prompt rules instruct coordinators to do this.
312
+ */
313
+ export function buildWorkerTaskFooter(): string {
314
+ return `
315
+
316
+ ---
317
+ When your task is done, end your final response with a JSON code block in this exact format (omit fields that don't apply):
318
+ \`\`\`json
319
+ {
320
+ "status": "completed",
321
+ "changedFiles": ["src/foo.ts", "tests/foo.test.ts"],
322
+ "gitStatus": { "branch": "feat/your-branch", "committed": true, "pushed": false },
323
+ "validationResults": [{ "command": "npm test", "status": "passed" }],
324
+ "errors": [],
325
+ "nextAction": "optional guidance for the coordinator"
326
+ }
327
+ \`\`\`
328
+ Valid status values: \`completed\` | \`failed\` | \`blocked\` | \`partial\`.`;
329
+ }
330
+
331
+ // ─── Ledger Compaction ──────────────────────────
332
+
333
+ /**
334
+ * Compact the active ledger file for a mesh by moving old terminal entries
335
+ * (task_completed, task_failed, task_stalled, recovery_attempted older than 7 days)
336
+ * to <meshId>.archive.jsonl, keeping the active file lean.
337
+ *
338
+ * Non-terminal entries (dispatch, sessions, node lifecycle) are always retained.
339
+ * Called automatically from appendLedgerEntry when the file exceeds COMPACT_THRESHOLD_BYTES.
340
+ */
341
+ export function compactLedger(meshId: string): { archivedCount: number; retainedCount: number } {
342
+ const filePath = getLedgerPath(meshId);
343
+ if (!existsSync(filePath)) return { archivedCount: 0, retainedCount: 0 };
344
+
345
+ const cutoff = Date.now() - ARCHIVE_TERMINAL_OLDER_THAN_MS;
346
+ const entries = readLedgerEntries(meshId);
347
+
348
+ const keep: MeshLedgerEntry[] = [];
349
+ const archive: MeshLedgerEntry[] = [];
350
+ for (const entry of entries) {
351
+ if (ARCHIVABLE_KINDS.has(entry.kind) && new Date(entry.timestamp).getTime() < cutoff) {
352
+ archive.push(entry);
353
+ } else {
354
+ keep.push(entry);
355
+ }
356
+ }
357
+
358
+ if (archive.length === 0) return { archivedCount: 0, retainedCount: keep.length };
359
+
360
+ // Append archived entries to the archive file, rotate if it exceeds 50MB
361
+ const archivePath = getArchivePath(meshId);
362
+ try {
363
+ if (existsSync(archivePath) && statSync(archivePath).size > 50 * 1024 * 1024) {
364
+ rotateArchiveFile(meshId, archivePath);
365
+ }
366
+ const archiveLines = archive.map(e => JSON.stringify(e)).join('\n') + '\n';
367
+ appendFileSync(archivePath, archiveLines, { encoding: 'utf-8', mode: 0o600 });
368
+ updateArchivedCounts(meshId, archive);
369
+ } catch (e: any) {
370
+ process.stderr.write(`[adhdev-mesh] Ledger archive write failed for mesh ${meshId}: ${e?.message || e}\n`);
371
+ return { archivedCount: 0, retainedCount: entries.length };
372
+ }
373
+
374
+ // Rewrite active file with retained entries only
375
+ try {
376
+ const keepLines = keep.length ? keep.map(e => JSON.stringify(e)).join('\n') + '\n' : '';
377
+ writeFileSync(filePath, keepLines, { encoding: 'utf-8', mode: 0o600 });
378
+ invalidateLedgerCache(meshId);
379
+ } catch (e: any) {
380
+ process.stderr.write(`[adhdev-mesh] Ledger compaction rewrite failed for mesh ${meshId}: ${e?.message || e}\n`);
381
+ return { archivedCount: archive.length, retainedCount: keep.length };
382
+ }
383
+
384
+ // G2: mirror the compaction in SQLite so the runtime store matches the active
385
+ // ledger set. Archived entries live on in the JSONL archive files (export/debug).
386
+ try {
387
+ MeshRuntimeStore.getInstance().deleteLedgerEntries(meshId, archive.map(e => e.id));
388
+ invalidateLedgerCache(meshId);
389
+ } catch { /* best-effort; summary counts absorb the difference via archived counts */ }
390
+
391
+ return { archivedCount: archive.length, retainedCount: keep.length };
392
+ }
393
+
189
394
  // ─── Core API ───────────────────────────────────
190
395
 
396
+ function readNonEmptyString(value: unknown): string | undefined {
397
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
398
+ }
399
+
400
+ function readStringArray(value: unknown): string[] {
401
+ if (!Array.isArray(value)) return [];
402
+ return value.map(item => readNonEmptyString(item)).filter(Boolean) as string[];
403
+ }
404
+
405
+ function extractJsonObjectFromSummary(summary?: string): Record<string, unknown> | undefined {
406
+ const text = readNonEmptyString(summary);
407
+ if (!text) return undefined;
408
+ const fenced = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
409
+ const candidates = [fenced?.[1], text].filter(Boolean) as string[];
410
+ for (const candidate of candidates) {
411
+ const trimmed = candidate.trim();
412
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) continue;
413
+ try {
414
+ const parsed = JSON.parse(trimmed);
415
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
416
+ // Require at least one mesh worker result field to avoid false positives
417
+ // (e.g. JSON from tool call outputs or log lines in the final summary).
418
+ const hasWorkerShape = 'status' in parsed && (
419
+ 'changedFiles' in parsed || 'errors' in parsed
420
+ || 'gitStatus' in parsed || 'nextAction' in parsed
421
+ || 'validationResults' in parsed
422
+ );
423
+ if (hasWorkerShape) return parsed;
424
+ }
425
+ } catch { /* try next candidate */ }
426
+ }
427
+ return undefined;
428
+ }
429
+
430
+ function normalizeValidationResults(value: unknown): MeshValidationResultArtifact[] {
431
+ if (!Array.isArray(value)) return [];
432
+ return value
433
+ .filter(item => item && typeof item === 'object' && !Array.isArray(item))
434
+ .map((item: any) => {
435
+ const status = ['passed', 'failed', 'skipped', 'unknown'].includes(item.status) ? item.status : 'unknown';
436
+ return {
437
+ ...(readNonEmptyString(item.command) ? { command: readNonEmptyString(item.command) } : {}),
438
+ status,
439
+ ...(Number.isFinite(Number(item.durationMs)) ? { durationMs: Number(item.durationMs) } : {}),
440
+ ...(readNonEmptyString(item.outputPath) ? { outputPath: readNonEmptyString(item.outputPath) } : {}),
441
+ ...(readNonEmptyString(item.summary) ? { summary: readNonEmptyString(item.summary) } : {}),
442
+ };
443
+ });
444
+ }
445
+
446
+ function normalizeProcessArtifacts(value: unknown): MeshProcessArtifact[] {
447
+ if (!Array.isArray(value)) return [];
448
+ const kinds = new Set(['process', 'log', 'port', 'window', 'session', 'file', 'url', 'other']);
449
+ return value
450
+ .filter(item => item && typeof item === 'object' && !Array.isArray(item))
451
+ .map((item: any) => ({
452
+ kind: kinds.has(item.kind) ? item.kind : 'other',
453
+ ...(readNonEmptyString(item.id) ? { id: readNonEmptyString(item.id) } : {}),
454
+ ...(readNonEmptyString(item.label) ? { label: readNonEmptyString(item.label) } : {}),
455
+ ...(readNonEmptyString(item.locator) ? { locator: readNonEmptyString(item.locator) } : {}),
456
+ ...(Number.isFinite(Number(item.pid)) ? { pid: Number(item.pid) } : {}),
457
+ ...(Number.isFinite(Number(item.port)) ? { port: Number(item.port) } : {}),
458
+ ...(readNonEmptyString(item.url) ? { url: readNonEmptyString(item.url) } : {}),
459
+ ...(readNonEmptyString(item.path) ? { path: readNonEmptyString(item.path) } : {}),
460
+ ...(readNonEmptyString(item.sessionId) ? { sessionId: readNonEmptyString(item.sessionId) } : {}),
461
+ ...(typeof item.keepRunning === 'boolean' ? { keepRunning: item.keepRunning } : {}),
462
+ ...(item.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata) ? { metadata: item.metadata as Record<string, unknown> } : {}),
463
+ }));
464
+ }
465
+
466
+ export function normalizeMeshWorkerResult(input?: Record<string, unknown>, source: MeshWorkerResultArtifact['source'] = 'explicit_metadata'): MeshWorkerResultArtifact {
467
+ const raw = input && typeof input === 'object' ? input : {};
468
+ const status = ['completed', 'failed', 'blocked', 'partial', 'unknown'].includes(String(raw.status))
469
+ ? raw.status as MeshWorkerResultStatus
470
+ : 'unknown';
471
+ const gitStatus = raw.gitStatus && typeof raw.gitStatus === 'object' && !Array.isArray(raw.gitStatus)
472
+ ? raw.gitStatus as Record<string, unknown>
473
+ : undefined;
474
+ return {
475
+ status,
476
+ ...(readNonEmptyString(raw.classification) ? { classification: readNonEmptyString(raw.classification) } : {}),
477
+ changedFiles: readStringArray(raw.changedFiles),
478
+ validationResults: normalizeValidationResults(raw.validationResults),
479
+ ...(gitStatus ? { gitStatus } : {}),
480
+ processArtifacts: normalizeProcessArtifacts(raw.processArtifacts),
481
+ errors: readStringArray(raw.errors),
482
+ ...(readNonEmptyString(raw.nextAction) ? { nextAction: readNonEmptyString(raw.nextAction) } : {}),
483
+ requiresUserAction: raw.requiresUserAction === true,
484
+ source,
485
+ };
486
+ }
487
+
488
+ function resolveWorkerResult(opts: BuildTaskCompletionEvidenceOptions): MeshWorkerResultArtifact {
489
+ if (opts.workerResult && typeof opts.workerResult === 'object') {
490
+ return normalizeMeshWorkerResult(opts.workerResult, 'explicit_metadata');
491
+ }
492
+ const parsed = extractJsonObjectFromSummary(opts.finalSummary);
493
+ if (parsed) {
494
+ return normalizeMeshWorkerResult(parsed, 'final_summary_json');
495
+ }
496
+ return normalizeMeshWorkerResult(undefined, 'default');
497
+ }
498
+
191
499
  export function buildTaskCompletionEvidence(opts: BuildTaskCompletionEvidenceOptions): MeshTaskCompletionEvidence {
192
500
  const providerSessionId = opts.providerSessionId?.trim() || undefined;
193
501
  const providerType = opts.providerType?.trim() || undefined;
@@ -204,6 +512,7 @@ export function buildTaskCompletionEvidence(opts: BuildTaskCompletionEvidenceOpt
204
512
  providerSessionId,
205
513
  finalSummaryAvailable: typeof opts.finalSummary === 'string' && opts.finalSummary.trim().length > 0,
206
514
  },
515
+ workerResult: resolveWorkerResult(opts),
207
516
  git: {
208
517
  status: 'deferred',
209
518
  reason: 'ordinary_completion_git_status_not_checked',
@@ -239,21 +548,44 @@ export function appendLedgerEntry(
239
548
 
240
549
  const filePath = getLedgerPath(meshId);
241
550
 
242
- // Rotate if file exceeds max size
551
+ // Compact or rotate based on file size
243
552
  if (existsSync(filePath)) {
244
553
  try {
245
554
  const stat = statSync(filePath);
246
555
  if (stat.size >= MAX_FILE_SIZE_BYTES) {
247
556
  rotateLedgerFile(meshId, filePath);
557
+ } else if (stat.size >= COMPACT_THRESHOLD_BYTES) {
558
+ compactLedger(meshId);
248
559
  }
249
560
  } catch {
250
561
  // stat failed — proceed with append anyway
251
562
  }
252
563
  }
253
564
 
565
+ // Write to SQLite (G2: primary runtime read/write path)
566
+ try {
567
+ MeshRuntimeStore.getInstance().appendLedgerEntry({
568
+ id: entry.id,
569
+ meshId: entry.meshId,
570
+ timestamp: entry.timestamp,
571
+ kind: entry.kind,
572
+ nodeId: entry.nodeId ?? null,
573
+ sessionId: entry.sessionId ?? null,
574
+ providerType: entry.providerType ?? null,
575
+ payload: entry.payload,
576
+ });
577
+ } catch {
578
+ // SQLite write failed but the JSONL append below still records the entry.
579
+ // Reset the one-time import flag so the next read re-imports from JSONL
580
+ // and the store self-heals instead of silently missing this entry.
581
+ ledgerImportDone.delete(meshId);
582
+ }
583
+
584
+ // Also write to JSONL (retained as export/import/debug/legacy artifact)
254
585
  try {
255
586
  const line = JSON.stringify(entry) + '\n';
256
587
  appendFileSync(filePath, line, { encoding: 'utf-8', mode: 0o600 });
588
+ invalidateLedgerCache(meshId);
257
589
  meshLedgerEvents.emit('append', meshId, entry);
258
590
  return entry;
259
591
  } catch (e: any) {
@@ -285,8 +617,9 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
285
617
  if (entries.length === 0) return { accepted: 0, skippedDuplicate: 0, rejectedInvalid: 0, entries: [] };
286
618
  const ledgerPath = getLedgerPath(meshId);
287
619
 
288
- // Read existing to deduplicate by ID
289
- const existing = new Set(readLedgerEntries(meshId).map(e => e.id));
620
+ // Dedup against recent entries only — P2P replication is incremental (cursor-based),
621
+ // so duplicates appear in the recent tail, not deep history.
622
+ const existing = new Set(readLedgerEntries(meshId, { tail: 1000 }).map(e => e.id));
290
623
  const validEntries: MeshLedgerEntry[] = [];
291
624
  let rejectedInvalid = 0;
292
625
  let skippedDuplicate = 0;
@@ -307,9 +640,24 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
307
640
  return { accepted: 0, skippedDuplicate, rejectedInvalid, entries: [] };
308
641
  }
309
642
 
643
+ // G2: write to SQLite (primary runtime store); INSERT OR IGNORE dedups by id.
644
+ try {
645
+ MeshRuntimeStore.getInstance().importLedgerEntries(validEntries.map(e => ({
646
+ id: e.id,
647
+ meshId: e.meshId,
648
+ timestamp: e.timestamp,
649
+ kind: e.kind,
650
+ nodeId: e.nodeId ?? null,
651
+ sessionId: e.sessionId ?? null,
652
+ providerType: e.providerType ?? null,
653
+ payload: e.payload ?? {},
654
+ })));
655
+ } catch { /* best-effort; JSONL append below still records the entries */ }
656
+
310
657
  try {
311
658
  const lines = validEntries.map(e => JSON.stringify(e)).join('\n') + '\n';
312
659
  appendFileSync(ledgerPath, lines, { encoding: 'utf-8', mode: 0o600 });
660
+ invalidateLedgerCache(meshId);
313
661
  for (const entry of validEntries) {
314
662
  meshLedgerEvents.emit('append', meshId, entry);
315
663
  }
@@ -319,103 +667,151 @@ export function appendRemoteLedgerEntries(meshId: string, entries: MeshLedgerEnt
319
667
  }
320
668
  }
321
669
 
322
- /**
323
- * Read ledger entries with optional filtering.
324
- */
325
- export function readLedgerEntries(meshId: string, opts?: ReadLedgerOptions): MeshLedgerEntry[] {
670
+ // ─── Ledger Read Cache ─────────────────────────
671
+ // Absorbs repeated reads within a single event-processing burst (e.g. agent:stopped
672
+ // triggers shouldSuppressIntentionalCleanupStop, findRecentTerminalLedgerEvidence,
673
+ // hasDispatchAfterTerminal, and getSessionRecoveryContext all reading the same store).
674
+ // TTL is 100ms: short enough to stay current, long enough to cover one event cycle.
675
+ // Cache is invalidated on every write (append, remote import, compaction).
676
+
677
+ const ledgerReadCache = new Map<string, { entries: MeshLedgerEntry[]; cachedAt: number }>();
678
+ const LEDGER_CACHE_TTL_MS = 100;
679
+
680
+ function readLedgerFile(meshId: string): MeshLedgerEntry[] {
326
681
  const filePath = getLedgerPath(meshId);
327
682
  if (!existsSync(filePath)) return [];
328
-
329
683
  let content: string;
684
+ try { content = readFileSync(filePath, 'utf-8'); } catch { return []; }
685
+ const entries: MeshLedgerEntry[] = [];
686
+ for (const line of content.split('\n')) {
687
+ if (!line.trim()) continue;
688
+ try {
689
+ const entry = JSON.parse(line) as MeshLedgerEntry;
690
+ if (entry.id && entry.kind) entries.push(entry);
691
+ } catch { /* skip malformed lines */ }
692
+ }
693
+ return entries;
694
+ }
695
+
696
+ // ─── G2: One-Time JSONL → SQLite Import ─────────
697
+ // On the first SQLite read for a mesh (per store instance), import any legacy
698
+ // JSONL entries into mesh_event_ledger. INSERT OR IGNORE makes this idempotent:
699
+ // dual-written entries are skipped, only pre-cutover legacy entries are added.
700
+ // Keyed by the store instance so MeshRuntimeStore.resetForTests() (fresh DB)
701
+ // naturally re-imports.
702
+
703
+ let ledgerImportStoreRef: MeshRuntimeStore | undefined;
704
+ const ledgerImportDone = new Set<string>();
705
+
706
+ function ensureLedgerImported(store: MeshRuntimeStore, meshId: string): void {
707
+ if (ledgerImportStoreRef !== store) {
708
+ ledgerImportDone.clear();
709
+ ledgerImportStoreRef = store;
710
+ }
711
+ if (ledgerImportDone.has(meshId)) return;
712
+ ledgerImportDone.add(meshId);
713
+ const fileEntries = readLedgerFile(meshId);
714
+ if (fileEntries.length === 0) return;
330
715
  try {
331
- content = readFileSync(filePath, 'utf-8');
716
+ store.importLedgerEntries(fileEntries.map(e => ({
717
+ id: e.id,
718
+ meshId: e.meshId,
719
+ timestamp: e.timestamp,
720
+ kind: e.kind,
721
+ nodeId: e.nodeId ?? null,
722
+ sessionId: e.sessionId ?? null,
723
+ providerType: e.providerType ?? null,
724
+ payload: e.payload ?? {},
725
+ })));
726
+ } catch { /* import is best-effort; reads fall back to JSONL on store failure */ }
727
+ }
728
+
729
+ function readLedgerFromStore(meshId: string): MeshLedgerEntry[] {
730
+ const store = MeshRuntimeStore.getInstance();
731
+ ensureLedgerImported(store, meshId);
732
+ return store.readLedgerEntriesOrdered(meshId).map(r => ({
733
+ id: r.id,
734
+ meshId: r.meshId,
735
+ timestamp: r.timestamp,
736
+ kind: r.kind as MeshLedgerKind,
737
+ ...(r.nodeId ? { nodeId: r.nodeId } : {}),
738
+ ...(r.sessionId ? { sessionId: r.sessionId } : {}),
739
+ ...(r.providerType ? { providerType: r.providerType } : {}),
740
+ payload: (r.payload && typeof r.payload === 'object' ? r.payload : {}) as Record<string, unknown>,
741
+ }));
742
+ }
743
+
744
+ function getCachedRawEntries(meshId: string): MeshLedgerEntry[] {
745
+ const now = Date.now();
746
+ const cached = ledgerReadCache.get(meshId);
747
+ if (cached && now - cached.cachedAt < LEDGER_CACHE_TTL_MS) return cached.entries;
748
+ let entries: MeshLedgerEntry[];
749
+ try {
750
+ // G2: SQLite mesh_event_ledger is the primary runtime read path.
751
+ entries = readLedgerFromStore(meshId);
332
752
  } catch {
333
- return [];
753
+ // Store unavailable — fall back to the JSONL export artifact.
754
+ entries = readLedgerFile(meshId);
334
755
  }
756
+ ledgerReadCache.set(meshId, { entries, cachedAt: now });
757
+ return entries;
758
+ }
335
759
 
336
- const lines = content.split('\n').filter(line => line.trim());
337
- let entries: MeshLedgerEntry[] = [];
760
+ function invalidateLedgerCache(meshId: string): void {
761
+ ledgerReadCache.delete(meshId);
762
+ }
338
763
 
339
- for (const line of lines) {
340
- try {
341
- const entry = JSON.parse(line) as MeshLedgerEntry;
342
- if (!entry.id || !entry.kind) continue;
343
- entries.push(entry);
344
- } catch {
345
- // Skip malformed lines
346
- }
347
- }
764
+ /**
765
+ * Test helper: clear all runtime ledger state for a mesh — SQLite rows, read
766
+ * cache, and the one-time import flag. JSONL files are the caller's concern.
767
+ */
768
+ export function __clearMeshLedgerForTests(meshId: string): void {
769
+ try {
770
+ MeshRuntimeStore.getInstance().clearLedgerForMesh(meshId);
771
+ } catch { /* store unavailable — nothing to clear */ }
772
+ ledgerReadCache.delete(meshId);
773
+ ledgerImportDone.delete(meshId);
774
+ }
775
+
776
+ /**
777
+ * Read ledger entries with optional filtering.
778
+ * G2: SQLite (mesh_event_ledger) is the primary read path; legacy JSONL is
779
+ * imported once per store instance and otherwise retained as an
780
+ * export/import/debug artifact only.
781
+ */
782
+ export function readLedgerEntries(meshId: string, opts?: ReadLedgerOptions): MeshLedgerEntry[] {
783
+ let entries = getCachedRawEntries(meshId);
348
784
 
349
- // Apply filters
350
785
  if (opts?.since) {
351
786
  const sinceDate = new Date(opts.since).getTime();
352
- if (!isNaN(sinceDate)) {
353
- entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
354
- }
787
+ if (!isNaN(sinceDate)) entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
355
788
  }
356
-
357
789
  if (opts?.kind?.length) {
358
790
  const kindSet = new Set(opts.kind);
359
791
  entries = entries.filter(e => kindSet.has(e.kind));
360
792
  }
361
-
362
- // Apply tail (return last N entries)
363
793
  if (opts?.tail && opts.tail > 0 && entries.length > opts.tail) {
364
794
  entries = entries.slice(-opts.tail);
365
795
  }
366
-
367
796
  return entries;
368
797
  }
369
798
 
370
799
  /**
371
- * Read a bounded, cursor-addressable ledger slice for local-first/P2P replication.
372
- * The result is intentionally small and self-describing so coordinators can query
373
- * remote daemons on demand without Cloud/D1 becoming a ledger data-plane.
374
- */
375
- export function readLedgerSlice(meshId: string, opts?: ReadLedgerSliceOptions): MeshLedgerSlice {
376
- const limit = clampLedgerSliceLimit(opts?.limit);
377
- let entries = readLedgerEntries(meshId, { since: opts?.since, kind: opts?.kind });
378
- const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
379
- if (afterId) {
380
- const index = entries.findIndex(entry => entry.id === afterId);
381
- entries = index >= 0 ? entries.slice(index + 1) : entries;
382
- }
383
- const bounded = entries.slice(0, limit);
384
- return {
385
- protocol: 'adhdev.mesh.ledger.slice.v1',
386
- meshId,
387
- entries: bounded,
388
- cursor: {
389
- afterId,
390
- nextAfterId: bounded.length ? bounded[bounded.length - 1].id : afterId,
391
- limit,
392
- hasMore: entries.length > bounded.length,
393
- },
394
- summary: getLedgerSummary(meshId),
395
- sourceOfTruth: {
396
- kind: 'local_jsonl',
397
- path: getLedgerPath(meshId),
398
- bounded: true,
399
- maxLimit: MAX_LEDGER_SLICE_LIMIT,
400
- },
401
- };
402
- }
403
-
404
- /**
405
- * Get a summary of mesh activity from the ledger.
800
+ * Build a ledger summary from pre-loaded entries. Used by both getLedgerSummary
801
+ * and readLedgerSlice so they share a single getCachedRawEntries() call.
406
802
  */
407
- export function getLedgerSummary(meshId: string): MeshLedgerSummary {
408
- const entries = readLedgerEntries(meshId);
803
+ function buildLedgerSummary(meshId: string, entries: MeshLedgerEntry[]): MeshLedgerSummary {
804
+ const archived = readArchivedCounts(meshId);
409
805
  const now = Date.now();
410
806
  const recentFailureCutoff = now - RECENT_FAILURE_WINDOW_MS;
411
807
 
412
808
  const summary: MeshLedgerSummary = {
413
809
  meshId,
414
- totalEntries: entries.length,
810
+ totalEntries: entries.length + archived.totalArchived,
415
811
  taskDispatched: 0,
416
- taskCompleted: 0,
417
- taskFailed: 0,
418
- taskStalled: 0,
812
+ taskCompleted: archived.taskCompleted,
813
+ taskFailed: archived.taskFailed,
814
+ taskStalled: archived.taskStalled,
419
815
  sessionLaunched: 0,
420
816
  checkpointCreated: 0,
421
817
  lastActivityAt: null,
@@ -450,6 +846,79 @@ export function getLedgerSummary(meshId: string): MeshLedgerSummary {
450
846
  return summary;
451
847
  }
452
848
 
849
+ /**
850
+ * Read a bounded, cursor-addressable ledger slice for local-first/P2P replication.
851
+ * The result is intentionally small and self-describing so coordinators can query
852
+ * remote daemons on demand without Cloud/D1 becoming a ledger data-plane.
853
+ */
854
+ export function readLedgerSlice(meshId: string, opts?: ReadLedgerSliceOptions): MeshLedgerSlice {
855
+ const limit = clampLedgerSliceLimit(opts?.limit);
856
+ // Load raw entries once and share between filtering, pagination, and summary.
857
+ const rawEntries = getCachedRawEntries(meshId);
858
+
859
+ let entries: MeshLedgerEntry[] = rawEntries;
860
+ if (opts?.since) {
861
+ const sinceDate = new Date(opts.since).getTime();
862
+ if (!isNaN(sinceDate)) entries = entries.filter(e => new Date(e.timestamp).getTime() >= sinceDate);
863
+ }
864
+ if (opts?.kind?.length) {
865
+ const kindSet = new Set(opts.kind);
866
+ entries = entries.filter(e => kindSet.has(e.kind));
867
+ }
868
+
869
+ const afterId = typeof opts?.afterId === 'string' && opts.afterId.trim() ? opts.afterId.trim() : null;
870
+ if (afterId) {
871
+ const index = entries.findIndex(entry => entry.id === afterId);
872
+ entries = index >= 0 ? entries.slice(index + 1) : entries;
873
+ }
874
+ const bounded = entries.slice(0, limit);
875
+ return {
876
+ protocol: 'adhdev.mesh.ledger.slice.v1',
877
+ meshId,
878
+ entries: bounded,
879
+ cursor: {
880
+ afterId,
881
+ nextAfterId: bounded.length ? bounded[bounded.length - 1].id : afterId,
882
+ limit,
883
+ hasMore: entries.length > bounded.length,
884
+ },
885
+ summary: buildLedgerSummary(meshId, rawEntries),
886
+ sourceOfTruth: {
887
+ kind: 'local_jsonl',
888
+ path: getLedgerPath(meshId),
889
+ bounded: true,
890
+ maxLimit: MAX_LEDGER_SLICE_LIMIT,
891
+ },
892
+ };
893
+ }
894
+
895
+ /**
896
+ * G4: Read a bounded ledger slice from the SQLite mesh_event_ledger table.
897
+ * This is the preferred P2P reconcile read path; JSONL files are retained as
898
+ * export/import/debug/legacy artifacts only.
899
+ *
900
+ * Returns a shape structurally compatible with MeshLedgerSlice (minus the
901
+ * JSONL-specific `summary` and `sourceOfTruth.path` fields) so callers can
902
+ * pass it to buildMeshLedgerReplicaEvidence without modification.
903
+ */
904
+ export function readLedgerSliceFromStore(meshId: string, opts?: ReadLedgerSliceOptions): ReturnType<typeof MeshRuntimeStore.prototype.readLedgerSlice> {
905
+ return MeshRuntimeStore.getInstance().readLedgerSlice(meshId, {
906
+ afterId: opts?.afterId,
907
+ since: opts?.since,
908
+ // ReadLedgerSliceOptions allows kind as array; SQLite path takes a single kind string.
909
+ // Pass first kind value if provided; callers needing multi-kind filtering should use readLedgerSlice (JSONL).
910
+ kind: opts?.kind?.length ? opts.kind[0] : undefined,
911
+ limit: opts?.limit,
912
+ });
913
+ }
914
+
915
+ /**
916
+ * Get a summary of mesh activity from the ledger.
917
+ */
918
+ export function getLedgerSummary(meshId: string): MeshLedgerSummary {
919
+ return buildLedgerSummary(meshId, getCachedRawEntries(meshId));
920
+ }
921
+
453
922
  // ─── Recovery Context ───────────────────────────
454
923
 
455
924
  export interface SessionRecoveryContext {
@@ -484,46 +953,64 @@ export function getSessionRecoveryContext(
484
953
  },
485
954
  ): SessionRecoveryContext {
486
955
  const maxRetries = opts.maxRetries ?? 1;
487
- const entries = readLedgerEntries(meshId);
956
+ // tail:500 is sufficient — task_dispatched is never archived (only terminal kinds are),
957
+ // so dispatch history is always present. The 30-min failure window means we never need
958
+ // more than a few dozen recent entries for consecutiveNodeFailures. Bounding to 500
959
+ // avoids a full O(n) scan for meshes with many historical entries.
960
+ const entries = readLedgerEntries(meshId, { tail: 500 });
488
961
 
489
- // Find the last task_dispatched for this session or node
962
+ // Single backward pass: find last task_dispatched AND count consecutive recent failures.
963
+ const now = Date.now();
964
+ const recentWindow = now - RECENT_FAILURE_WINDOW_MS;
490
965
  let lastDispatch: MeshLedgerEntry | null = null;
966
+ let consecutiveNodeFailures = 0;
967
+ let failureCountDone = false;
491
968
  for (let i = entries.length - 1; i >= 0; i--) {
492
969
  const e = entries[i];
493
- if (e.kind !== 'task_dispatched') continue;
494
- if (opts.sessionId && e.sessionId === opts.sessionId) { lastDispatch = e; break; }
495
- if (opts.nodeId && e.nodeId === opts.nodeId) { lastDispatch = e; break; }
970
+ const ts = new Date(e.timestamp).getTime();
971
+
972
+ // Failure counting: scan until we exit the recent window or hit a chain-breaker
973
+ if (!failureCountDone) {
974
+ if (ts < recentWindow) {
975
+ failureCountDone = true;
976
+ } else if (opts.nodeId && e.nodeId !== opts.nodeId) {
977
+ // Entry for a different node — skip for failure counting but continue scanning for dispatch
978
+ } else if (e.kind === 'task_failed') {
979
+ if (!isIntentionalCleanupStopEntry(e)) consecutiveNodeFailures++;
980
+ } else if (e.kind === 'task_completed' || e.kind === 'task_dispatched') {
981
+ // A completion or new dispatch breaks the consecutive failure chain
982
+ failureCountDone = true;
983
+ }
984
+ }
985
+
986
+ // Dispatch search: find the last dispatch matching this session or node
987
+ if (lastDispatch === null && e.kind === 'task_dispatched') {
988
+ if (opts.sessionId && e.sessionId === opts.sessionId) { lastDispatch = e; }
989
+ else if (!opts.sessionId && opts.nodeId && e.nodeId === opts.nodeId) { lastDispatch = e; }
990
+ }
991
+
992
+ // Stop once both tasks are done
993
+ if (lastDispatch !== null && failureCountDone) break;
496
994
  }
497
995
 
498
996
  const lastTaskMessage = typeof lastDispatch?.payload?.message === 'string'
499
997
  ? lastDispatch.payload.message
500
998
  : null;
501
999
 
502
- // Count consecutive recent failures for this node (within 30 min window)
503
- const now = Date.now();
504
- const recentWindow = now - RECENT_FAILURE_WINDOW_MS;
505
- let consecutiveNodeFailures = 0;
506
- for (let i = entries.length - 1; i >= 0; i--) {
507
- const e = entries[i];
508
- if (new Date(e.timestamp).getTime() < recentWindow) break;
509
- if (opts.nodeId && e.nodeId !== opts.nodeId) continue;
510
- if (e.kind === 'task_failed') {
511
- if (isIntentionalCleanupStopEntry(e)) continue;
512
- consecutiveNodeFailures++;
513
- } else if (e.kind === 'task_completed' || e.kind === 'task_dispatched') {
514
- // A completion or new dispatch breaks the consecutive failure chain
515
- break;
516
- }
517
- }
518
-
519
- // Count how many times the same task was attempted (match by message prefix)
1000
+ // Count how many times the same task was attempted.
1001
+ // Prefer exact taskId match (payload.taskId) to avoid 200-char prefix collisions.
520
1002
  let taskAttemptCount = 0;
521
- if (lastTaskMessage) {
522
- const prefix = lastTaskMessage.slice(0, 200);
523
- for (const e of entries) {
524
- if (e.kind === 'task_dispatched' && typeof e.payload?.message === 'string') {
525
- if (e.payload.message.startsWith(prefix)) {
526
- taskAttemptCount++;
1003
+ if (lastDispatch) {
1004
+ const taskId = typeof lastDispatch.payload?.taskId === 'string' ? lastDispatch.payload.taskId : null;
1005
+ if (taskId) {
1006
+ for (const e of entries) {
1007
+ if (e.kind === 'task_dispatched' && e.payload?.taskId === taskId) taskAttemptCount++;
1008
+ }
1009
+ } else if (lastTaskMessage) {
1010
+ const prefix = lastTaskMessage.slice(0, 200);
1011
+ for (const e of entries) {
1012
+ if (e.kind === 'task_dispatched' && typeof e.payload?.message === 'string') {
1013
+ if (e.payload.message.startsWith(prefix)) taskAttemptCount++;
527
1014
  }
528
1015
  }
529
1016
  }
@@ -573,7 +1060,8 @@ function rotateLedgerFile(meshId: string, currentPath: string): void {
573
1060
 
574
1061
  try {
575
1062
  renameSync(currentPath, getRotatedPath(meshId, index));
576
- } catch {
1063
+ } catch (e: any) {
577
1064
  // Rotation failed — the next append will just grow the file
1065
+ process.stderr.write(`[adhdev-mesh] Ledger rotation failed for mesh ${meshId}: ${e?.message || e}. File will continue to grow.\n`);
578
1066
  }
579
1067
  }