@adhdev/daemon-core 0.9.82-rc.21 → 0.9.82-rc.210

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