@adhdev/daemon-core 0.9.82-rc.26 → 0.9.82-rc.261

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