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
@@ -34,6 +34,7 @@ import { readMeta, listWorkflowMetas, latestCliSessionFor, type WorkflowMeta } f
34
34
  import { extractSessionName } from '../workflows/sessionDiscovery.js';
35
35
  import { encodeProjectDir } from '../http/fileRead.js';
36
36
  import { arcoHome } from '../arcoHome.js';
37
+ import { readLogLines } from '../eventLog.js';
37
38
 
38
39
  const WFID_PATTERN = /^[a-zA-Z0-9-]{1,64}$/;
39
40
  const TITLE_MAX = 80;
@@ -695,16 +696,10 @@ async function findAiTitle(meta: WorkflowMeta): Promise<string | undefined> {
695
696
  // first operator message used by the title chain.
696
697
  async function scanEvents(cwd: string, wfid: string): Promise<{ turnCount: number; firstMessage: string }> {
697
698
  if (!WFID_PATTERN.test(wfid)) return { turnCount: 0, firstMessage: '' };
698
- const eventsPath = path.join(cwd, '.arco', 'workflows', wfid, 'events.jsonl');
699
- let raw: string;
700
- try {
701
- raw = await fs.readFile(eventsPath, 'utf8');
702
- } catch {
703
- return { turnCount: 0, firstMessage: '' };
704
- }
705
699
  let turnCount = 0;
706
700
  let firstMessage = '';
707
- for (const line of raw.split('\n')) {
701
+ // Sealed segments and the live file (P7.3).
702
+ try { for await (const line of readLogLines(path.join(cwd, '.arco', 'workflows', wfid))) {
708
703
  if (!line || !line.includes('"user_message_echo"')) continue;
709
704
  let entry: any;
710
705
  try { entry = JSON.parse(line); } catch { continue; }
@@ -713,7 +708,7 @@ async function scanEvents(cwd: string, wfid: string): Promise<{ turnCount: numbe
713
708
  if (!firstMessage && typeof entry.content === 'string' && entry.content.trim()) {
714
709
  firstMessage = entry.content.trim();
715
710
  }
716
- }
711
+ } } catch { return { turnCount, firstMessage }; }
717
712
  return { turnCount, firstMessage };
718
713
  }
719
714
 
@@ -22,6 +22,8 @@ import {
22
22
  } from './state.js';
23
23
  import { WS_BACKPRESSURE_DROP_BYTES } from './constants.js';
24
24
  import { persistAndStampSeq } from '../workflowStore.js';
25
+ import { rememberPlanBody } from '../planHistory.js';
26
+ import { checkArtifactSizes, conversationWarnBytes, fileWarnBytes } from '../storageWarnings.js';
25
27
  import { readMeta, updateMeta } from '../workflowMeta.js';
26
28
  import { appendRecord, matchFileEvent, resolveMatchPath } from '../recentFilesLedger.js';
27
29
  import { artifactsDir } from '../workers/limits.js';
@@ -174,6 +176,9 @@ export function send(ws: WebSocket, message: ServerMessage): void {
174
176
  // ARCHIVE — agent-writes ledger. Native Write/Edit/NotebookEdit tool events
175
177
  // ride the operator turn through send(); record them here.
176
178
  recordFilesLedger(wfid, stamped);
179
+ // P7.4: primary turns end through send(); warn once about very large
180
+ // artifacts (idempotent with the broadcastWorkflow hook).
181
+ if (stamped.type === 'primary_turn_ended' && cwd && source && !source.config.incognito) void reportArtifactSizes(wfid, cwd);
177
182
  // Fan out to every observer of this workflow. Multi-observer so a
178
183
  // second browser window attached to the same workflowId also sees the
179
184
  // stream; previously the single-slot pointer got overwritten on the
@@ -368,6 +373,20 @@ export async function flushPlansWatcher(cwd: string, state: PlansWatcher): Promi
368
373
  }
369
374
  }
370
375
 
376
+ async function reportArtifactSizes(workflowId: string, cwd: string): Promise<void> {
377
+ try {
378
+ const items = await checkArtifactSizes(join(cwd, '.arco', 'workflows', workflowId));
379
+ if (items.length) {
380
+ broadcastWorkflow(workflowId, {
381
+ type: 'storage_warning', workflowId, items,
382
+ fileThresholdBytes: fileWarnBytes(), conversationThresholdBytes: conversationWarnBytes(),
383
+ });
384
+ }
385
+ } catch (err) {
386
+ console.error(`[arco] artifact size check failed for ${workflowId.slice(0, 8)}:`, err);
387
+ }
388
+ }
389
+
371
390
  export function broadcastWorkflow(workflowId: string, message: ServerMessage): void {
372
391
  const wf = workflows.get(workflowId);
373
392
  if (!wf) return;
@@ -415,6 +434,8 @@ export function broadcastWorkflow(workflowId: string, message: ServerMessage): v
415
434
  if (!wf.config.incognito) notifications.onTurnStarted(workflowId);
416
435
  } else if (message.type === 'primary_turn_ended') {
417
436
  clusterIdleNudger.onMemberTurnEnded(workflowId);
437
+ // P7.4: warn once about very large artifacts written during the turn.
438
+ if (cwd && !wf.config.incognito) void reportArtifactSizes(workflowId, cwd);
418
439
  if (!wf.config.incognito) {
419
440
  notifications.onTurnEnded(workflowId, { provider: wf.config.primaryProvider, workflowName: wf.config.name });
420
441
  }
@@ -508,7 +529,38 @@ export function broadcastCluster(clusterId: string, message: ServerMessage): voi
508
529
  if (message.type === 'cluster_plan_changed') {
509
530
  clusterAutoTurn.rulePickupWorkChanged(clusterId);
510
531
  const members = clusterStore.getMembers(clusterId) ?? [];
511
- for (const wfid of members) broadcastWorkflow(wfid, message);
532
+ // P7.2: the audit copy carries the body's hash; the body itself is
533
+ // stored once in the project's plan history (never deleted with plans).
534
+ const hashes = new Map<string, string | null>();
535
+ for (const wfid of members) broadcastWorkflow(wfid, planAuditCopy(message, workflowCwds.get(wfid), hashes));
536
+ }
537
+ }
538
+
539
+ function planAuditCopy(
540
+ message: Extract<ServerMessage, { type: 'cluster_plan_changed' }>,
541
+ cwd: string | undefined,
542
+ hashes: Map<string, string | null>,
543
+ ): ServerMessage {
544
+ if (!cwd || !message.body) return message;
545
+ let hash = hashes.get(cwd);
546
+ if (hash === undefined) { hash = rememberPlanBody(cwd, message.body); hashes.set(cwd, hash); }
547
+ if (!hash) return message;
548
+ const { body: _body, ...rest } = message;
549
+ void _body;
550
+ return { ...rest, bodySha256: hash };
551
+ }
552
+
553
+ // Live-only fan-out to a workflow's open tabs: no sequence number, nothing
554
+ // written to events.jsonl. For full task-board copies (P7.2): the board lives
555
+ // in the ledger store, reconnecting tabs get a fresh copy
556
+ // (sendTaskLedgerSnapshot / task_ledger_list), and recovery folds the
557
+ // persisted task_ledger_event records.
558
+ export function sendWorkflowLive(workflowId: string, message: ServerMessage): void {
559
+ const wf = workflows.get(workflowId);
560
+ if (!wf) return;
561
+ const payload = JSON.stringify(message);
562
+ for (const obs of wf.observers) {
563
+ if (obs.readyState === WebSocket.OPEN) obs.send(payload);
512
564
  }
513
565
  }
514
566
 
@@ -34,6 +34,13 @@ import { ensureLiveTokens } from './providers/claude-native/oauth.js';
34
34
  import { loadTokens } from './providers/claude-native/auth.js';
35
35
  import { CLAUDE_CLI_USER_AGENT } from './providers/claude-native/wireFingerprint.js';
36
36
  import { resolveClaudeAliasFromCatalog } from './providers/claude-native/catalog.js';
37
+ import { getLmstudioBase, probeLmstudio } from './providers/lmstudio.js';
38
+ import { getStrataBase, probeStrata } from './providers/strata.js';
39
+ import { getDeepSeekBase, probeDeepSeek } from './providers/deepseek.js';
40
+ import { llamacppManager } from './providers/llamacppManager.js';
41
+ import { probeLlamacppLive } from './providers/llamacpp.js';
42
+ import { queueLocalProvider, type LocalProviderName } from './providers/localProviderQueue.js';
43
+ import { localModelsUnloading } from './providers/localModelControl.js';
37
44
 
38
45
  export interface EvaluatorRequest {
39
46
  model: string;
@@ -168,15 +175,29 @@ export function claudeAdapter(opts: { fetchImpl?: typeof fetch; tokens?: () => P
168
175
  system: [{ type: 'text', text: CLAUDE_IDENTITY }, { type: 'text', text: req.instructions }],
169
176
  messages: [{ role: 'user', content: req.prompt }],
170
177
  }, { signal });
171
- if (!Array.isArray(resp.content)) throw new EvaluatorRefused('unreadable_answer');
172
- if (resp.content.some((b) => b.type !== 'text')) throw new EvaluatorRefused('non_text_answer');
173
- const text = resp.content.map((b) => (b.type === 'text' ? b.text : '')).join('');
174
- if (text.length > outputCharCap(req.maxOutputTokens)) throw new EvaluatorRefused('output_too_long');
178
+ const blocks: unknown = resp.content;
179
+ const types = Array.isArray(blocks) ? blocks.map((block: unknown) => {
180
+ const type = block && typeof block === 'object' && 'type' in block ? (block as { type?: unknown }).type : undefined;
181
+ return typeof type === 'string' && ['text', 'thinking', 'redacted_thinking', 'tool_use'].includes(type) ? type : 'other';
182
+ }) : [];
183
+ const refuse = (reason: string): never => {
184
+ console.warn(`[arco] Claude evaluator refused: ${reason}; block types: ${types.slice(0, 20).join(',') || 'none'}`);
185
+ throw new EvaluatorRefused(reason);
186
+ };
187
+ if (!Array.isArray(blocks)) return refuse('unreadable_answer');
188
+ if (resp.stop_reason === 'tool_use' || types.includes('tool_use') || types.includes('other')) return refuse('non_text_answer');
189
+ if (blocks.some((b: unknown) => b && typeof b === 'object' && 'type' in b && b.type === 'text' && (!('text' in b) || typeof b.text !== 'string'))) return refuse('unreadable_answer');
190
+ const text = blocks.filter((b: { type?: string }) => b?.type === 'text').map((b: { text: string }) => b.text).join('');
191
+ if (resp.stop_reason === 'max_tokens' || text.length > outputCharCap(req.maxOutputTokens)) return refuse('output_too_long');
192
+ if (!text.trim()) return refuse('empty_answer');
175
193
  return text;
176
194
  } catch (error) {
177
195
  if (signal.aborted) throw signal.reason;
178
196
  if (error instanceof EvaluatorRefused) throw error;
179
- if (error instanceof SyntaxError) throw new EvaluatorRefused('unreadable_answer');
197
+ if (error instanceof SyntaxError) {
198
+ console.warn('[arco] Claude evaluator refused: unreadable_answer; block types: none');
199
+ throw new EvaluatorRefused('unreadable_answer');
200
+ }
180
201
  if (error instanceof Anthropic.APIError) {
181
202
  if (error.status === 401) throw new EvaluatorRefused('not_signed_in');
182
203
  if (error.status) throw new EvaluatorRefused(`provider_http_${error.status}`);
@@ -416,11 +437,113 @@ export function codexAdapter(opts: { launch?: () => [string, string[]]; usable?:
416
437
  };
417
438
  }
418
439
 
440
+ async function boundedLocalResponse(response: Response, maxBytes: number): Promise<unknown> {
441
+ const declared = Number(response.headers.get('content-length'));
442
+ if (Number.isFinite(declared) && declared > maxBytes) throw new EvaluatorRefused('output_too_long');
443
+ if (!response.body) throw new EvaluatorRefused('unreadable_answer');
444
+ const reader = response.body.getReader();
445
+ const chunks: Uint8Array[] = []; let size = 0;
446
+ try {
447
+ for (;;) {
448
+ const { value, done } = await reader.read();
449
+ if (done) break;
450
+ size += value.byteLength;
451
+ if (size > maxBytes) { await reader.cancel(); throw new EvaluatorRefused('output_too_long'); }
452
+ chunks.push(value);
453
+ }
454
+ } finally { reader.releaseLock(); }
455
+ const data = new Uint8Array(size); let offset = 0;
456
+ for (const chunk of chunks) { data.set(chunk, offset); offset += chunk.byteLength; }
457
+ try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(data)); }
458
+ catch { throw new EvaluatorRefused('unreadable_answer'); }
459
+ }
460
+
461
+ // A single bounded, non-streaming OpenAI-compatible request for local models.
462
+ export function openAiCompatibleAdapter(provider: SmartPickupEvaluatorProvider, opts: {
463
+ base: (model: string, signal: AbortSignal) => Promise<string>;
464
+ available: () => Promise<boolean>;
465
+ fetchImpl?: typeof fetch;
466
+ run?: <T>(work: () => Promise<T>) => Promise<T>;
467
+ }): EvaluatorAdapter {
468
+ const fetchImpl = opts.fetchImpl ?? fetch;
469
+ return {
470
+ provider,
471
+ async capability() { try { return { provider, available: await opts.available() }; } catch { return { provider, available: false, reason: 'Local provider is unavailable.' }; } },
472
+ async evaluate(req) {
473
+ const { signal, done } = deadline(req);
474
+ let onAbort: (() => void) | undefined;
475
+ try {
476
+ const perform = async () => {
477
+ signal.throwIfAborted();
478
+ const base = (await opts.base(req.model, signal)).replace(/\/$/, '');
479
+ signal.throwIfAborted();
480
+ const response = await fetchImpl(`${base}/chat/completions`, {
481
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, signal,
482
+ body: JSON.stringify({ model: req.model, stream: false, max_tokens: req.maxOutputTokens, temperature: 0,
483
+ messages: [{ role: 'system', content: req.instructions }, { role: 'user', content: req.prompt }] }),
484
+ });
485
+ if (!response.ok) throw new EvaluatorRefused(response.status === 401 || response.status === 403 ? 'not_signed_in' : `provider_http_${response.status}`);
486
+ const result = await boundedLocalResponse(response, outputCharCap(req.maxOutputTokens) * 4 + 16_384) as { choices?: Array<{ message?: { content?: unknown; tool_calls?: unknown; function_call?: unknown }; finish_reason?: string }> };
487
+ const choice = result && Array.isArray(result.choices) ? result.choices[0] : undefined;
488
+ if ((choice?.message?.tool_calls != null && (!Array.isArray(choice.message.tool_calls) || choice.message.tool_calls.length > 0)) || choice?.message?.function_call || (choice?.finish_reason === 'tool_calls' || choice?.finish_reason === 'function_call')) throw new EvaluatorRefused('tool_attempted');
489
+ if (!choice?.message || !('content' in choice.message)) throw new EvaluatorRefused('unreadable_answer');
490
+ if (typeof choice.message.content !== 'string') throw new EvaluatorRefused('non_text_answer');
491
+ const answer = choice.message.content;
492
+ if (choice.finish_reason === 'length' || answer.length > outputCharCap(req.maxOutputTokens)) throw new EvaluatorRefused('output_too_long');
493
+ if (!answer.trim()) throw new EvaluatorRefused('empty_answer');
494
+ return answer;
495
+ };
496
+ const work = opts.run ? opts.run(perform) : perform();
497
+ const aborted = new Promise<never>((_, reject) => {
498
+ onAbort = () => reject(signal.reason);
499
+ signal.addEventListener('abort', onAbort, { once: true });
500
+ if (signal.aborted) onAbort();
501
+ });
502
+ return await Promise.race([work, aborted]);
503
+ } catch (error) {
504
+ if (signal.aborted) throw signal.reason;
505
+ if (error instanceof EvaluatorRefused) throw error;
506
+ if (error instanceof SyntaxError) throw new EvaluatorRefused('unreadable_answer');
507
+ throw new EvaluatorRefused('unavailable');
508
+ } finally { if (onAbort) signal.removeEventListener('abort', onAbort); done(); }
509
+ },
510
+ };
511
+ }
512
+
513
+ function localRun<T>(provider: LocalProviderName, work: () => Promise<T>): Promise<T> {
514
+ return queueLocalProvider(provider, async () => {
515
+ if (localModelsUnloading()) throw new EvaluatorRefused('unavailable');
516
+ return work();
517
+ });
518
+ }
519
+
520
+ export async function requireLoadedLocalModel(provider: 'lmstudio' | 'strata' | 'deepseek', base: string, model: string, signal: AbortSignal): Promise<string> {
521
+ const url = provider === 'lmstudio' ? `${base.replace(/\/v\d+$/, '')}/api/v1/models` : `${base}/status`;
522
+ const response = await fetch(url, { signal });
523
+ if (!response.ok) throw new EvaluatorRefused('unavailable');
524
+ const body = await boundedLocalResponse(response, 128_000) as { model?: string; loaded?: boolean; models?: Array<{ key?: string; loaded_instances?: Array<{ id?: string }> }> };
525
+ const loaded = provider === 'lmstudio'
526
+ ? body.models?.some((entry) => (entry.key === model && !!entry.loaded_instances?.length) || entry.loaded_instances?.some((instance) => instance.id === model))
527
+ : body.model === model && body.loaded === true;
528
+ if (!loaded) throw new EvaluatorRefused(`model_not_loaded_${provider}`);
529
+ return base;
530
+ }
531
+
419
532
  let adapters: Record<SmartPickupEvaluatorProvider, EvaluatorAdapter> = {
420
533
  ollama: ollamaAdapter(),
421
534
  claude: claudeAdapter(),
422
535
  cursor: cursorAdapter(),
423
536
  codex: codexAdapter(),
537
+ lmstudio: openAiCompatibleAdapter('lmstudio', { base: async (model, signal) => requireLoadedLocalModel('lmstudio', await getLmstudioBase(), model, signal), available: async () => (await probeLmstudio()).up, run: (work) => localRun('lmstudio', work) }),
538
+ strata: openAiCompatibleAdapter('strata', { base: async (model, signal) => requireLoadedLocalModel('strata', await getStrataBase(), model, signal), available: async () => (await probeStrata()).up, run: (work) => localRun('strata', work) }),
539
+ deepseek: openAiCompatibleAdapter('deepseek', { base: async (model, signal) => requireLoadedLocalModel('deepseek', await getDeepSeekBase(), model, signal), available: async () => (await probeDeepSeek()).up, run: (work) => localRun('deepseek', work) }),
540
+ llamacpp: openAiCompatibleAdapter('llamacpp', { base: async (model) => {
541
+ const status = llamacppManager.getStatus();
542
+ if (status.state !== 'ready' || status.alias !== model || !status.port) throw new EvaluatorRefused('model_not_loaded_llamacpp');
543
+ return `http://${llamacppManager.getEndpoint().host}:${status.port}/v1`;
544
+ }, available: async () => (await probeLlamacppLive()).up, run: (work) => localRun('llamacpp', async () => {
545
+ const release = llamacppManager.acquire(); try { return await work(); } finally { release(); }
546
+ }) }),
424
547
  };
425
548
 
426
549
  export function evaluatorAdapter(provider: SmartPickupEvaluatorProvider): EvaluatorAdapter {
@@ -0,0 +1,216 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { STAYING_FILES, holdsKept, isKept, readKeep, withKeepLock } from './keepStore.js';
4
+ import { ensureProjectStateIgnore } from './projectStateIgnore.js';
5
+
6
+ // Operator storage actions (P7.4/P7.5, docs/STORAGE_PLAN.md). Every action is
7
+ // an explicit operator request, never touches plans, skips KEEP items, stops
8
+ // when the KEEP file cannot be read, and is recorded in
9
+ // <project>/.arco/storage-actions.jsonl.
10
+ export class StorageActionError extends Error {
11
+ constructor(readonly code: 'keep_unreadable' | 'busy' | 'open' | 'not_found' | 'kept' | 'exists' | 'invalid' | 'unsafe', message: string) {
12
+ super(message);
13
+ }
14
+ }
15
+
16
+ const WFID = /^[a-zA-Z0-9-]{1,64}$/;
17
+ export function conversationDir(cwd: string, workflowId: string): string {
18
+ if (!WFID.test(workflowId)) throw new StorageActionError('invalid', 'Invalid conversation id.');
19
+ return path.join(cwd, '.arco', 'workflows', workflowId);
20
+ }
21
+
22
+ // Links are never followed by a storage action. The project's `.arco`,
23
+ // `.arco/workflows` and the conversation folder must be real folders (not
24
+ // links), and the folder must resolve to where its path says; otherwise the
25
+ // action is refused before anything is read, written or removed.
26
+ // `mayBeMissing`: a conversation folder that does not exist is fine (restore).
27
+ export async function checkedConversationDir(cwd: string, workflowId: string, opts: { mayBeMissing?: boolean } = {}): Promise<string> {
28
+ const dir = conversationDir(cwd, workflowId);
29
+ for (const p of [path.join(cwd, '.arco'), path.join(cwd, '.arco', 'workflows'), dir]) {
30
+ let st;
31
+ try { st = await fs.lstat(p); }
32
+ catch (err) {
33
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
34
+ if (opts.mayBeMissing && p === dir) return dir;
35
+ throw new StorageActionError('not_found', 'The conversation folder was not found.');
36
+ }
37
+ if (st.isSymbolicLink() || !st.isDirectory()) throw unsafe(path.relative(cwd, p));
38
+ }
39
+ const expected = path.join(await fs.realpath(cwd), '.arco', 'workflows', workflowId);
40
+ if (await fs.realpath(dir) !== expected) throw unsafe(path.relative(cwd, dir));
41
+ return dir;
42
+ }
43
+ export function unsafe(rel: string): StorageActionError {
44
+ return new StorageActionError('unsafe', `${rel.split(path.sep).join('/')} is a link or not a folder, so nothing was changed.`);
45
+ }
46
+ // The project's archive folder: a real folder or missing, never a link.
47
+ export async function checkedArchiveFolder(cwd: string): Promise<void> {
48
+ const p = path.join(cwd, '.arco', 'archive');
49
+ try { const st = await fs.lstat(p); if (st.isSymbolicLink() || !st.isDirectory()) throw unsafe(path.join('.arco', 'archive')); }
50
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
51
+ }
52
+
53
+ // A folder or file inside a checked conversation folder: false when missing,
54
+ // refused when it is a link.
55
+ export async function checkedEntry(dir: string, rel: string): Promise<boolean> {
56
+ try { if ((await fs.lstat(path.join(dir, ...rel.split('/')))).isSymbolicLink()) throw unsafe(rel); return true; }
57
+ catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return false; throw err; }
58
+ }
59
+
60
+ export async function recordStorageAction(cwd: string, entry: Record<string, unknown>): Promise<void> {
61
+ const line = JSON.stringify({ at: Date.now(), ...entry }) + '\n';
62
+ try {
63
+ ensureProjectStateIgnore(cwd);
64
+ await fs.mkdir(path.join(cwd, '.arco'), { recursive: true });
65
+ await fs.appendFile(path.join(cwd, '.arco', 'storage-actions.jsonl'), line, { encoding: 'utf8', mode: 0o600 });
66
+ }
67
+ catch (err) { console.error('[arco] storage action not recorded:', err); }
68
+ }
69
+
70
+ export interface RemovalResult { removedBytes: number; removedFiles: number; keptItems: number }
71
+
72
+ // Remove everything under `root` (relative `rel` inside the conversation)
73
+ // except kept items. Links are removed as links, never followed.
74
+ async function removeExceptKept(dir: string, rel: string, kept: Parameters<typeof isKept>[0], out: RemovalResult): Promise<void> {
75
+ const abs = rel ? path.join(dir, ...rel.split('/')) : dir;
76
+ // The start folder itself is never a link (a link inside is removed as one).
77
+ try { if ((await fs.lstat(abs)).isSymbolicLink()) throw unsafe(rel || '.'); }
78
+ catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return; throw err; }
79
+ let entries;
80
+ try { entries = await fs.readdir(abs, { withFileTypes: true }); }
81
+ catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return; throw err; }
82
+ for (const entry of entries) {
83
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
84
+ const child = path.join(abs, entry.name);
85
+ if (!rel && STAYING_FILES.has(entry.name)) continue;
86
+ if (isKept(kept, childRel)) { out.keptItems++; continue; }
87
+ if (entry.isDirectory() && holdsKept(kept, childRel)) { await removeExceptKept(dir, childRel, kept, out); continue; }
88
+ const size = await treeSize(child);
89
+ await fs.rm(child, { recursive: true, force: true });
90
+ out.removedBytes += size.bytes; out.removedFiles += size.files;
91
+ }
92
+ }
93
+
94
+ export async function treeSize(p: string): Promise<{ bytes: number; files: number }> {
95
+ let bytes = 0, files = 0;
96
+ const stack = [p];
97
+ while (stack.length) {
98
+ const cur = stack.pop()!;
99
+ let st;
100
+ try { st = await fs.lstat(cur); } catch { continue; }
101
+ if (st.isDirectory()) {
102
+ try { for (const name of await fs.readdir(cur)) stack.push(path.join(cur, name)); } catch { /* unreadable */ }
103
+ } else { bytes += st.size; files++; }
104
+ }
105
+ return { bytes, files };
106
+ }
107
+
108
+ // EMPTY SCRATCH: delete the conversation's scratch/ contents except kept
109
+ // items. Refused while the conversation is working and when the KEEP file
110
+ // cannot be read.
111
+ export async function emptyScratch(cwd: string, workflowId: string, opts: { busy: boolean }): Promise<RemovalResult> {
112
+ if (opts.busy) throw new StorageActionError('busy', 'The conversation is working; empty its scratch folder when it is idle.');
113
+ const dir = await checkedConversationDir(cwd, workflowId, { mayBeMissing: true });
114
+ await checkedEntry(dir, 'scratch');
115
+ return withKeepLock(dir, async () => {
116
+ const keep = await readKeep(dir);
117
+ if (!keep.ok) throw new StorageActionError('keep_unreadable', 'The KEEP list of this conversation cannot be read, so nothing was deleted.');
118
+ const out: RemovalResult = { removedBytes: 0, removedFiles: 0, keptItems: 0 };
119
+ if (isKept(keep.items, 'scratch')) { out.keptItems++; return out; }
120
+ await removeExceptKept(dir, 'scratch', keep.items, out);
121
+ await recordStorageAction(cwd, { action: 'empty_scratch', workflowId, removedBytes: out.removedBytes, removedFiles: out.removedFiles, keptItems: out.keptItems });
122
+ return out;
123
+ });
124
+ }
125
+
126
+ // DELETE a closed conversation (P7.5): the existing purge (folder, checkpoints,
127
+ // Recall row, mailbox), plus its archive if it has one. Kept items stay in
128
+ // the conversation folder. Refused for an open or working conversation, a
129
+ // wholly kept one, or an unreadable KEEP list.
130
+ export async function deleteConversation(
131
+ cwd: string, workflowId: string,
132
+ opts: { open: boolean; busy: boolean; purge: (cwd: string, id: string, o: { nuclear: boolean; removeDir?: (dir: string) => Promise<void> }) => Promise<{ ok: boolean; error?: string }>; archiveFile?: string },
133
+ ): Promise<RemovalResult> {
134
+ if (opts.open || opts.busy) throw new StorageActionError('open', 'Close the conversation before deleting it.');
135
+ const dir = await checkedConversationDir(cwd, workflowId, { mayBeMissing: true });
136
+ if (opts.archiveFile) {
137
+ await checkedArchiveFolder(cwd);
138
+ try { if (!(await fs.lstat(opts.archiveFile)).isFile()) throw unsafe(path.relative(cwd, opts.archiveFile)); }
139
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
140
+ }
141
+ return withKeepLock(dir, async () => {
142
+ const keep = await readKeep(dir);
143
+ if (!keep.ok) throw new StorageActionError('keep_unreadable', 'The KEEP list of this conversation cannot be read, so nothing was deleted.');
144
+ if (isKept(keep.items, '.')) throw new StorageActionError('kept', 'The whole conversation is kept.');
145
+ let exists = true;
146
+ try { await fs.lstat(dir); } catch { exists = false; }
147
+ let archived = false;
148
+ if (opts.archiveFile) { try { await fs.lstat(opts.archiveFile); archived = true; } catch { /* none */ } }
149
+ if (!exists && !archived) throw new StorageActionError('not_found', 'The conversation was not found.');
150
+ const out: RemovalResult = { removedBytes: 0, removedFiles: 0, keptItems: 0 };
151
+ if (exists && !keep.items.length) { const size = await treeSize(dir); out.removedBytes += size.bytes; out.removedFiles += size.files; }
152
+ const result = await opts.purge(cwd, workflowId, {
153
+ nuclear: false,
154
+ ...(keep.items.length ? { removeDir: async () => { await removeExceptKept(dir, '', keep.items, out); } } : {}),
155
+ });
156
+ if (!result.ok) throw new Error(result.error || 'The conversation could not be deleted.');
157
+ if (archived && opts.archiveFile) {
158
+ out.removedBytes += (await fs.stat(opts.archiveFile)).size; out.removedFiles++;
159
+ // Checked again right before the removal.
160
+ await checkedArchiveFolder(cwd);
161
+ if (!(await fs.lstat(opts.archiveFile)).isFile()) throw unsafe(path.relative(cwd, opts.archiveFile));
162
+ await fs.rm(opts.archiveFile, { force: true });
163
+ }
164
+ await recordStorageAction(cwd, { action: 'delete', workflowId, removedBytes: out.removedBytes, removedFiles: out.removedFiles, keptItems: out.keptItems });
165
+ return out;
166
+ });
167
+ }
168
+
169
+ // COMPRESS OLD LOGS (operator click, per project): seal the live logs of
170
+ // closed conversations into compressed segments. Open or working
171
+ // conversations are skipped and listed; logs under 1 MiB are not worth it.
172
+ // Lossless: the same sealing as during writes, inside each conversation's
173
+ // flush chain. Nothing is deleted.
174
+ export const COMPRESS_MIN_BYTES = 1024 * 1024;
175
+ // deferred: segments written but the live file is still held open (Windows);
176
+ // the next COMPRESS OLD LOGS or seal finishes it.
177
+ export interface CompressResult { sealed: number; skippedOpen: string[]; failed: number; deferred: number; beforeBytes: number; afterBytes: number }
178
+ export async function compressOldLogs(
179
+ cwd: string,
180
+ opts: { isOpen: (id: string) => boolean; isBusy: (id: string) => boolean; seal: (cwd: string, id: string) => Promise<unknown> },
181
+ ): Promise<CompressResult> {
182
+ const root = path.join(cwd, '.arco', 'workflows');
183
+ const out: CompressResult = { sealed: 0, skippedOpen: [], failed: 0, deferred: 0, beforeBytes: 0, afterBytes: 0 };
184
+ let names: string[] = [];
185
+ try { names = await fs.readdir(root); } catch { names = []; }
186
+ for (const id of names.sort()) {
187
+ if (!WFID.test(id)) continue;
188
+ // Linked folders are never sealed into (checkedConversationDir refuses them).
189
+ try { await checkedConversationDir(cwd, id); } catch { continue; }
190
+ const live = path.join(root, id, 'events.jsonl');
191
+ let size = 0;
192
+ try { const st = await fs.lstat(live); if (!st.isFile()) continue; size = st.size; } catch { continue; }
193
+ if (size < COMPRESS_MIN_BYTES) continue;
194
+ if (opts.isOpen(id) || opts.isBusy(id)) { out.skippedOpen.push(id); continue; }
195
+ const before = await logBytes(path.join(root, id));
196
+ let result: unknown;
197
+ try { result = await opts.seal(cwd, id); }
198
+ catch (err) { out.failed++; console.error(`[arco] compress logs: ${id.slice(0, 8)} not sealed:`, err); continue; }
199
+ if (result && typeof result === 'object' && (result as { liveReplaced?: boolean }).liveReplaced === false) { out.deferred++; continue; }
200
+ const after = await logBytes(path.join(root, id));
201
+ if (after < before) { out.sealed++; out.beforeBytes += before; out.afterBytes += after; }
202
+ }
203
+ await recordStorageAction(cwd, { action: 'compress_logs', sealed: out.sealed, skippedOpen: out.skippedOpen.length, failed: out.failed, deferred: out.deferred, beforeBytes: out.beforeBytes, afterBytes: out.afterBytes });
204
+ return out;
205
+ }
206
+
207
+ async function logBytes(dir: string): Promise<number> {
208
+ let total = 0;
209
+ try {
210
+ for (const name of await fs.readdir(dir)) {
211
+ if (name !== 'events.jsonl' && !/^events\.\d{12}-\d{12}\.jsonl\.br$/.test(name)) continue;
212
+ total += (await fs.lstat(path.join(dir, name))).size;
213
+ }
214
+ } catch { /* unreadable */ }
215
+ return total;
216
+ }