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,277 @@
1
+ import { promises as fs, createReadStream, createWriteStream } from 'node:fs';
2
+ import { createBrotliCompress, createBrotliDecompress, constants as zc } from 'node:zlib';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { pipeline } from 'node:stream/promises';
5
+ import { Readable } from 'node:stream';
6
+ import path from 'node:path';
7
+ import { STAYING_FILES, holdsKept, isKept, readKeep, withKeepLock } from './keepStore.js';
8
+ import { checkedArchiveFolder, checkedConversationDir, conversationDir, recordStorageAction, StorageActionError, unsafe } from './storageActions.js';
9
+ import { renameWithRetry } from './atomicFile.js';
10
+ import { ensureProjectStateIgnore } from './projectStateIgnore.js';
11
+
12
+ // ARCHIVE and restore for closed conversations (P7.5, docs/STORAGE_PLAN.md).
13
+ //
14
+ // An archive is one Brotli-compressed file, <project>/.arco/archive/<id>.arcoarchive:
15
+ // "ARCO-ARCHIVE 1\n"
16
+ // then per file: one JSON header line {path, size, mode, mtimeMs, sha256}
17
+ // followed by exactly `size` bytes and a newline,
18
+ // and a final line {"end": true, "files": N, "workflowId": id, "archivedAt": ms}.
19
+ // The archive is written to a temporary file, read back and checked file by
20
+ // file against the original hashes, renamed into place, and only then are the
21
+ // archived files removed. Kept items (keep.json) stay in the conversation
22
+ // folder and are not archived. Plans are outside conversation folders and
23
+ // never involved.
24
+
25
+ const MAGIC = 'ARCO-ARCHIVE 1\n';
26
+ export const ARCHIVE_SUFFIX = '.arcoarchive';
27
+
28
+ export function archiveDir(cwd: string): string { return path.join(cwd, '.arco', 'archive'); }
29
+ export function archivePath(cwd: string, workflowId: string): string {
30
+ conversationDir(cwd, workflowId); // validates the id
31
+ return path.join(archiveDir(cwd), `${workflowId}${ARCHIVE_SUFFIX}`);
32
+ }
33
+
34
+ interface Entry { path: string; size: number; mode: number; mtimeMs: number; sha256: string }
35
+
36
+ async function hashFile(file: string): Promise<string> {
37
+ const h = createHash('sha256');
38
+ for await (const chunk of createReadStream(file)) h.update(chunk as Buffer);
39
+ return h.digest('hex');
40
+ }
41
+
42
+ // Regular files to archive, relative to the conversation folder, '/' paths.
43
+ // Links are not followed and not archived (they stay, like kept items).
44
+ async function collect(dir: string, kept: Parameters<typeof isKept>[0]): Promise<{ files: Entry[]; skipped: number }> {
45
+ const files: Entry[] = [];
46
+ let skipped = 0;
47
+ const walk = async (rel: string): Promise<void> => {
48
+ const abs = rel ? path.join(dir, ...rel.split('/')) : dir;
49
+ for (const entry of await fs.readdir(abs, { withFileTypes: true })) {
50
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
51
+ if (isKept(kept, childRel)) { skipped++; continue; }
52
+ // The KEEP list and the size-warning record always stay in place, so
53
+ // kept items stay protected after an archive.
54
+ if (!rel && STAYING_FILES.has(entry.name)) { skipped++; continue; }
55
+ const child = path.join(abs, entry.name);
56
+ if (entry.isDirectory()) { await walk(childRel); continue; }
57
+ if (!entry.isFile()) { skipped++; continue; }
58
+ const st = await fs.lstat(child);
59
+ files.push({ path: childRel, size: st.size, mode: st.mode & 0o777, mtimeMs: st.mtimeMs, sha256: await hashFile(child) });
60
+ }
61
+ };
62
+ await walk('');
63
+ return { files, skipped };
64
+ }
65
+
66
+ async function* archiveStream(dir: string, files: Entry[], trailer: Record<string, unknown>): AsyncGenerator<Buffer> {
67
+ yield Buffer.from(MAGIC);
68
+ for (const f of files) {
69
+ yield Buffer.from(JSON.stringify(f) + '\n');
70
+ let written = 0;
71
+ for await (const chunk of createReadStream(path.join(dir, ...f.path.split('/')), { start: 0, end: Math.max(0, f.size - 1) })) {
72
+ if (f.size === 0) break;
73
+ written += (chunk as Buffer).length;
74
+ yield chunk as Buffer;
75
+ }
76
+ if (written !== f.size) throw new Error(`${f.path} changed while it was archived`);
77
+ yield Buffer.from('\n');
78
+ }
79
+ yield Buffer.from(JSON.stringify({ end: true, files: files.length, ...trailer }) + '\n');
80
+ }
81
+
82
+ // Reads an archive and calls `onFile` with each header and its bytes as an
83
+ // async iterable pulled straight from the decompressor (one chunk in memory
84
+ // at a time). Bytes the callback leaves unread are skipped. Returns the trailer.
85
+ async function readArchive(file: string, onFile: (entry: Entry, data: AsyncIterable<Buffer>) => Promise<void>): Promise<Record<string, unknown>> {
86
+ const input = createReadStream(file);
87
+ const source = input.pipe(createBrotliDecompress());
88
+ const it = source[Symbol.asyncIterator]() as AsyncIterator<Buffer>;
89
+ let buf: Buffer = Buffer.alloc(0);
90
+ const fill = async (): Promise<boolean> => {
91
+ const next = await it.next();
92
+ if (next.done) return false;
93
+ buf = buf.length ? Buffer.concat([buf, next.value]) : next.value;
94
+ return true;
95
+ };
96
+ const line = async (): Promise<string> => {
97
+ for (;;) {
98
+ const i = buf.indexOf(10);
99
+ if (i >= 0) { const s = buf.subarray(0, i).toString('utf8'); buf = buf.subarray(i + 1); return s; }
100
+ if (buf.length > 1024 * 1024) throw new Error('The archive is damaged.');
101
+ if (!(await fill())) throw new Error('The archive ends early.');
102
+ }
103
+ };
104
+ try {
105
+ if ((await line()) + '\n' !== MAGIC) throw new Error('Not an Arco archive.');
106
+ for (;;) {
107
+ const header = JSON.parse(await line()) as Entry & { end?: boolean };
108
+ if (header.end) return header as unknown as Record<string, unknown>;
109
+ if (typeof header.path !== 'string' || !Number.isSafeInteger(header.size) || header.size < 0) throw new Error('The archive is damaged.');
110
+ let remaining = header.size;
111
+ const next = async (): Promise<Buffer | null> => {
112
+ if (remaining <= 0) return null;
113
+ if (!buf.length && !(await fill())) throw new Error('The archive ends early.');
114
+ const take = buf.subarray(0, Math.min(remaining, buf.length));
115
+ buf = buf.subarray(take.length);
116
+ remaining -= take.length;
117
+ return take;
118
+ };
119
+ const data: AsyncIterable<Buffer> = { [Symbol.asyncIterator]: () => ({ next: async () => { const v = await next(); return v ? { value: v, done: false } : { value: undefined, done: true }; } }) };
120
+ await onFile(header, data);
121
+ while (await next()) { /* skip what the callback did not read */ }
122
+ if (!buf.length && !(await fill())) throw new Error('The archive ends early.');
123
+ if (buf[0] !== 10) throw new Error('The archive is damaged.');
124
+ buf = buf.subarray(1);
125
+ }
126
+ } finally {
127
+ input.destroy(); source.destroy();
128
+ }
129
+ }
130
+
131
+ function safeRel(rel: string): string {
132
+ const parts = rel.split('/');
133
+ if (!rel || parts.some((p) => !p || p === '.' || p === '..') || path.isAbsolute(rel) || rel.includes('\\') || rel.includes('\0')) {
134
+ throw new Error('The archive holds an unsafe path.');
135
+ }
136
+ return rel;
137
+ }
138
+
139
+ export interface ArchiveResult { files: number; originalBytes: number; archiveBytes: number; keptItems: number }
140
+
141
+ // Every existing part of `rel` below the conversation folder is a real folder
142
+ // or file, not a link.
143
+ async function noLinkOnPath(dir: string, rel: string): Promise<void> {
144
+ const parts = rel.split('/');
145
+ for (let i = 1; i <= parts.length; i++) {
146
+ const sub = parts.slice(0, i).join('/');
147
+ try { if ((await fs.lstat(path.join(dir, ...parts.slice(0, i)))).isSymbolicLink()) throw unsafe(sub); }
148
+ catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return; throw err; }
149
+ }
150
+ }
151
+
152
+ export async function archiveConversation(cwd: string, workflowId: string, opts: { open: boolean; busy: boolean; by: 'operator' | 'policy' }): Promise<ArchiveResult> {
153
+ if (opts.open || opts.busy) throw new StorageActionError('open', 'Close the conversation before archiving it.');
154
+ const dir = await checkedConversationDir(cwd, workflowId);
155
+ await checkedArchiveFolder(cwd);
156
+ const target = archivePath(cwd, workflowId);
157
+ try { await fs.lstat(target); throw new StorageActionError('exists', 'An archive of this conversation already exists.'); }
158
+ catch (err) { if (err instanceof StorageActionError) throw err; }
159
+ // Hold the KEEP lock from the read through the last removal.
160
+ return withKeepLock(dir, async () => {
161
+ const keep = await readKeep(dir);
162
+ if (!keep.ok) throw new StorageActionError('keep_unreadable', 'The KEEP list of this conversation cannot be read, so nothing was archived.');
163
+ if (isKept(keep.items, '.')) throw new StorageActionError('kept', 'The whole conversation is kept.');
164
+ const { files, skipped } = await collect(dir, keep.items);
165
+ const archivedAt = Date.now();
166
+ ensureProjectStateIgnore(cwd);
167
+ await fs.mkdir(archiveDir(cwd), { recursive: true });
168
+ const tmp = `${target}.${randomUUID()}.tmp`;
169
+ try {
170
+ await pipeline(Readable.from(archiveStream(dir, files, { workflowId, archivedAt })),
171
+ createBrotliCompress({ params: { [zc.BROTLI_PARAM_QUALITY]: 4, [zc.BROTLI_PARAM_LGWIN]: 22 } }),
172
+ createWriteStream(tmp, { flags: 'wx', mode: 0o600 }));
173
+ const fh = await fs.open(tmp, 'r+'); try { await fh.sync(); } finally { await fh.close(); }
174
+ // Read back: every file present with the same size and hash.
175
+ const expected = new Map(files.map((f) => [f.path, f]));
176
+ let seen = 0;
177
+ await readArchive(tmp, async (entry, data) => {
178
+ const h = createHash('sha256'); let size = 0;
179
+ for await (const chunk of data) { h.update(chunk as Buffer); size += (chunk as Buffer).length; }
180
+ const want = expected.get(entry.path);
181
+ if (!want || want.size !== size || want.sha256 !== h.digest('hex')) throw new Error(`${entry.path} did not read back correctly`);
182
+ seen++;
183
+ });
184
+ if (seen !== files.length) throw new Error('The archive is incomplete.');
185
+ await renameWithRetry(tmp, target);
186
+ } catch (err) {
187
+ await fs.rm(tmp, { force: true });
188
+ throw err;
189
+ }
190
+ // Remove what was archived; kept items and links stay. A folder swapped
191
+ // for a link since the walk stops the removal.
192
+ for (const f of files) {
193
+ await noLinkOnPath(dir, f.path);
194
+ await fs.rm(path.join(dir, ...f.path.split('/')), { force: true });
195
+ }
196
+ await pruneEmptyFolders(dir, keep.items);
197
+ const archiveBytes = (await fs.stat(target)).size;
198
+ const originalBytes = files.reduce((n, f) => n + f.size, 0);
199
+ await recordStorageAction(cwd, { action: 'archive', by: opts.by, workflowId, files: files.length, originalBytes, archiveBytes, keptItems: skipped });
200
+ return { files: files.length, originalBytes, archiveBytes, keptItems: skipped };
201
+ });
202
+ }
203
+
204
+ async function pruneEmptyFolders(dir: string, kept: Parameters<typeof isKept>[0]): Promise<void> {
205
+ const prune = async (abs: string, rel: string): Promise<boolean> => {
206
+ let entries;
207
+ try { entries = await fs.readdir(abs, { withFileTypes: true }); } catch { return false; }
208
+ let empty = true;
209
+ for (const e of entries) {
210
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
211
+ if (e.isDirectory() && !isKept(kept, childRel) && await prune(path.join(abs, e.name), childRel)) continue;
212
+ empty = false;
213
+ }
214
+ if (empty && rel && !holdsKept(kept, rel)) { await fs.rmdir(abs).catch(() => undefined); return true; }
215
+ return empty && !!rel;
216
+ };
217
+ if (await prune(dir, '') ) await fs.rmdir(dir).catch(() => undefined);
218
+ }
219
+
220
+ export interface RestoreResult { files: number; restoredBytes: number }
221
+
222
+ // Restore into the conversation folder. Refused when any archived file
223
+ // already exists there (nothing is overwritten); the archive is removed only
224
+ // after every file is written and checked.
225
+ export async function restoreConversation(cwd: string, workflowId: string): Promise<RestoreResult> {
226
+ const dir = await checkedConversationDir(cwd, workflowId, { mayBeMissing: true });
227
+ await checkedArchiveFolder(cwd);
228
+ const source = archivePath(cwd, workflowId);
229
+ let sourceStat;
230
+ try { sourceStat = await fs.lstat(source); } catch { throw new StorageActionError('not_found', 'No archive of this conversation was found.'); }
231
+ if (!sourceStat.isFile()) throw unsafe(path.relative(cwd, source));
232
+ // A file that already exists (keep.json included) is never overwritten.
233
+ const collisions: string[] = [];
234
+ // First pass: the whole archive reads back with matching hashes, and no
235
+ // file exists yet. Nothing is written before both hold.
236
+ await readArchive(source, async (entry, data) => {
237
+ const rel = safeRel(entry.path);
238
+ const h = createHash('sha256');
239
+ for await (const chunk of data) h.update(chunk);
240
+ if (h.digest('hex') !== entry.sha256) throw new Error(`${rel} is damaged in the archive; nothing was restored`);
241
+ await noLinkOnPath(dir, rel);
242
+ try { await fs.lstat(path.join(dir, ...rel.split('/'))); collisions.push(rel); } catch { /* free */ }
243
+ });
244
+ if (collisions.length) throw new StorageActionError('exists', `The conversation folder already holds ${collisions[0]}; nothing was restored.`);
245
+ let files = 0, restoredBytes = 0;
246
+ await readArchive(source, async (entry, data) => {
247
+ const rel = safeRel(entry.path);
248
+ const dest = path.join(dir, ...rel.split('/'));
249
+ await noLinkOnPath(dir, rel);
250
+ await fs.mkdir(path.dirname(dest), { recursive: true });
251
+ await noLinkOnPath(dir, rel);
252
+ const tmp = `${dest}.${randomUUID()}.tmp`;
253
+ const h = createHash('sha256');
254
+ async function* hashed() { for await (const c of data) { h.update(c); yield c; } }
255
+ await pipeline(Readable.from(hashed()), createWriteStream(tmp, { flags: 'wx', mode: entry.mode || 0o600 }));
256
+ if (h.digest('hex') !== entry.sha256) { await fs.rm(tmp, { force: true }); throw new Error(`${rel} did not restore correctly`); }
257
+ await renameWithRetry(tmp, dest);
258
+ await fs.utimes(dest, new Date(entry.mtimeMs), new Date(entry.mtimeMs)).catch(() => undefined);
259
+ files++; restoredBytes += entry.size;
260
+ });
261
+ await checkedArchiveFolder(cwd);
262
+ if ((await fs.lstat(source)).isFile()) await fs.rm(source, { force: true });
263
+ await recordStorageAction(cwd, { action: 'restore', workflowId, files, restoredBytes });
264
+ return { files, restoredBytes };
265
+ }
266
+
267
+ export async function listArchives(cwd: string): Promise<Array<{ workflowId: string; bytes: number; archivedAt: number }>> {
268
+ let names: string[] = [];
269
+ try { names = await fs.readdir(archiveDir(cwd)); } catch { return []; }
270
+ const out = [];
271
+ for (const name of names) {
272
+ if (!name.endsWith(ARCHIVE_SUFFIX)) continue;
273
+ const workflowId = name.slice(0, -ARCHIVE_SUFFIX.length);
274
+ try { const st = await fs.stat(path.join(archiveDir(cwd), name)); out.push({ workflowId, bytes: st.size, archivedAt: st.mtimeMs }); } catch { /* vanished */ }
275
+ }
276
+ return out;
277
+ }
@@ -0,0 +1,184 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { arcoHome } from './arcoHome.js';
4
+ import { projectPaths, isChatStorage } from './projects.js';
5
+ import { readKnownCwds } from './explorerArtifacts.js';
6
+ import { snapshot } from './workspace.js';
7
+ import { workflows } from './server/state.js';
8
+ import { scanStorage, type StorageBucketName, type StorageFile } from './storageReport.js';
9
+ import { archiveConversation, listArchives } from './storageArchive.js';
10
+ import { atomicWriteFile } from './atomicFile.js';
11
+ import { readKeep, isKept } from './keepStore.js';
12
+
13
+ // The all-projects STORAGE view, the disk-budget notice and the optional
14
+ // auto-archive rule (P7.5, docs/STORAGE_PLAN.md). Reads use the bounded,
15
+ // read-only storage report; the only write is archiving, and only when the
16
+ // operator turned the rule on.
17
+
18
+ const GiB = 1024 * 1024 * 1024;
19
+ export interface StoragePolicy { version: 1; autoArchiveClosedDays: number | null; budgetGiB: number; budgetNotice: boolean }
20
+ export const DEFAULT_POLICY: StoragePolicy = { version: 1, autoArchiveClosedDays: null, budgetGiB: 100, budgetNotice: true };
21
+
22
+ function policyPath(): string { return path.join(arcoHome(), 'storage-policy.json'); }
23
+
24
+ export async function readPolicy(): Promise<StoragePolicy> {
25
+ try {
26
+ const v = JSON.parse(await fs.readFile(policyPath(), 'utf8')) as Partial<StoragePolicy>;
27
+ return sanitizePolicy(v);
28
+ } catch { return { ...DEFAULT_POLICY }; }
29
+ }
30
+
31
+ export function sanitizePolicy(v: Partial<StoragePolicy>): StoragePolicy {
32
+ const days = v.autoArchiveClosedDays;
33
+ const budget = v.budgetGiB;
34
+ return {
35
+ version: 1,
36
+ autoArchiveClosedDays: typeof days === 'number' && Number.isInteger(days) && days >= 1 && days <= 3650 ? days : null,
37
+ budgetGiB: typeof budget === 'number' && Number.isFinite(budget) && budget >= 1 && budget <= 1_000_000 ? budget : DEFAULT_POLICY.budgetGiB,
38
+ budgetNotice: typeof v.budgetNotice === 'boolean' ? v.budgetNotice : DEFAULT_POLICY.budgetNotice,
39
+ };
40
+ }
41
+
42
+ export async function writePolicy(patch: Partial<StoragePolicy>): Promise<StoragePolicy> {
43
+ const next = sanitizePolicy({ ...(await readPolicy()), ...patch });
44
+ await atomicWriteFile(policyPath(), JSON.stringify(next, null, 2) + '\n');
45
+ return next;
46
+ }
47
+
48
+ export function openWorkflowIds(): Set<string> {
49
+ const ws = snapshot();
50
+ return new Set([...ws.workflows.map((w) => w.workflowId), ...ws.clusters.flatMap((c) => c.memberIds)]);
51
+ }
52
+
53
+ export interface ProjectOverview {
54
+ path: string; kind: 'project' | 'chat'; stateBytes: number;
55
+ buckets: Partial<Record<StorageBucketName, number>>;
56
+ biggest: StorageFile | null; conversations: number; openConversations: number;
57
+ archives: Array<{ workflowId: string; bytes: number; archivedAt: number }>; errors: number;
58
+ }
59
+ export interface StorageOverview {
60
+ measuredAt: number; totalBytes: number;
61
+ home: { stateBytes: number; buckets: Partial<Record<StorageBucketName, number>>; biggest: StorageFile | null };
62
+ projects: ProjectOverview[];
63
+ budget: { enabled: boolean; limitBytes: number; over: boolean };
64
+ }
65
+
66
+ function bucketBytes(buckets: Record<string, { bytes: number }>): Partial<Record<StorageBucketName, number>> {
67
+ const out: Partial<Record<StorageBucketName, number>> = {};
68
+ for (const [name, b] of Object.entries(buckets)) if (b.bytes > 0) out[name as StorageBucketName] = b.bytes;
69
+ return out;
70
+ }
71
+
72
+ async function stateFolders(): Promise<Array<{ path: string; kind: 'project' | 'chat' }>> {
73
+ const seen = new Set<string>();
74
+ const out: Array<{ path: string; kind: 'project' | 'chat' }> = [];
75
+ const add = (p: string, kind: 'project' | 'chat') => { const r = path.resolve(p); if (!seen.has(r)) { seen.add(r); out.push({ path: r, kind }); } };
76
+ for (const p of await projectPaths().catch(() => [])) add(p, 'project');
77
+ for (const p of await readKnownCwds().catch(() => [])) if (isChatStorage(p)) add(p, 'chat');
78
+ return out;
79
+ }
80
+
81
+ async function stateDir(cwd: string): Promise<string | null> {
82
+ const dir = path.join(cwd, '.arco');
83
+ try { const st = await fs.lstat(dir); return st.isDirectory() ? dir : null; } catch { return null; }
84
+ }
85
+
86
+ let cached: { promise: Promise<StorageOverview>; at: number } | null = null;
87
+
88
+ // One scan of every known project and chat state folder and Arco's own
89
+ // folder, one worker at a time. Cached; `refresh` measures again.
90
+ export function storageOverview(refresh = false): Promise<StorageOverview> {
91
+ if (!cached || refresh) {
92
+ const promise = measureAll();
93
+ cached = { promise, at: Date.now() };
94
+ promise.catch(() => { if (cached?.promise === promise) cached = null; });
95
+ }
96
+ return cached.promise;
97
+ }
98
+
99
+ export function cachedOverviewAge(): number | null { return cached ? Date.now() - cached.at : null; }
100
+
101
+ async function measureAll(): Promise<StorageOverview> {
102
+ const open = openWorkflowIds();
103
+ const projects: ProjectOverview[] = [];
104
+ for (const folder of await stateFolders()) {
105
+ const dir = await stateDir(folder.path);
106
+ if (!dir) continue;
107
+ const report = await scanStorage(dir, null, { open: [...open] });
108
+ projects.push({
109
+ path: folder.path, kind: folder.kind, stateBytes: report.stateBytes, buckets: bucketBytes(report.buckets),
110
+ biggest: report.largestFiles[0] ?? null, conversations: report.workflows.length,
111
+ openConversations: report.workflows.filter((w) => w.open).length,
112
+ archives: await listArchives(folder.path), errors: report.errors,
113
+ });
114
+ }
115
+ projects.sort((a, b) => b.stateBytes - a.stateBytes);
116
+ const home = await scanStorage(arcoHome(), null, { scope: 'home' });
117
+ const totalBytes = home.stateBytes + projects.reduce((n, p) => n + p.stateBytes, 0);
118
+ const policy = await readPolicy();
119
+ const limitBytes = policy.budgetGiB * GiB;
120
+ return {
121
+ measuredAt: Date.now(), totalBytes,
122
+ home: { stateBytes: home.stateBytes, buckets: bucketBytes(home.buckets), biggest: home.largestFiles[0] ?? null },
123
+ projects,
124
+ budget: { enabled: policy.budgetNotice, limitBytes, over: policy.budgetNotice && totalBytes > limitBytes },
125
+ };
126
+ }
127
+
128
+ // Conversations closed for at least `days` days: not open, not working, not
129
+ // wholly kept, last written (meta.json or a log file) before the cutoff.
130
+ export async function staleConversations(cwd: string, days: number, now = Date.now()): Promise<string[]> {
131
+ const root = path.join(cwd, '.arco', 'workflows');
132
+ const open = openWorkflowIds();
133
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
134
+ let names: string[] = [];
135
+ try { names = await fs.readdir(root); } catch { return []; }
136
+ const out: string[] = [];
137
+ for (const id of names) {
138
+ if (!/^[a-zA-Z0-9-]{1,64}$/.test(id) || open.has(id) || workflows.get(id)?.busy) continue;
139
+ const dir = path.join(root, id);
140
+ let latest = 0;
141
+ try {
142
+ for (const name of await fs.readdir(dir)) {
143
+ if (name !== 'meta.json' && !name.startsWith('events.')) continue;
144
+ latest = Math.max(latest, (await fs.lstat(path.join(dir, name))).mtimeMs);
145
+ }
146
+ } catch { continue; }
147
+ if (!latest || latest > cutoff) continue;
148
+ const keep = await readKeep(dir);
149
+ if (!keep.ok || isKept(keep.items, '.')) continue;
150
+ out.push(id);
151
+ }
152
+ return out;
153
+ }
154
+
155
+ // The opt-in rule: archive conversations closed for more than N days. Never
156
+ // deletes. Returns how many were archived.
157
+ export async function runAutoArchive(): Promise<number> {
158
+ const policy = await readPolicy();
159
+ if (!policy.autoArchiveClosedDays) return 0;
160
+ let archived = 0;
161
+ for (const folder of await stateFolders()) {
162
+ for (const id of await staleConversations(folder.path, policy.autoArchiveClosedDays)) {
163
+ try { await archiveConversation(folder.path, id, { open: false, busy: false, by: 'policy' }); archived++; }
164
+ catch (err) { console.error(`[arco] auto-archive skipped ${id.slice(0, 8)}: ${err instanceof Error ? err.message : String(err)}`); }
165
+ }
166
+ }
167
+ return archived;
168
+ }
169
+
170
+ let timer: NodeJS.Timeout | null = null;
171
+ // Daily: the auto-archive rule (when on) and a fresh measurement for the
172
+ // disk-budget notice (when on). The first run waits ten minutes after start.
173
+ export function startStoragePolicy(): void {
174
+ if (timer || process.env.ARCO_STORAGE_POLICY === '0') return;
175
+ const run = async () => {
176
+ try {
177
+ const policy = await readPolicy();
178
+ if (policy.autoArchiveClosedDays) await runAutoArchive();
179
+ if (policy.budgetNotice) await storageOverview(true);
180
+ } catch (err) { console.error('[arco] storage policy run failed:', err); }
181
+ };
182
+ timer = setTimeout(function tick() { void run().finally(() => { timer = setTimeout(tick, 24 * 60 * 60 * 1000); timer.unref(); }); }, 10 * 60 * 1000);
183
+ timer.unref();
184
+ }
@@ -0,0 +1,210 @@
1
+ import { Worker } from 'node:worker_threads';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+
5
+ export interface StorageFile { path: string; bytes: number }
6
+ export interface StorageBucket { bytes: number; allocatedBytes: number; files: number }
7
+ // Every byte under a scanned root lands in exactly one bucket. Extra hard links
8
+ // to an already counted file are reported once in `hardLinkBytes` and are not
9
+ // added to any bucket. A nested state folder (another project's state, such as
10
+ // a chat or Genesis project inside the home folder) is skipped and counted in
11
+ // `nestedFolders`; it is measured as its own project.
12
+ export const STORAGE_BUCKETS = [
13
+ 'events', 'artifacts', 'handoffs', 'checkpoints', 'scratch', 'conversationFiles',
14
+ 'plans', 'boards', 'worktrees', 'savedClusters', 'voiceAndModels', 'caches',
15
+ 'providerData', 'logs', 'archives', 'other',
16
+ ] as const;
17
+ export type StorageBucketName = typeof STORAGE_BUCKETS[number];
18
+ export interface StorageWorkflow {
19
+ id: string; open: boolean; lastActive: number; eventBytes: number;
20
+ eventTypes: Record<string, number>; artifactBytes: number; handoffBytes: number;
21
+ checkpointBytes: number; scratchBytes: number; otherBytes: number;
22
+ largestFiles: StorageFile[]; largeFiles: StorageFile[]; errors: number;
23
+ }
24
+ export interface StorageReport {
25
+ measuredAt: number; scope: 'project' | 'home'; stateBytes: number; allocatedBytes: number;
26
+ hardLinkBytes: number; nestedFolders: number; checkpointBytes: number;
27
+ buckets: Record<StorageBucketName, StorageBucket>;
28
+ workflows: StorageWorkflow[]; largestFiles: StorageFile[]; largeFiles: StorageFile[]; errors: number;
29
+ }
30
+
31
+ export const LARGE_FILE_BYTES = 500 * 1024 * 1024;
32
+
33
+ // Parsing and directory traversal run in a worker: even one oversized JSONL
34
+ // record cannot stall the HTTP server. Symlinks are never followed.
35
+ const workerSource = String.raw`
36
+ const { parentPort, workerData } = require('node:worker_threads');
37
+ const fs = require('node:fs/promises');
38
+ const { createReadStream } = require('node:fs');
39
+ const { createBrotliDecompress } = require('node:zlib');
40
+ const path = require('node:path');
41
+ const LIMIT = 10, LARGE = workerData.large, NAMES = workerData.names;
42
+ function emptyBuckets() { const b = {}; for (const n of NAMES) b[n] = { bytes: 0, allocatedBytes: 0, files: 0 }; return b; }
43
+ function pushLargest(list, item) { list.push(item); list.sort((a, b) => b.bytes - a.bytes); if (list.length > LIMIT) list.pop(); }
44
+ function isEventLog(name) { return name === 'events.jsonl' || /^events\.[0-9]+-[0-9]+\.jsonl\.br$/.test(name); }
45
+ // rel: path segments below the scanned root.
46
+ function classifyProject(rel) {
47
+ if (rel[0] === 'workflows' && rel.length >= 3) {
48
+ const part = rel[2];
49
+ if (rel.length === 3 && isEventLog(part)) return 'events';
50
+ if (part === 'artifacts') return 'artifacts';
51
+ if (part === 'handoffs') return 'handoffs';
52
+ if (part === 'checkpoints') return 'checkpoints';
53
+ if (part === 'scratch') return 'scratch';
54
+ return 'conversationFiles';
55
+ }
56
+ if (rel[0] === 'plans') return 'plans';
57
+ if (rel[0] === 'project') return 'boards';
58
+ if (rel[0] === 'worktrees') return 'worktrees';
59
+ if (rel[0] === 'scratch') return 'scratch';
60
+ if (rel[0] === 'archive') return 'archives';
61
+ if (rel.length === 1 && /\.log$/.test(rel[0])) return 'logs';
62
+ return 'other';
63
+ }
64
+ function classifyHome(rel) {
65
+ const top = rel[0];
66
+ if (top === 'checkpoints') return 'checkpoints';
67
+ if (top === 'worktrees' || top === 'bakeoffs') return 'worktrees';
68
+ if (top === 'clusters' && rel[2] === 'isolates') return 'worktrees';
69
+ if (top === 'cluster-snapshots') return 'savedClusters';
70
+ if (top === 'voice' || top === 'models') return 'voiceAndModels';
71
+ if (top === 'media-scratch') return 'scratch';
72
+ if (top === 'cache' || top === 'browser-profile' || top === 'cli-snapshots' || /^camoufox-/.test(top)) return 'caches';
73
+ if (top === 'provider-accounts') return 'providerData';
74
+ if (top === 'logs' || (rel.length === 1 && /\.log$/.test(top))) return 'logs';
75
+ return 'other';
76
+ }
77
+ async function eventTypes(file, counts) {
78
+ try {
79
+ const st = await fs.lstat(file); if (!st.isFile()) return 0;
80
+ let stream = createReadStream(file);
81
+ if (file.endsWith('.br')) stream = stream.pipe(createBrotliDecompress());
82
+ let parts = [], length = 0;
83
+ const type = () => {
84
+ let t = '(unreadable)';
85
+ try { const e = JSON.parse(Buffer.concat(parts, length).toString('utf8')); if (typeof e.type === 'string') t = e.type; } catch {}
86
+ return t;
87
+ };
88
+ for await (const chunk of stream) {
89
+ let start = 0;
90
+ for (let i = 0; i < chunk.length; i++) if (chunk[i] === 10) {
91
+ const part = chunk.subarray(start, i); parts.push(part); length += part.length;
92
+ const t = type(); counts[t] = (counts[t] || 0) + length + 1; parts = []; length = 0; start = i + 1;
93
+ }
94
+ if (start < chunk.length) { const part = chunk.subarray(start); parts.push(part); length += part.length; }
95
+ }
96
+ if (length) { const t = type(); counts[t] = (counts[t] || 0) + length; }
97
+ return 0;
98
+ } catch (e) { return e.code === 'ENOENT' ? 0 : 1; }
99
+ }
100
+ async function walk(root, scope, stateName, open) {
101
+ const buckets = emptyBuckets(); const seen = new Set(); const workflows = new Map();
102
+ let total = 0, allocated = 0, hardLinkBytes = 0, nestedFolders = 0, errors = 0;
103
+ const largest = [], largeFiles = [];
104
+ const classify = scope === 'home' ? classifyHome : classifyProject;
105
+ const stack = [[root, []]];
106
+ while (stack.length) {
107
+ const [dir, rel] = stack.pop(); let entries;
108
+ try { if (!(await fs.lstat(dir)).isDirectory()) continue; entries = await fs.readdir(dir, { withFileTypes: true }); }
109
+ catch (e) { if (e.code !== 'ENOENT') errors++; continue; }
110
+ for (const entry of entries) {
111
+ const p = path.join(dir, entry.name), r = rel.concat(entry.name);
112
+ if (entry.isDirectory()) {
113
+ if (entry.name === stateName) { nestedFolders++; continue; }
114
+ stack.push([p, r]); continue;
115
+ }
116
+ if (!entry.isFile()) continue;
117
+ let st;
118
+ try { st = await fs.lstat(p); if (!st.isFile()) continue; } catch { errors++; continue; }
119
+ if (st.nlink > 1) {
120
+ const key = st.dev + ':' + st.ino;
121
+ if (seen.has(key)) { hardLinkBytes += st.size; continue; }
122
+ seen.add(key);
123
+ }
124
+ const bucket = classify(r); const alloc = (st.blocks || 0) * 512;
125
+ buckets[bucket].bytes += st.size; buckets[bucket].allocatedBytes += alloc; buckets[bucket].files++;
126
+ total += st.size; allocated += alloc;
127
+ if (st.size >= LARGE) largeFiles.push({ path: p, bytes: st.size });
128
+ pushLargest(largest, { path: p, bytes: st.size });
129
+ if (scope === 'project' && r[0] === 'workflows' && r.length >= 3 && /^[a-zA-Z0-9-]{1,64}$/.test(r[1])) {
130
+ let w = workflows.get(r[1]);
131
+ if (!w) {
132
+ w = { id: r[1], open: open.includes(r[1]), lastActive: 0, eventBytes: 0, eventTypes: Object.create(null),
133
+ artifactBytes: 0, handoffBytes: 0, checkpointBytes: 0, scratchBytes: 0, otherBytes: 0,
134
+ largestFiles: [], largeFiles: [], errors: 0, logs: [] };
135
+ workflows.set(r[1], w);
136
+ }
137
+ w.lastActive = Math.max(w.lastActive, st.mtimeMs);
138
+ if (bucket === 'events') { w.eventBytes += st.size; w.logs.push(p); }
139
+ else if (bucket === 'artifacts') w.artifactBytes += st.size;
140
+ else if (bucket === 'handoffs') w.handoffBytes += st.size;
141
+ else if (bucket === 'checkpoints') w.checkpointBytes += st.size;
142
+ else if (bucket === 'scratch') w.scratchBytes += st.size;
143
+ else w.otherBytes += st.size;
144
+ if (st.size >= LARGE) w.largeFiles.push({ path: p, bytes: st.size });
145
+ pushLargest(w.largestFiles, { path: p, bytes: st.size });
146
+ }
147
+ }
148
+ }
149
+ const list = [];
150
+ for (const w of workflows.values()) {
151
+ for (const log of w.logs.sort()) w.errors += await eventTypes(log, w.eventTypes);
152
+ delete w.logs; list.push(w);
153
+ }
154
+ const size = (w) => w.eventBytes + w.artifactBytes + w.handoffBytes + w.checkpointBytes + w.scratchBytes + w.otherBytes;
155
+ list.sort((a, b) => size(b) - size(a));
156
+ return { buckets, total, allocated, hardLinkBytes, nestedFolders, errors, largest, largeFiles, workflows: list };
157
+ }
158
+ async function sizeOf(root) {
159
+ let bytes = 0, errors = 0; const stack = [root];
160
+ while (stack.length) {
161
+ const dir = stack.pop(); let entries;
162
+ try { if (!(await fs.lstat(dir)).isDirectory()) continue; entries = await fs.readdir(dir, { withFileTypes: true }); }
163
+ catch (e) { if (e.code !== 'ENOENT') errors++; continue; }
164
+ for (const entry of entries) {
165
+ const p = path.join(dir, entry.name);
166
+ if (entry.isDirectory()) { stack.push(p); continue; }
167
+ if (!entry.isFile()) continue;
168
+ try { const st = await fs.lstat(p); if (st.isFile()) bytes += st.size; } catch { errors++; }
169
+ }
170
+ }
171
+ return { bytes, errors };
172
+ }
173
+ (async () => {
174
+ const { root, scope, stateName, open, checkpointRoot } = workerData;
175
+ const result = await walk(root, scope, stateName, open);
176
+ const shared = checkpointRoot ? await sizeOf(checkpointRoot) : { bytes: 0, errors: 0 };
177
+ parentPort.postMessage({ measuredAt: Date.now(), scope, stateBytes: result.total, allocatedBytes: result.allocated,
178
+ hardLinkBytes: result.hardLinkBytes, nestedFolders: result.nestedFolders, checkpointBytes: shared.bytes,
179
+ buckets: result.buckets, workflows: result.workflows, largestFiles: result.largest, largeFiles: result.largeFiles,
180
+ errors: result.errors + shared.errors });
181
+ })().catch(e => { throw e; });
182
+ `;
183
+
184
+ export interface ScanOptions {
185
+ scope?: 'project' | 'home';
186
+ // Name of a state folder. A directory with this name below the scanned root
187
+ // is another project's state and is skipped (it is measured on its own).
188
+ stateName?: string;
189
+ open?: string[];
190
+ }
191
+
192
+ export function scanStorage(stateRoot: string, checkpointRoot: string | null, opts: ScanOptions | string[] = {}): Promise<StorageReport> {
193
+ const o: ScanOptions = Array.isArray(opts) ? { open: opts } : opts;
194
+ return new Promise((resolve, reject) => {
195
+ const worker = new Worker(workerSource, {
196
+ eval: true,
197
+ workerData: {
198
+ root: stateRoot, checkpointRoot, scope: o.scope ?? 'project', names: [...STORAGE_BUCKETS],
199
+ stateName: o.stateName ?? '.arco', open: o.open ?? [], large: LARGE_FILE_BYTES,
200
+ },
201
+ });
202
+ worker.once('message', resolve);
203
+ worker.once('error', reject);
204
+ worker.once('exit', (code) => { if (code !== 0) reject(new Error(`Storage scan failed (${code})`)); });
205
+ });
206
+ }
207
+ export function projectCheckpointRoot(home: string, cwd: string): string {
208
+ const hash = createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
209
+ return path.join(home, 'checkpoints', hash);
210
+ }