arco-workbench 0.1.3 → 0.1.4

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 (296) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/README.md +5 -1
  3. package/client/dist/assets/{PhosphorBackdrop-CkVIGkeX.js → PhosphorBackdrop-CNumba2X.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-DHF7CnpE.js → ThemedBackgroundShaderImpl-DX5KyCt3.js} +1 -1
  5. package/client/dist/assets/{XtermView-SY0UcZUS.js → XtermView-DhS5g8Rt.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-Ca4F8HiM.js → galleryEditor-fPb76Cjv.js} +1 -1
  7. package/client/dist/assets/index-CjkHb-_n.js +592 -0
  8. package/client/dist/assets/index-DIbh3ae5.css +1 -0
  9. package/client/dist/index.html +2 -2
  10. package/client/src/App.tsx +2 -0
  11. package/client/src/alerts/desktopAlerts.ts +13 -1
  12. package/client/src/brief/briefFacts.ts +22 -0
  13. package/client/src/brief/briefFromStore.ts +7 -2
  14. package/client/src/components/ArtifactMoveDialog.tsx +64 -0
  15. package/client/src/components/BriefControl.tsx +38 -47
  16. package/client/src/components/CatchMeUp.tsx +25 -25
  17. package/client/src/components/CheckpointActions.tsx +7 -4
  18. package/client/src/components/ClusterComposerButtons.tsx +6 -3
  19. package/client/src/components/ClusterPlanTab.tsx +15 -1
  20. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +6 -2
  21. package/client/src/components/ClusterTab.tsx +33 -3
  22. package/client/src/components/ClusterTaskBoardTab.tsx +62 -8
  23. package/client/src/components/DialogShell.tsx +115 -0
  24. package/client/src/components/DocsUpdateDialog.tsx +16 -42
  25. package/client/src/components/ForwardMessages.tsx +28 -32
  26. package/client/src/components/GitDialog.tsx +52 -52
  27. package/client/src/components/GitOtherWork.tsx +4 -2
  28. package/client/src/components/HandoffDialog.tsx +19 -45
  29. package/client/src/components/Home/HomeView.tsx +36 -8
  30. package/client/src/components/Home/home.css +7 -0
  31. package/client/src/components/KeepButton.tsx +23 -0
  32. package/client/src/components/MdTuneupDialog.tsx +52 -51
  33. package/client/src/components/MemberCard.tsx +4 -1
  34. package/client/src/components/MemberPane.tsx +1 -1
  35. package/client/src/components/NotificationCenter.tsx +4 -3
  36. package/client/src/components/NotificationChannelsSettings.tsx +25 -7
  37. package/client/src/components/PlanCandidateBanner.tsx +111 -57
  38. package/client/src/components/PlanComposerDialog.tsx +55 -87
  39. package/client/src/components/ProjectStateNotice.tsx +60 -0
  40. package/client/src/components/PublicProjectBox.tsx +25 -0
  41. package/client/src/components/ResearchDialog.tsx +15 -24
  42. package/client/src/components/ReviewDialog.tsx +32 -57
  43. package/client/src/components/RightPanel/OutputsPanel.tsx +4 -0
  44. package/client/src/components/RightPanel/PlanTab.tsx +24 -2
  45. package/client/src/components/RightPanel/UsageTab.tsx +77 -1
  46. package/client/src/components/SkillEditorDialog.tsx +38 -73
  47. package/client/src/components/SpawnDialog.tsx +19 -41
  48. package/client/src/components/StorageWarnings.tsx +21 -0
  49. package/client/src/components/SystemHeader.tsx +2 -2
  50. package/client/src/components/TerminalInput.tsx +6 -2
  51. package/client/src/components/TidyComposer.tsx +24 -41
  52. package/client/src/components/TranscriptSendDialog.tsx +151 -202
  53. package/client/src/components/UtilityAgentPicker.tsx +4 -2
  54. package/client/src/components/WorkflowCreator/index.tsx +2 -0
  55. package/client/src/components/WorkflowView.tsx +4 -1
  56. package/client/src/components/clusterNeedsYou.ts +35 -3
  57. package/client/src/components/compare/CompareDialog.tsx +26 -2
  58. package/client/src/components/terminalInput/planDraft.ts +33 -4
  59. package/client/src/components/utilityResult.ts +5 -1
  60. package/client/src/explorer/ExplorerApp.tsx +5 -2
  61. package/client/src/explorer/PlansLens.tsx +60 -19
  62. package/client/src/explorer/StorageLens.tsx +275 -0
  63. package/client/src/explorer/launch.ts +3 -3
  64. package/client/src/explorer/plansGrouping.ts +15 -0
  65. package/client/src/help/content/cluster.tsx +42 -7
  66. package/client/src/help/content/composer.tsx +26 -6
  67. package/client/src/help/content/header.tsx +16 -14
  68. package/client/src/help/content/misc.tsx +141 -6
  69. package/client/src/help/content/rightPanel.tsx +16 -0
  70. package/client/src/help/content/settings.tsx +4 -4
  71. package/client/src/help/manualSections/actions.tsx +19 -4
  72. package/client/src/help/manualSections/clusters.tsx +29 -16
  73. package/client/src/help/manualSections/configuration.tsx +6 -4
  74. package/client/src/help/manualSections/maintenance.tsx +27 -5
  75. package/client/src/help/manualSections/plans.tsx +96 -2
  76. package/client/src/help/manualSections/powerFeatures.tsx +2 -2
  77. package/client/src/help/manualSections/reference.tsx +6 -0
  78. package/client/src/help/manualSections/workspace.tsx +9 -5
  79. package/client/src/stores/appStore.ts +10 -1
  80. package/client/src/stores/appStore.types.ts +2 -0
  81. package/client/src/stores/mdTuneupStore.ts +5 -4
  82. package/client/src/stores/memoryTrim.ts +18 -2
  83. package/client/src/stores/storageWarningStore.ts +18 -0
  84. package/client/src/utils/gitDialogMemory.ts +26 -0
  85. package/client/src/utils/historyEvents.ts +1 -0
  86. package/client/src/utils/homeModel.ts +19 -0
  87. package/client/src/utils/publicProject.ts +56 -0
  88. package/client/src/ws/handleServerMessage.ts +7 -2
  89. package/docs/ARCHITECTURE.md +1 -1
  90. package/docs/CHECKPOINTS.md +2 -0
  91. package/docs/CLIENT.md +29 -11
  92. package/docs/FEATURES.md +14 -11
  93. package/docs/GETTING_STARTED.md +7 -7
  94. package/docs/GLOSSARY.md +3 -3
  95. package/docs/GOTCHAS.md +3 -2
  96. package/docs/HTTP_API.md +31 -1
  97. package/docs/NOTIFICATIONS.md +13 -14
  98. package/docs/OPERATIONS.md +27 -1
  99. package/docs/OPERATOR_ACTIONS.md +1 -1
  100. package/docs/OUTPUTS.md +9 -0
  101. package/docs/PERSISTENCE.md +34 -4
  102. package/docs/PLAN_OR_BOARD.md +7 -0
  103. package/docs/PRIMITIVES.md +3 -3
  104. package/docs/PROTOCOL.md +14 -4
  105. package/docs/PROTOCOL_CLUSTER.md +3 -2
  106. package/docs/SERVICE_MODE.md +5 -1
  107. package/docs/SETTINGS.md +8 -6
  108. package/docs/STORAGE_PLAN.md +324 -0
  109. package/docs/TASK_LEDGER.md +5 -4
  110. package/native/linux-arm64/manifest.json +1 -1
  111. package/node_modules/@arco/shared/dist/index.d.ts +2 -0
  112. package/node_modules/@arco/shared/dist/index.js +2 -0
  113. package/node_modules/@arco/shared/dist/protocol/autoPickup.d.ts +1 -1
  114. package/node_modules/@arco/shared/dist/protocol/autoPickup.js +1 -1
  115. package/node_modules/@arco/shared/dist/protocol/checkpoints.d.ts +1 -0
  116. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +2 -1
  117. package/node_modules/@arco/shared/dist/protocol/index.d.ts +1 -0
  118. package/node_modules/@arco/shared/dist/protocol/index.js +1 -0
  119. package/node_modules/@arco/shared/dist/protocol/mdTuneup.d.ts +6 -0
  120. package/node_modules/@arco/shared/dist/protocol/notifications.d.ts +2 -1
  121. package/node_modules/@arco/shared/dist/protocol/notifications.js +3 -2
  122. package/node_modules/@arco/shared/dist/protocol/plans.d.ts +2 -0
  123. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +2 -1
  124. package/node_modules/@arco/shared/dist/protocol/storage.d.ts +21 -0
  125. package/node_modules/@arco/shared/dist/protocol/storage.js +3 -0
  126. package/node_modules/@arco/shared/dist/protocol/tasks.d.ts +3 -0
  127. package/node_modules/@arco/shared/dist/protocol/utilityAgent.d.ts +2 -2
  128. package/node_modules/@arco/shared/dist/protocol/utilityAgent.js +2 -2
  129. package/node_modules/@arco/shared/dist/publicGuardrails.d.ts +7 -0
  130. package/node_modules/@arco/shared/dist/publicGuardrails.js +47 -0
  131. package/node_modules/@arco/shared/dist/publicSafetyRules.d.ts +1 -0
  132. package/node_modules/@arco/shared/dist/publicSafetyRules.js +6 -0
  133. package/node_modules/@arco/shared/package.json +1 -1
  134. package/package.json +3 -2
  135. package/scripts/packaging/arco.mjs +17 -1
  136. package/scripts/packaging/services.mjs +35 -5
  137. package/scripts/packaging/storage.mjs +125 -0
  138. package/scripts/packaging/update.mjs +3 -3
  139. package/server/dist/artifactCopy.d.ts +26 -0
  140. package/server/dist/artifactCopy.js +398 -0
  141. package/server/dist/atomicFile.d.ts +1 -0
  142. package/server/dist/atomicFile.js +1 -1
  143. package/server/dist/attention.d.ts +1 -1
  144. package/server/dist/attention.js +10 -13
  145. package/server/dist/catchUp.d.ts +2 -0
  146. package/server/dist/catchUp.js +46 -23
  147. package/server/dist/clusterPeerOps.d.ts +2 -0
  148. package/server/dist/clusterPeerOps.js +2 -0
  149. package/server/dist/clusterSnapshots.js +22 -12
  150. package/server/dist/eventLog.d.ts +55 -0
  151. package/server/dist/eventLog.js +792 -0
  152. package/server/dist/explorerLaunch.d.ts +4 -1
  153. package/server/dist/explorerLaunch.js +3 -2
  154. package/server/dist/explorerPlans.d.ts +4 -0
  155. package/server/dist/explorerPlans.js +27 -2
  156. package/server/dist/http/clusterRoutes.js +2 -0
  157. package/server/dist/http/explorerRoutes.js +2 -1
  158. package/server/dist/http/publicProjectRoutes.d.ts +2 -0
  159. package/server/dist/http/publicProjectRoutes.js +68 -0
  160. package/server/dist/http/router.js +6 -0
  161. package/server/dist/http/storageRoutes.d.ts +2 -0
  162. package/server/dist/http/storageRoutes.js +254 -0
  163. package/server/dist/http/usageStatsRoutes.js +3 -12
  164. package/server/dist/index.js +4 -0
  165. package/server/dist/keepStore.d.ts +16 -0
  166. package/server/dist/keepStore.js +119 -0
  167. package/server/dist/management/clusterActivity.js +6 -20
  168. package/server/dist/management/initHubLink.js +10 -43
  169. package/server/dist/mcp/clusterMcpTools.js +8 -1
  170. package/server/dist/notifications.d.ts +3 -1
  171. package/server/dist/notifications.js +5 -4
  172. package/server/dist/outputStore.d.ts +1 -0
  173. package/server/dist/outputStore.js +1 -1
  174. package/server/dist/outputs.js +39 -8
  175. package/server/dist/planHistory.d.ts +3 -0
  176. package/server/dist/planHistory.js +60 -0
  177. package/server/dist/primitives/runMdTuneup.d.ts +5 -1
  178. package/server/dist/primitives/runMdTuneup.js +43 -2
  179. package/server/dist/project/taskLedger.d.ts +4 -0
  180. package/server/dist/project/taskLedger.js +19 -0
  181. package/server/dist/providers/claude-native/peerTools.js +4 -0
  182. package/server/dist/providers/claude-native/resumeSummary.js +30 -19
  183. package/server/dist/providers/index.js +8 -13
  184. package/server/dist/providers/localProviderQueue.d.ts +2 -0
  185. package/server/dist/providers/localProviderQueue.js +11 -0
  186. package/server/dist/publicProject.d.ts +54 -0
  187. package/server/dist/publicProject.js +135 -0
  188. package/server/dist/recall/index.js +22 -23
  189. package/server/dist/server/broadcast.d.ts +2 -1
  190. package/server/dist/server/broadcast.js +56 -1
  191. package/server/dist/smartPickupAdapters.d.ts +7 -0
  192. package/server/dist/smartPickupAdapters.js +172 -8
  193. package/server/dist/storageActions.d.ts +50 -0
  194. package/server/dist/storageActions.js +326 -0
  195. package/server/dist/storageArchive.d.ts +24 -0
  196. package/server/dist/storageArchive.js +358 -0
  197. package/server/dist/storageOverview.d.ts +47 -0
  198. package/server/dist/storageOverview.js +197 -0
  199. package/server/dist/storageReport.d.ts +48 -0
  200. package/server/dist/storageReport.js +185 -0
  201. package/server/dist/storageWarnings.d.ts +4 -0
  202. package/server/dist/storageWarnings.js +96 -0
  203. package/server/dist/workers/limits.js +4 -1
  204. package/server/dist/workflowStore.d.ts +2 -0
  205. package/server/dist/workflowStore.js +88 -72
  206. package/server/dist/workflows/purgeWorkflow.d.ts +1 -0
  207. package/server/dist/workflows/purgeWorkflow.js +15 -2
  208. package/server/dist/workflows/sessionDiscovery.js +5 -17
  209. package/server/dist/workflows/sessionIndex.js +22 -17
  210. package/server/dist/ws/taskLedgerHandlers.js +8 -3
  211. package/server/dist/ws/workflowHandlers.js +5 -4
  212. package/server/package.json +1 -1
  213. package/server/src/artifactCopy.ts +254 -0
  214. package/server/src/atomicFile.ts +1 -1
  215. package/server/src/attention.ts +9 -10
  216. package/server/src/catchUp.ts +37 -15
  217. package/server/src/clusterPeerOps.ts +5 -0
  218. package/server/src/clusterSnapshots.ts +20 -13
  219. package/server/src/eventLog.ts +571 -0
  220. package/server/src/explorerLaunch.ts +3 -2
  221. package/server/src/explorerPlans.ts +22 -2
  222. package/server/src/http/clusterRoutes.ts +4 -1
  223. package/server/src/http/explorerRoutes.ts +2 -1
  224. package/server/src/http/publicProjectRoutes.ts +54 -0
  225. package/server/src/http/router.ts +4 -0
  226. package/server/src/http/storageRoutes.ts +187 -0
  227. package/server/src/http/usageStatsRoutes.ts +3 -11
  228. package/server/src/index.ts +4 -0
  229. package/server/src/keepStore.ts +102 -0
  230. package/server/src/management/clusterActivity.ts +6 -16
  231. package/server/src/management/initHubLink.ts +10 -39
  232. package/server/src/mcp/clusterMcpTools.ts +8 -2
  233. package/server/src/notifications.ts +4 -3
  234. package/server/src/outputStore.ts +5 -2
  235. package/server/src/outputs.ts +30 -6
  236. package/server/src/planHistory.ts +48 -0
  237. package/server/src/primitives/runMdTuneup.ts +32 -2
  238. package/server/src/project/taskLedger.ts +20 -0
  239. package/server/src/providers/claude-native/peerTools.ts +4 -0
  240. package/server/src/providers/claude-native/resumeSummary.ts +32 -18
  241. package/server/src/providers/index.ts +2 -16
  242. package/server/src/providers/localProviderQueue.ts +13 -0
  243. package/server/src/publicProject.ts +142 -0
  244. package/server/src/recall/index.ts +4 -9
  245. package/server/src/server/broadcast.ts +53 -1
  246. package/server/src/smartPickupAdapters.ts +128 -5
  247. package/server/src/storageActions.ts +216 -0
  248. package/server/src/storageArchive.ts +277 -0
  249. package/server/src/storageOverview.ts +184 -0
  250. package/server/src/storageReport.ts +210 -0
  251. package/server/src/storageWarnings.ts +84 -0
  252. package/server/src/workers/limits.ts +4 -1
  253. package/server/src/workflowStore.ts +78 -61
  254. package/server/src/workflows/purgeWorkflow.ts +12 -3
  255. package/server/src/workflows/sessionDiscovery.ts +5 -13
  256. package/server/src/workflows/sessionIndex.ts +5 -9
  257. package/server/src/ws/taskLedgerHandlers.ts +8 -3
  258. package/server/src/ws/workflowHandlers.ts +5 -4
  259. package/shared/dist/index.d.ts +2 -0
  260. package/shared/dist/index.js +2 -0
  261. package/shared/dist/protocol/autoPickup.d.ts +1 -1
  262. package/shared/dist/protocol/autoPickup.js +1 -1
  263. package/shared/dist/protocol/checkpoints.d.ts +1 -0
  264. package/shared/dist/protocol/clusters.d.ts +2 -1
  265. package/shared/dist/protocol/index.d.ts +1 -0
  266. package/shared/dist/protocol/index.js +1 -0
  267. package/shared/dist/protocol/mdTuneup.d.ts +6 -0
  268. package/shared/dist/protocol/notifications.d.ts +2 -1
  269. package/shared/dist/protocol/notifications.js +3 -2
  270. package/shared/dist/protocol/plans.d.ts +2 -0
  271. package/shared/dist/protocol/serverMessages.d.ts +2 -1
  272. package/shared/dist/protocol/storage.d.ts +21 -0
  273. package/shared/dist/protocol/storage.js +3 -0
  274. package/shared/dist/protocol/tasks.d.ts +3 -0
  275. package/shared/dist/protocol/utilityAgent.d.ts +2 -2
  276. package/shared/dist/protocol/utilityAgent.js +2 -2
  277. package/shared/dist/publicGuardrails.d.ts +7 -0
  278. package/shared/dist/publicGuardrails.js +47 -0
  279. package/shared/dist/publicSafetyRules.d.ts +1 -0
  280. package/shared/dist/publicSafetyRules.js +6 -0
  281. package/shared/src/index.ts +3 -0
  282. package/shared/src/protocol/autoPickup.ts +1 -1
  283. package/shared/src/protocol/checkpoints.ts +4 -0
  284. package/shared/src/protocol/clusters.ts +6 -1
  285. package/shared/src/protocol/index.ts +1 -0
  286. package/shared/src/protocol/mdTuneup.ts +5 -0
  287. package/shared/src/protocol/notifications.ts +6 -2
  288. package/shared/src/protocol/plans.ts +2 -0
  289. package/shared/src/protocol/serverMessages.ts +2 -0
  290. package/shared/src/protocol/storage.ts +35 -0
  291. package/shared/src/protocol/tasks.ts +6 -0
  292. package/shared/src/protocol/utilityAgent.ts +2 -2
  293. package/shared/src/publicGuardrails.ts +50 -0
  294. package/shared/src/publicSafetyRules.ts +5 -0
  295. package/client/dist/assets/index-CcNtMA2y.js +0 -546
  296. package/client/dist/assets/index-Dl8tYsSp.css +0 -1
@@ -0,0 +1,792 @@
1
+ // Sealed, compressed log segments (P7.3, docs/STORAGE_PLAN.md).
2
+ //
3
+ // A conversation folder holds the live log `events.jsonl` (plain NDJSON,
4
+ // appended by workflowStore) and, once it has grown past the seal threshold,
5
+ // sealed segments `events.<firstSeq>-<lastSeq>.jsonl.br`: Brotli-compressed
6
+ // records, sequence numbers zero-padded to 12 digits so name order is sequence
7
+ // order. Every reader goes through this module and sees one history: segments
8
+ // in order, then the live file, each record once.
9
+ //
10
+ // Sealing never loses a record. Segments are written to a temporary file,
11
+ // flushed and read back before they are renamed into place, and the newest
12
+ // sealed record is copied into the new live file so that a release which
13
+ // reads only `events.jsonl` still continues the sequence. A segment name is
14
+ // never trusted on its own: before a seal drops a live record because a
15
+ // segment's name covers it, that segment is decompressed and checked (every
16
+ // line parses, sequence numbers rise, the first and last match the name). A
17
+ // segment that fails is moved aside (renamed `*.damaged-<time>`, never
18
+ // deleted) and its records are sealed again from the live file. Readers skip
19
+ // live records only up to the newest sequence number they actually read from
20
+ // a segment, or that a checked segment holds.
21
+ import { promises as fs, createReadStream, closeSync, fstatSync, openSync, readFileSync, readSync, readdirSync, statSync, constants as fsConstants } from 'node:fs';
22
+ import { createInterface } from 'node:readline';
23
+ import { brotliCompress, brotliDecompress, brotliDecompressSync, createBrotliDecompress, constants as zc } from 'node:zlib';
24
+ import { promisify } from 'node:util';
25
+ import { randomUUID } from 'node:crypto';
26
+ import path from 'node:path';
27
+ import { renameWithRetry } from './atomicFile.js';
28
+ const compress = promisify(brotliCompress);
29
+ const decompress = promisify(brotliDecompress);
30
+ export const LIVE_LOG = 'events.jsonl';
31
+ export const FORMAT_FILE = 'log-format.json';
32
+ // Format 2 = sealed segments. A release that knows only format 1 (plain log)
33
+ // refuses nothing; a later release that finds a format above the one it knows
34
+ // must refuse to write.
35
+ export const LOG_FORMAT = 2;
36
+ const SEGMENT_RE = /^events\.(\d{12})-(\d{12})\.jsonl\.br$/;
37
+ const SEGMENT_TMP_RE = /^events\.\d{12}-\d{12}\.jsonl\.br\.[0-9a-f-]+\.tmp$/;
38
+ const LIVE_TMP_RE = /^events\.jsonl\.[0-9a-f-]+\.tmp$/;
39
+ const SEQ_RE = /^\{"seq":(\d+)[,}]/;
40
+ export const DEFAULT_SEAL_BYTES = 16 * 1024 * 1024;
41
+ export function sealThresholdBytes() {
42
+ const raw = Number(process.env.ARCO_EVENT_SEGMENT_BYTES);
43
+ return Number.isFinite(raw) && raw >= 1024 ? Math.floor(raw) : DEFAULT_SEAL_BYTES;
44
+ }
45
+ function pad(n) { return String(n).padStart(12, '0'); }
46
+ export function segmentName(firstSeq, lastSeq) {
47
+ return `events.${pad(firstSeq)}-${pad(lastSeq)}.jsonl.br`;
48
+ }
49
+ function parseSegments(dir, names) {
50
+ const out = [];
51
+ for (const name of names) {
52
+ const m = SEGMENT_RE.exec(name);
53
+ if (!m)
54
+ continue;
55
+ out.push({ name, file: path.join(dir, name), firstSeq: Number(m[1]), lastSeq: Number(m[2]) });
56
+ }
57
+ return out.sort((a, b) => a.firstSeq - b.firstSeq || a.lastSeq - b.lastSeq);
58
+ }
59
+ export async function listSegments(dir) {
60
+ try {
61
+ return parseSegments(dir, await fs.readdir(dir));
62
+ }
63
+ catch (err) {
64
+ if (err.code === 'ENOENT')
65
+ return [];
66
+ throw err;
67
+ }
68
+ }
69
+ export function listSegmentsSync(dir) {
70
+ try {
71
+ return parseSegments(dir, readdirSync(dir));
72
+ }
73
+ catch (err) {
74
+ if (err.code === 'ENOENT')
75
+ return [];
76
+ throw err;
77
+ }
78
+ }
79
+ // Sequence number of a record line without a full parse when the line has the
80
+ // writer's shape (`{"seq":N,...`); falls back to JSON for anything else.
81
+ export function lineSeq(line) {
82
+ const m = SEQ_RE.exec(line);
83
+ if (m)
84
+ return Number(m[1]);
85
+ try {
86
+ const v = JSON.parse(line);
87
+ return typeof v.seq === 'number' ? v.seq : null;
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ // A segment's content matches its name: every line is JSON, sequence numbers
94
+ // rise, and the first and last are the ones in the name.
95
+ export function segmentTextMatches(seg, text) {
96
+ if (!text.endsWith('\n'))
97
+ return false;
98
+ let first = null, last = 0;
99
+ for (const line of text.slice(0, -1).split('\n')) {
100
+ let v;
101
+ try {
102
+ v = JSON.parse(line);
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ const seq = v && typeof v === 'object' ? v.seq : undefined;
108
+ if (typeof seq !== 'number')
109
+ continue;
110
+ if (first === null)
111
+ first = seq;
112
+ else if (seq <= last)
113
+ return false;
114
+ last = seq;
115
+ }
116
+ return first === seg.firstSeq && last === seg.lastSeq;
117
+ }
118
+ // Checked segments, by path, size and modification time. A segment this
119
+ // process wrote is entered when its read-back matched.
120
+ const checked = new Map();
121
+ function checkKey(file, st) { return `${file}\0${st.size}\0${st.mtimeMs}`; }
122
+ function remember(key, ok) {
123
+ if (checked.size > 4096)
124
+ checked.clear();
125
+ checked.set(key, ok);
126
+ return ok;
127
+ }
128
+ export async function segmentIsSound(seg) {
129
+ let key;
130
+ try {
131
+ key = checkKey(seg.file, await fs.stat(seg.file));
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ const known = checked.get(key);
137
+ if (known !== undefined)
138
+ return known;
139
+ let text;
140
+ try {
141
+ text = (await decompress(await fs.readFile(seg.file))).toString('utf8');
142
+ }
143
+ catch {
144
+ return remember(key, false);
145
+ }
146
+ return remember(key, segmentTextMatches(seg, text));
147
+ }
148
+ export function segmentIsSoundSync(seg) {
149
+ let key;
150
+ try {
151
+ key = checkKey(seg.file, statSync(seg.file));
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ const known = checked.get(key);
157
+ if (known !== undefined)
158
+ return known;
159
+ let text;
160
+ try {
161
+ text = brotliDecompressSync(readFileSync(seg.file)).toString('utf8');
162
+ }
163
+ catch {
164
+ return remember(key, false);
165
+ }
166
+ return remember(key, segmentTextMatches(seg, text));
167
+ }
168
+ // Newest sequence number held by a segment that passed the check (0 when
169
+ // none did). Tail and head readers drop live records only up to this.
170
+ function trustedThroughSync(segments) {
171
+ for (let i = segments.length - 1; i >= 0; i--)
172
+ if (segmentIsSoundSync(segments[i]))
173
+ return segments[i].lastSeq;
174
+ return 0;
175
+ }
176
+ async function trustedThrough(segments) {
177
+ for (let i = segments.length - 1; i >= 0; i--)
178
+ if (await segmentIsSound(segments[i]))
179
+ return segments[i].lastSeq;
180
+ return 0;
181
+ }
182
+ function lastSeqIn(text) {
183
+ let end = text.length;
184
+ while (end > 0) {
185
+ const start = text.lastIndexOf('\n', end - 1);
186
+ const line = text.slice(start + 1, end);
187
+ if (line) {
188
+ const seq = lineSeq(line);
189
+ if (seq !== null)
190
+ return seq;
191
+ }
192
+ if (start < 0)
193
+ break;
194
+ end = start;
195
+ }
196
+ return 0;
197
+ }
198
+ export class SegmentReadError extends Error {
199
+ file;
200
+ constructor(file, cause) {
201
+ super(`Sealed log segment ${path.basename(file)} could not be read`);
202
+ this.file = file;
203
+ this.cause = cause;
204
+ }
205
+ }
206
+ function reportUnreadable(err) {
207
+ console.error(`[arco] ${err instanceof Error ? err.message : String(err)}; skipping it, the rest of the history stays readable`);
208
+ }
209
+ async function* segmentLines(seg) {
210
+ const input = createReadStream(seg.file);
211
+ const rl = createInterface({ input: input.pipe(createBrotliDecompress()), crlfDelay: Infinity });
212
+ try {
213
+ for await (const line of rl)
214
+ if (line)
215
+ yield line;
216
+ }
217
+ catch (err) {
218
+ throw new SegmentReadError(seg.file, err);
219
+ }
220
+ finally {
221
+ rl.close();
222
+ input.destroy();
223
+ }
224
+ }
225
+ async function openLive(file) {
226
+ try {
227
+ return await fs.open(file, 'r');
228
+ }
229
+ catch (err) {
230
+ if (err.code === 'ENOENT')
231
+ return null;
232
+ throw err;
233
+ }
234
+ }
235
+ async function* handleLines(fh) {
236
+ const input = fh.createReadStream({ autoClose: false });
237
+ const rl = createInterface({ input, crlfDelay: Infinity });
238
+ try {
239
+ for await (const line of rl)
240
+ if (line)
241
+ yield line;
242
+ }
243
+ finally {
244
+ rl.close();
245
+ input.destroy();
246
+ }
247
+ }
248
+ async function* liveLines(file) {
249
+ const fh = await openLive(file);
250
+ if (!fh)
251
+ return;
252
+ try {
253
+ yield* handleLines(fh);
254
+ }
255
+ finally {
256
+ await fh.close();
257
+ }
258
+ }
259
+ // Every record line in sequence order: sealed segments, then the live file.
260
+ // `fromSeq` skips whole segments that end at or before it (callers still
261
+ // filter individual lines, as they did on the plain log). An unreadable
262
+ // segment is reported and skipped; its records show as a gap.
263
+ //
264
+ // A seal can finish while this runs. The live file is opened (and so pinned)
265
+ // before the segment list is read a second time: whichever live file is
266
+ // pinned, every record not in a listed segment is in it, and records already
267
+ // read from a segment are skipped by sequence number. Only sequence numbers
268
+ // actually read count, so a damaged segment never hides live records.
269
+ export async function* readLogLines(dir, opts = {}) {
270
+ const fromSeq = opts.fromSeq ?? 0;
271
+ const done = new Set();
272
+ let sealedThrough = 0;
273
+ async function* drainSegments() {
274
+ for (const seg of await listSegments(dir)) {
275
+ if (done.has(seg.name))
276
+ continue;
277
+ done.add(seg.name);
278
+ // Records at or below fromSeq are dropped by the callers either way.
279
+ if (seg.lastSeq <= fromSeq) {
280
+ sealedThrough = Math.max(sealedThrough, seg.lastSeq);
281
+ continue;
282
+ }
283
+ try {
284
+ for await (const line of segmentLines(seg)) {
285
+ const seq = lineSeq(line);
286
+ if (seq !== null && seq > sealedThrough)
287
+ sealedThrough = seq;
288
+ yield line;
289
+ }
290
+ }
291
+ catch (err) {
292
+ if (err instanceof SegmentReadError)
293
+ reportUnreadable(err);
294
+ else
295
+ throw err;
296
+ }
297
+ }
298
+ }
299
+ yield* drainSegments();
300
+ const fh = await openLive(path.join(dir, LIVE_LOG));
301
+ try {
302
+ yield* drainSegments();
303
+ if (!fh)
304
+ return;
305
+ for await (const line of handleLines(fh)) {
306
+ if (sealedThrough > 0) {
307
+ const seq = lineSeq(line);
308
+ if (seq !== null && seq <= sealedThrough)
309
+ continue;
310
+ }
311
+ yield line;
312
+ }
313
+ }
314
+ finally {
315
+ await fh?.close();
316
+ }
317
+ }
318
+ // The whole history as one NDJSON text (each record once, newline-terminated).
319
+ // Same memory profile as reading a plain log with readFile.
320
+ export async function readLogText(dir) {
321
+ const parts = [];
322
+ for await (const line of readLogLines(dir))
323
+ parts.push(line);
324
+ return parts.length ? parts.join('\n') + '\n' : '';
325
+ }
326
+ function decompressSegmentSync(seg) {
327
+ try {
328
+ return brotliDecompressSync(readFileSync(seg.file)).toString('utf8');
329
+ }
330
+ catch (err) {
331
+ throw new SegmentReadError(seg.file, err);
332
+ }
333
+ }
334
+ function liveTextSync(file) {
335
+ try {
336
+ const text = readFileSync(file, 'utf8');
337
+ return { text, size: Buffer.byteLength(text) };
338
+ }
339
+ catch (err) {
340
+ if (err.code === 'ENOENT')
341
+ return { text: '', size: 0 };
342
+ throw err;
343
+ }
344
+ }
345
+ function dropSealed(text, sealedThrough) {
346
+ if (!sealedThrough || !text)
347
+ return text;
348
+ const lines = text.split('\n');
349
+ let i = 0;
350
+ while (i < lines.length) {
351
+ const line = lines[i];
352
+ if (!line) {
353
+ i++;
354
+ continue;
355
+ }
356
+ const seq = lineSeq(line);
357
+ if (seq !== null && seq <= sealedThrough) {
358
+ i++;
359
+ continue;
360
+ }
361
+ break;
362
+ }
363
+ return lines.slice(i).join('\n');
364
+ }
365
+ export function readLogTextSync(dir) {
366
+ const segments = listSegmentsSync(dir);
367
+ let out = '', sealedThrough = 0;
368
+ for (const seg of segments) {
369
+ let text = '';
370
+ try {
371
+ text = decompressSegmentSync(seg);
372
+ }
373
+ catch (err) {
374
+ reportUnreadable(err);
375
+ }
376
+ out += text;
377
+ sealedThrough = Math.max(sealedThrough, lastSeqIn(text));
378
+ }
379
+ return out + dropSealed(liveTextSync(path.join(dir, LIVE_LOG)).text, sealedThrough);
380
+ }
381
+ // The last `maxBytes` of the history, possibly starting mid-record (callers
382
+ // drop the first line when `truncated`, as they did on the plain log). Reads
383
+ // only the live file's tail when it is long enough; otherwise prepends the
384
+ // newest segments. The live file is pinned before segments are listed (see
385
+ // readLogLines).
386
+ export async function readLogTail(dir, maxBytes) {
387
+ const fh = await openLive(path.join(dir, LIVE_LOG));
388
+ let live = '';
389
+ try {
390
+ if (fh) {
391
+ const size = (await fh.stat()).size;
392
+ if (size >= maxBytes) {
393
+ const buf = Buffer.alloc(maxBytes);
394
+ const { bytesRead } = await fh.read(buf, 0, maxBytes, size - maxBytes);
395
+ return { text: buf.subarray(0, bytesRead).toString('utf8'), truncated: true };
396
+ }
397
+ const buf = Buffer.alloc(size);
398
+ const { bytesRead } = await fh.read(buf, 0, size, 0);
399
+ live = buf.subarray(0, bytesRead).toString('utf8');
400
+ }
401
+ }
402
+ finally {
403
+ await fh?.close();
404
+ }
405
+ const segments = await listSegments(dir);
406
+ let text = dropSealed(live, await trustedThrough(segments));
407
+ let i = segments.length - 1;
408
+ // A damaged segment is reported and skipped; older sound ones still count,
409
+ // as in the full reader.
410
+ while (i >= 0 && Buffer.byteLength(text) < maxBytes) {
411
+ if (!(await segmentIsSound(segments[i]))) {
412
+ reportUnreadable(new SegmentReadError(segments[i].file, 'content does not match its name'));
413
+ i--;
414
+ continue;
415
+ }
416
+ try {
417
+ text = (await segmentText(segments[i])) + text;
418
+ }
419
+ catch (err) {
420
+ if (!(err instanceof SegmentReadError))
421
+ throw err;
422
+ reportUnreadable(err);
423
+ }
424
+ i--;
425
+ }
426
+ return clipTail(text, maxBytes, i >= 0);
427
+ }
428
+ function clipTail(text, maxBytes, more) {
429
+ const bytes = Buffer.from(text, 'utf8');
430
+ if (bytes.length > maxBytes)
431
+ return { text: bytes.subarray(bytes.length - maxBytes).toString('utf8'), truncated: true };
432
+ return { text, truncated: more };
433
+ }
434
+ async function segmentText(seg) {
435
+ const parts = [];
436
+ for await (const line of segmentLines(seg))
437
+ parts.push(line);
438
+ return parts.length ? parts.join('\n') + '\n' : '';
439
+ }
440
+ export function readLogTailSync(dir, maxBytes) {
441
+ const file = path.join(dir, LIVE_LOG);
442
+ let fd = -1;
443
+ try {
444
+ fd = openSync(file, fsConstants.O_RDONLY);
445
+ }
446
+ catch (err) {
447
+ if (err.code !== 'ENOENT')
448
+ throw err;
449
+ }
450
+ let live = '';
451
+ if (fd >= 0) {
452
+ try {
453
+ const size = fstatSync(fd).size;
454
+ const want = Math.min(size, maxBytes);
455
+ const buf = Buffer.alloc(want);
456
+ const n = readSync(fd, buf, 0, want, size - want);
457
+ if (size >= maxBytes)
458
+ return { text: buf.subarray(0, n).toString('utf8'), truncated: true };
459
+ live = buf.subarray(0, n).toString('utf8');
460
+ }
461
+ finally {
462
+ closeSync(fd);
463
+ }
464
+ }
465
+ const segments = listSegmentsSync(dir);
466
+ let text = dropSealed(live, trustedThroughSync(segments));
467
+ let i = segments.length - 1;
468
+ while (i >= 0 && Buffer.byteLength(text) < maxBytes) {
469
+ if (!segmentIsSoundSync(segments[i])) {
470
+ reportUnreadable(new SegmentReadError(segments[i].file, 'content does not match its name'));
471
+ i--;
472
+ continue;
473
+ }
474
+ try {
475
+ text = decompressSegmentSync(segments[i]) + text;
476
+ }
477
+ catch (err) {
478
+ reportUnreadable(err);
479
+ }
480
+ i--;
481
+ }
482
+ return clipTail(text, maxBytes, i >= 0);
483
+ }
484
+ // The first `maxBytes` of the history (synchronous; for head readers such as
485
+ // session titles). Decompresses at most the oldest segments needed.
486
+ export function readLogHeadSync(dir, maxBytes) {
487
+ const segments = listSegmentsSync(dir);
488
+ let text = '', sealedThrough = 0;
489
+ for (const seg of segments) {
490
+ let part = '';
491
+ try {
492
+ part = decompressSegmentSync(seg);
493
+ }
494
+ catch (err) {
495
+ reportUnreadable(err);
496
+ }
497
+ text += part;
498
+ sealedThrough = Math.max(sealedThrough, lastSeqIn(part));
499
+ if (Buffer.byteLength(text) >= maxBytes)
500
+ return Buffer.from(text).subarray(0, maxBytes).toString('utf8');
501
+ }
502
+ const file = path.join(dir, LIVE_LOG);
503
+ let live = '';
504
+ let fd = -1;
505
+ try {
506
+ fd = openSync(file, fsConstants.O_RDONLY);
507
+ }
508
+ catch (err) {
509
+ if (err.code !== 'ENOENT')
510
+ throw err;
511
+ }
512
+ if (fd >= 0) {
513
+ try {
514
+ const want = maxBytes - Buffer.byteLength(text) + 1024 * 1024; // room for the copied sealed record
515
+ const buf = Buffer.alloc(Math.max(0, want));
516
+ const n = readSync(fd, buf, 0, buf.length, 0);
517
+ live = buf.subarray(0, n).toString('utf8');
518
+ }
519
+ finally {
520
+ closeSync(fd);
521
+ }
522
+ }
523
+ text += dropSealed(live, sealedThrough);
524
+ return Buffer.from(text).subarray(0, maxBytes).toString('utf8');
525
+ }
526
+ // Newest sealed sequence number (0 when nothing is sealed). Read from file
527
+ // names only: sequence recovery uses it so that a number is never reused,
528
+ // even one named by a damaged segment. Readers do not use it to drop records.
529
+ export async function sealedThroughSeq(dir) {
530
+ const segments = await listSegments(dir);
531
+ return segments.length ? segments[segments.length - 1].lastSeq : 0;
532
+ }
533
+ // Highest sequence number any segment name has ever claimed, including
534
+ // segments moved aside as damaged (`*.damaged-<time>`), so sequence recovery
535
+ // never hands out a number a segment name already used.
536
+ const NAMED_RE = /^events\.\d{12}-(\d{12})\.jsonl\.br(?:\.damaged-\d+)?$/;
537
+ export async function highestNamedSeq(dir) {
538
+ let names = [];
539
+ try {
540
+ names = await fs.readdir(dir);
541
+ }
542
+ catch (err) {
543
+ if (err.code === 'ENOENT')
544
+ return 0;
545
+ throw err;
546
+ }
547
+ let max = 0;
548
+ for (const name of names) {
549
+ const m = NAMED_RE.exec(name);
550
+ if (m)
551
+ max = Math.max(max, Number(m[1]));
552
+ }
553
+ return max;
554
+ }
555
+ export async function firstSealedSeq(dir) {
556
+ const segments = await listSegments(dir);
557
+ return segments.length ? segments[0].firstSeq : null;
558
+ }
559
+ export async function readLogFormat(dir) {
560
+ try {
561
+ const v = JSON.parse(await fs.readFile(path.join(dir, FORMAT_FILE), 'utf8'));
562
+ return typeof v.format === 'number' ? v.format : 1;
563
+ }
564
+ catch {
565
+ return 1;
566
+ }
567
+ }
568
+ async function fsyncDir(dir) {
569
+ // Directories cannot be opened for fsync on Windows; the rename is still
570
+ // atomic there.
571
+ if (process.platform === 'win32')
572
+ return;
573
+ const fh = await fs.open(dir, 'r');
574
+ try {
575
+ await fh.sync();
576
+ }
577
+ finally {
578
+ await fh.close();
579
+ }
580
+ }
581
+ async function writeDurable(dir, finalName, data, tmpName, verify) {
582
+ const tmp = path.join(dir, tmpName);
583
+ const fh = await fs.open(tmp, 'wx', 0o600);
584
+ try {
585
+ await fh.writeFile(data);
586
+ await fh.sync();
587
+ }
588
+ finally {
589
+ await fh.close();
590
+ }
591
+ if (verify) {
592
+ try {
593
+ await verify(tmp);
594
+ }
595
+ catch (err) {
596
+ await fs.rm(tmp, { force: true });
597
+ throw err;
598
+ }
599
+ }
600
+ // Windows briefly refuses a rename over a file a reader holds open, and
601
+ // keeps refusing while the reader stays. The temporary file never stays.
602
+ try {
603
+ await renameWithRetry(tmp, path.join(dir, finalName));
604
+ }
605
+ catch (err) {
606
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
607
+ throw err;
608
+ }
609
+ await fsyncDir(dir);
610
+ }
611
+ async function removeLeftovers(dir) {
612
+ let names = [];
613
+ try {
614
+ names = await fs.readdir(dir);
615
+ }
616
+ catch {
617
+ return;
618
+ }
619
+ for (const name of names) {
620
+ if (SEGMENT_TMP_RE.test(name) || LIVE_TMP_RE.test(name))
621
+ await fs.rm(path.join(dir, name), { force: true });
622
+ }
623
+ }
624
+ // Test seam: runs just before the live file is replaced.
625
+ export const sealTestHooks = {};
626
+ // A segment whose content does not match its name is renamed out of the
627
+ // segment list (kept on disk for inspection, never deleted).
628
+ async function moveAside(seg) {
629
+ const name = `${seg.name}.damaged-${Date.now()}`;
630
+ await renameWithRetry(seg.file, path.join(path.dirname(seg.file), name));
631
+ console.error(`[arco] sealed log segment ${seg.name} does not match its name; moved aside as ${name}, its records are sealed again from the live log`);
632
+ return name;
633
+ }
634
+ // Seal the live log of one conversation folder. The caller must make sure
635
+ // nothing appends to the live file while this runs (workflowStore runs it in
636
+ // the conversation's flush chain). Records go into segments of at most
637
+ // `segmentBytes` of text each.
638
+ //
639
+ // A live record is dropped only when a segment whose name covers it passes the
640
+ // content check. Live records not covered by a sound segment are sealed into
641
+ // new segments, which never overlap an existing one. The live file is replaced
642
+ // only after every new segment is in place.
643
+ export async function sealLiveLog(dir, segmentBytes = sealThresholdBytes()) {
644
+ const file = path.join(dir, LIVE_LOG);
645
+ try {
646
+ await fs.lstat(file);
647
+ }
648
+ catch (err) {
649
+ if (err.code === 'ENOENT')
650
+ return null;
651
+ throw err;
652
+ }
653
+ if (await readLogFormat(dir) > LOG_FORMAT)
654
+ throw new Error('This conversation log uses a newer storage format; update Arco to write to it.');
655
+ await removeLeftovers(dir);
656
+ const segments = await listSegments(dir);
657
+ const written = [], movedAside = [];
658
+ let records = 0, ptr = 0, coveredAny = false, liveRecords = 0;
659
+ let chunk = [], chunkBytes = 0, chunkFirst = 0, chunkLast = 0;
660
+ // The newest record that is sealed (in a sound segment or a new one); it is
661
+ // copied into the new live file.
662
+ let topSeq = 0, topLine = '';
663
+ const noteTop = (seq, line) => { if (seq > topSeq) {
664
+ topSeq = seq;
665
+ topLine = line;
666
+ } };
667
+ // Lines without a sequence number travel with the records around them; any
668
+ // left at the very end stay in the live file.
669
+ let pendingNoSeq = [];
670
+ const flush = async () => {
671
+ if (!chunk.length)
672
+ return;
673
+ const text = chunk.join('\n') + '\n';
674
+ const data = await compress(Buffer.from(text, 'utf8'), { params: {
675
+ [zc.BROTLI_PARAM_QUALITY]: 5, [zc.BROTLI_PARAM_LGWIN]: 24, [zc.BROTLI_PARAM_SIZE_HINT]: Buffer.byteLength(text),
676
+ } });
677
+ const name = segmentName(chunkFirst, chunkLast);
678
+ // Read the segment back before it is renamed into place.
679
+ await writeDurable(dir, name, data, `${name}.${randomUUID()}.tmp`, async (tmp) => {
680
+ const back = (await decompress(await fs.readFile(tmp))).toString('utf8');
681
+ if (back !== text)
682
+ throw new Error(`Sealed log segment ${name} did not read back correctly`);
683
+ });
684
+ try {
685
+ remember(checkKey(path.join(dir, name), await fs.stat(path.join(dir, name))), true);
686
+ }
687
+ catch { /* checked again on use */ }
688
+ written.push(name);
689
+ records += chunk.length;
690
+ noteTop(chunkLast, chunk[chunk.length - 1]);
691
+ chunk = [];
692
+ chunkBytes = 0;
693
+ chunkFirst = 0;
694
+ chunkLast = 0;
695
+ };
696
+ for await (const line of liveLines(file)) {
697
+ const seq = lineSeq(line);
698
+ if (seq === null) {
699
+ pendingNoSeq.push(line);
700
+ continue;
701
+ }
702
+ liveRecords++;
703
+ while (ptr < segments.length && segments[ptr].lastSeq < seq)
704
+ ptr++;
705
+ const seg = segments[ptr];
706
+ if (seg && seg.firstSeq <= seq) {
707
+ if (await segmentIsSound(seg)) {
708
+ // Already sealed (the copied record, or an interrupted seal).
709
+ await flush();
710
+ pendingNoSeq = [];
711
+ coveredAny = true;
712
+ noteTop(seq, line);
713
+ continue;
714
+ }
715
+ movedAside.push(await moveAside(seg));
716
+ segments.splice(ptr, 1);
717
+ }
718
+ const add = [...pendingNoSeq, line];
719
+ pendingNoSeq = [];
720
+ const addBytes = add.reduce((n, l) => n + Buffer.byteLength(l) + 1, 0);
721
+ // A new segment must not span an existing one.
722
+ const between = ptr > 0 && chunk.length > 0 && segments[ptr - 1].firstSeq > chunkLast;
723
+ if (chunk.length && (between || chunkBytes + addBytes > segmentBytes))
724
+ await flush();
725
+ if (!chunk.length)
726
+ chunkFirst = seq;
727
+ chunk.push(...add);
728
+ chunkBytes += addBytes;
729
+ chunkLast = Math.max(chunkLast, seq);
730
+ }
731
+ await flush();
732
+ // Nothing new to seal and the live file holds at most the copied record.
733
+ if (!written.length && (!coveredAny || liveRecords <= 1))
734
+ return null;
735
+ if (await readLogFormat(dir) < LOG_FORMAT) {
736
+ await writeDurable(dir, FORMAT_FILE, JSON.stringify({ format: LOG_FORMAT }) + '\n', `${FORMAT_FILE}.${randomUUID()}.tmp`);
737
+ }
738
+ const rest = pendingNoSeq.length ? pendingNoSeq.join('\n') + '\n' : '';
739
+ const nextLive = topLine + '\n' + rest;
740
+ try {
741
+ await sealTestHooks.beforeLiveReplace?.();
742
+ await writeDurable(dir, LIVE_LOG, nextLive, `${LIVE_LOG}.${randomUUID()}.tmp`);
743
+ }
744
+ catch (err) {
745
+ console.error(`[arco] sealed log segments are in place, but the live log could not be replaced yet (${err.code ?? 'error'}); it stays complete and the next seal replaces it`);
746
+ let liveBytes = 0;
747
+ try {
748
+ liveBytes = (await fs.stat(file)).size;
749
+ }
750
+ catch { /* gone */ }
751
+ return { segments: written, sealedRecords: records, liveBytes, movedAside, liveReplaced: false };
752
+ }
753
+ return { segments: written, sealedRecords: records, liveBytes: Buffer.byteLength(nextLive), movedAside, liveReplaced: true };
754
+ }
755
+ // Write the whole history back to one plain events.jsonl and remove the
756
+ // segments and the format marker (operator-run export before a downgrade).
757
+ // The plain file is complete and checked before anything is removed.
758
+ export async function unsealLog(dir) {
759
+ const segments = await listSegments(dir);
760
+ if (!segments.length)
761
+ return null;
762
+ const parts = [];
763
+ let last = 0, records = 0;
764
+ for (const seg of segments) {
765
+ for await (const line of segmentLines(seg)) {
766
+ parts.push(line);
767
+ records++;
768
+ const s = lineSeq(line);
769
+ if (s !== null)
770
+ last = Math.max(last, s);
771
+ }
772
+ }
773
+ for await (const line of liveLines(path.join(dir, LIVE_LOG))) {
774
+ const s = lineSeq(line);
775
+ if (s !== null && s <= last)
776
+ continue;
777
+ parts.push(line);
778
+ records++;
779
+ if (s !== null)
780
+ last = Math.max(last, s);
781
+ }
782
+ const text = parts.join('\n') + '\n';
783
+ await writeDurable(dir, LIVE_LOG, text, `${LIVE_LOG}.${randomUUID()}.tmp`);
784
+ const check = await fs.readFile(path.join(dir, LIVE_LOG), 'utf8');
785
+ if (check !== text)
786
+ throw new Error('The exported log did not read back correctly; sealed segments were kept.');
787
+ for (const seg of segments)
788
+ await fs.rm(seg.file, { force: true });
789
+ await fs.rm(path.join(dir, FORMAT_FILE), { force: true });
790
+ return { records, segments: segments.length };
791
+ }
792
+ //# sourceMappingURL=eventLog.js.map