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,54 @@
1
+ // /api/public-project -- guardrails for public projects (server/src/publicProject.ts).
2
+ // GET /api/public-project/remote?path=... -> { state: 'none' | 'hosted' | 'public', host? }
3
+ // GET /api/public-project/state?path=... -> project state report
4
+ // POST /api/public-project/restore-ignore { path } -> { ok, backup? }
5
+ // POST /api/public-project/stop-tracking { path } -> { ok, removed }
6
+ import { statSync } from 'node:fs';
7
+ import { isAbsolute } from 'node:path';
8
+ import { IncomingMessage, ServerResponse } from 'http';
9
+ import { assertSafePath } from '../fileAccessPolicy.js';
10
+ import { checkProjectState, restoreIgnoreFile, stopTrackingState, suggestFromRemote } from '../publicProject.js';
11
+
12
+ function sendJson(res: ServerResponse, code: number, body: unknown): true {
13
+ res.writeHead(code, { 'Content-Type': 'application/json' });
14
+ res.end(JSON.stringify(body));
15
+ return true;
16
+ }
17
+
18
+ function validDir(value: unknown): string | null {
19
+ if (typeof value !== 'string' || !isAbsolute(value)) return null;
20
+ try { assertSafePath(value); return statSync(value).isDirectory() ? value : null; } catch { return null; }
21
+ }
22
+
23
+ async function readPath(req: IncomingMessage): Promise<unknown> {
24
+ const chunks: Buffer[] = [];
25
+ let size = 0;
26
+ for await (const chunk of req) {
27
+ size += (chunk as Buffer).length;
28
+ if (size > 16 * 1024) return null;
29
+ chunks.push(chunk as Buffer);
30
+ }
31
+ try { return (JSON.parse(Buffer.concat(chunks).toString('utf-8')) as { path?: unknown }).path; } catch { return null; }
32
+ }
33
+
34
+ export async function tryHandlePublicProjectRoutes(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
35
+ const url = new URL(req.url || '/', 'http://localhost');
36
+ if (!url.pathname.startsWith('/api/public-project/')) return false;
37
+ const action = url.pathname.slice('/api/public-project/'.length);
38
+ try {
39
+ if (req.method === 'GET' && (action === 'remote' || action === 'state')) {
40
+ const cwd = validDir(url.searchParams.get('path'));
41
+ if (!cwd) return sendJson(res, 400, { error: 'Choose an existing project folder.' });
42
+ return sendJson(res, 200, action === 'remote' ? await suggestFromRemote(cwd) : await checkProjectState(cwd));
43
+ }
44
+ if (req.method === 'POST' && (action === 'restore-ignore' || action === 'stop-tracking')) {
45
+ const cwd = validDir(await readPath(req));
46
+ if (!cwd) return sendJson(res, 400, { error: 'Choose an existing project folder.' });
47
+ if (action === 'restore-ignore') return sendJson(res, 200, { ok: true, ...restoreIgnoreFile(cwd) });
48
+ return sendJson(res, 200, await stopTrackingState(cwd));
49
+ }
50
+ } catch (err) {
51
+ return sendJson(res, 500, { error: err instanceof Error ? err.message : 'failed' });
52
+ }
53
+ return sendJson(res, 404, { error: 'not found' });
54
+ }
@@ -1,3 +1,4 @@
1
+ import { tryHandleStorageRoutes } from './storageRoutes.js';
1
2
  import { removedProviderReason } from '@arco/shared';
2
3
  import { tryHandleAppVersionRoutes } from './appVersionRoutes.js';
3
4
  import { tryHandleSmartPickupRoutes } from './smartPickupRoutes.js';
@@ -140,6 +141,7 @@ import { tryHandleUsageStatsRoutes } from './usageStatsRoutes.js';
140
141
  import { tryHandleEndpointDiscoveryRoutes } from './endpointDiscoveryRoutes.js';
141
142
  import { tryHandleDiagnosticsRoutes } from './diagnosticsRoutes.js';
142
143
  import { tryHandleProjectRoutes } from './projectRoutes.js';
144
+ import { tryHandlePublicProjectRoutes } from './publicProjectRoutes.js';
143
145
  import { tryHandleProjectTrustRoutes } from './projectTrustRoutes.js';
144
146
  import { tryHandleServicesRoutes } from './servicesRoutes.js';
145
147
  import { tryHandleMediaOpsRoutes } from './mediaOpsRoutes.js';
@@ -462,6 +464,7 @@ export async function handleHttpRequest(
462
464
  // primary_turn_token_usage events under a cwd; no new capture). Distinct
463
465
  // /api/usage-stats prefix, so no collision with /api/usage or /api/recall.
464
466
  if (await tryHandleUsageStatsRoutes(req, res)) return;
467
+ if (await tryHandleStorageRoutes(req, res)) return;
465
468
 
466
469
  // D2 — Endpoint auto-discovery (tailscale peers + localhost, bounded ports).
467
470
  if (await tryHandleEndpointDiscoveryRoutes(req, res)) return;
@@ -473,6 +476,7 @@ export async function handleHttpRequest(
473
476
  // DD7 — project-trust manager (list / record / clear). User-scope file, so it
474
477
  // rides HTTP: the global SettingsPanel has no workflowId for the WS message.
475
478
  if (await tryHandleProjectRoutes(req, res)) return;
479
+ if (await tryHandlePublicProjectRoutes(req, res)) return;
476
480
  if (await tryHandleProjectTrustRoutes(req, res)) return;
477
481
 
478
482
  // Ops L1/L2 — Local services. GET /api/services is read-only enumeration of
@@ -0,0 +1,187 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import path from 'node:path';
3
+ import { arcoHome } from '../arcoHome.js';
4
+ import { snapshot } from '../workspace.js';
5
+ import { realpathWithinProjects } from '../projects.js';
6
+ import { lstat, readFile } from 'node:fs/promises';
7
+ import { projectCheckpointRoot, scanStorage, type StorageReport } from '../storageReport.js';
8
+ import { compressOldLogs, deleteConversation, emptyScratch, StorageActionError } from '../storageActions.js';
9
+ import { sealWorkflowLogNow } from '../workflowStore.js';
10
+ import { archiveConversation, archivePath, listArchives, restoreConversation } from '../storageArchive.js';
11
+ import { isKept, readKeep } from '../keepStore.js';
12
+ import { openWorkflowIds, readPolicy, storageOverview, writePolicy, cachedOverviewAge } from '../storageOverview.js';
13
+ import { purgeWorkflow } from '../workflows/purgeWorkflow.js';
14
+ import { workflows } from '../server/state.js';
15
+ import { addKeep } from '../keepStore.js';
16
+ import { outputDirectory } from '../outputStore.js';
17
+ import { inspectArtifactCopy, copyReviewedArtifact, ignoreCopyDestination } from '../artifactCopy.js';
18
+
19
+ const cache = new Map<string, Promise<StorageReport>>();
20
+ // Not a path, so it cannot collide with a project key.
21
+ const HOME_KEY = '\0home';
22
+ function json(res: ServerResponse, status: number, body: unknown): void {
23
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
24
+ res.end(JSON.stringify(body));
25
+ }
26
+
27
+ async function readJson(req: IncomingMessage): Promise<Record<string, unknown> | null> {
28
+ let size = 0; const chunks: Buffer[] = [];
29
+ for await (const chunk of req) {
30
+ size += (chunk as Buffer).length;
31
+ if (size > 64 * 1024) return null;
32
+ chunks.push(chunk as Buffer);
33
+ }
34
+ try { const v = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}'); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; }
35
+ catch { return null; }
36
+ }
37
+
38
+ // A registered project whose state folder is not a link; null otherwise.
39
+ async function projectFor(cwd: unknown): Promise<string | null> {
40
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return null;
41
+ const key = await realpathWithinProjects(path.resolve(cwd));
42
+ if (!key) return null;
43
+ try { if ((await lstat(path.join(key, '.arco'))).isSymbolicLink()) return null; }
44
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return null; }
45
+ return key;
46
+ }
47
+
48
+ const ACTION_STATUS: Record<StorageActionError['code'], number> = { keep_unreadable: 409, busy: 409, open: 409, kept: 409, exists: 409, unsafe: 409, not_found: 404, invalid: 400 };
49
+
50
+ // Operator storage actions. Each needs `confirm: true`: the client asks first.
51
+ async function handleStorageAction(req: IncomingMessage, res: ServerResponse, action: string): Promise<void> {
52
+ const body = await readJson(req);
53
+ if (!body) return json(res, 400, { error: 'invalid_body' });
54
+ const project = await projectFor(body.path);
55
+ if (!project) return json(res, 403, { error: 'Project is unavailable' });
56
+ if (body.confirm !== true) return json(res, 400, { error: 'confirmation_required' });
57
+ const workflowId = typeof body.workflowId === 'string' ? body.workflowId : '';
58
+ try {
59
+ if (action === 'compress-logs') {
60
+ const open = openWorkflowIds();
61
+ const result = await compressOldLogs(project, { isOpen: (id) => open.has(id), isBusy: (id) => !!workflows.get(id)?.busy, seal: sealWorkflowLogNow });
62
+ return json(res, 200, { ok: true, ...result });
63
+ }
64
+ if (action === 'copy-review' || action === 'copy-confirm' || action === 'copy-ignore') {
65
+ if (typeof body.itemPath !== 'string' || typeof body.destinationFolder !== 'string') return json(res, 400, { error: 'invalid' });
66
+ const declaredPublic = body.publicProject === true;
67
+ const review = await inspectArtifactCopy(project, workflowId, body.itemPath, body.destinationFolder, declaredPublic);
68
+ if (action === 'copy-review') return json(res, 200, review);
69
+ if (typeof body.token !== 'string' || body.token !== review.token) return json(res, 409, { error: 'The artifact or destination changed. Review it again.' });
70
+ if (action === 'copy-ignore') {
71
+ await ignoreCopyDestination(project, review.target);
72
+ return json(res, 200, { ok: true });
73
+ }
74
+ await copyReviewedArtifact(project, workflowId, body.itemPath, body.destinationFolder, declaredPublic, body.token, undefined, body.confirmUnscanned === true);
75
+ return json(res, 200, { ok: true });
76
+ }
77
+ if (action === 'keep') {
78
+ if (typeof body.itemPath !== 'string' || (body.reason !== 'operator' && body.reason !== 'size-warning')) return json(res, 400, { error: 'invalid' });
79
+ const dir = await outputDirectory(project, workflowId);
80
+ const items = await addKeep(dir, body.itemPath, body.reason);
81
+ return json(res, 200, { ok: true, items });
82
+ }
83
+ const busy = !!workflows.get(workflowId)?.busy;
84
+ const open = openWorkflowIds().has(workflowId);
85
+ if (action === 'empty-scratch') {
86
+ const result = await emptyScratch(project, workflowId, { busy });
87
+ return json(res, 200, { ok: true, ...result });
88
+ }
89
+ if (action === 'archive') return json(res, 200, { ok: true, ...(await archiveConversation(project, workflowId, { open, busy, by: 'operator' })) });
90
+ if (action === 'restore') return json(res, 200, { ok: true, ...(await restoreConversation(project, workflowId)) });
91
+ if (action === 'delete') {
92
+ return json(res, 200, { ok: true, ...(await deleteConversation(project, workflowId, { open, busy, purge: purgeWorkflow, archiveFile: archivePath(project, workflowId) })) });
93
+ }
94
+ return json(res, 404, { error: 'unknown_action' });
95
+ } catch (err) {
96
+ if (err instanceof StorageActionError) return json(res, ACTION_STATUS[err.code], { error: err.code, message: err.message });
97
+ if (action === 'keep' || action.startsWith('copy-')) return json(res, 400, { error: err instanceof Error ? err.message : 'The request could not be completed.' });
98
+ console.error('[arco] storage action failed:', err);
99
+ return json(res, 500, { error: 'storage_action_failed' });
100
+ }
101
+ }
102
+
103
+ export async function tryHandleStorageRoutes(req: IncomingMessage, res: ServerResponse): Promise<boolean> {
104
+ const url = new URL(req.url ?? '/', 'http://localhost');
105
+ if (url.pathname === '/api/storage/policy') {
106
+ if (req.method === 'GET') { json(res, 200, await readPolicy()); return true; }
107
+ if (req.method === 'POST') {
108
+ const body = await readJson(req);
109
+ if (!body) { json(res, 400, { error: 'invalid_body' }); return true; }
110
+ const patch: Record<string, unknown> = {};
111
+ for (const key of ['autoArchiveClosedDays', 'budgetGiB', 'budgetNotice']) if (key in body) patch[key] = body[key];
112
+ json(res, 200, await writePolicy(patch));
113
+ return true;
114
+ }
115
+ }
116
+ if (url.pathname === '/api/storage/budget' && req.method === 'GET') {
117
+ // The notice reads the last measurement; it never starts a scan itself.
118
+ const policy = await readPolicy();
119
+ const age = cachedOverviewAge();
120
+ const last = age === null ? null : await storageOverview().catch(() => null);
121
+ json(res, 200, { enabled: policy.budgetNotice, limitBytes: policy.budgetGiB * 1024 ** 3, totalBytes: last?.totalBytes ?? null, measuredAt: last?.measuredAt ?? null, over: !!(policy.budgetNotice && last && last.totalBytes > policy.budgetGiB * 1024 ** 3) });
122
+ return true;
123
+ }
124
+ const actionMatch = /^\/api\/storage\/([a-z-]+)$/.exec(url.pathname);
125
+ if (actionMatch && req.method === 'POST') { await handleStorageAction(req, res, actionMatch[1]); return true; }
126
+ if (url.pathname !== '/api/storage-report' || req.method !== 'GET') return false;
127
+ if (url.searchParams.get('scope') === 'all') {
128
+ try { json(res, 200, await storageOverview(url.searchParams.get('refresh') === '1')); }
129
+ catch { json(res, 500, { error: 'Storage scan failed' }); }
130
+ return true;
131
+ }
132
+ if (url.searchParams.get('scope') === 'home') {
133
+ // Arco's own folder: voice and media models, caches, shared checkpoints,
134
+ // task worktrees, saved clusters. Chat and Genesis project state folders
135
+ // inside it are skipped here and measured as their own projects.
136
+ if (url.searchParams.get('refresh') === '1') cache.delete(HOME_KEY);
137
+ let pending = cache.get(HOME_KEY);
138
+ if (!pending) { pending = scanStorage(arcoHome(), null, { scope: 'home' }); cache.set(HOME_KEY, pending); }
139
+ await respond(res, HOME_KEY, pending);
140
+ return true;
141
+ }
142
+ const cwd = url.searchParams.get('path');
143
+ if (!cwd || !path.isAbsolute(cwd)) {
144
+ res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Absolute path required' })); return true;
145
+ }
146
+ const key = await realpathWithinProjects(path.resolve(cwd));
147
+ if (!key) { res.writeHead(403, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Project is unavailable' })); return true; }
148
+ try { if ((await lstat(path.join(key, '.arco'))).isSymbolicLink()) { res.writeHead(403); res.end(); return true; } } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') { res.writeHead(403); res.end(); return true; } }
149
+ if (url.searchParams.get('refresh') === '1') cache.delete(key);
150
+ let pending = cache.get(key);
151
+ if (!pending) {
152
+ const workspace = snapshot();
153
+ const open = [...workspace.workflows.map(w => w.workflowId), ...workspace.clusters.flatMap(c => c.memberIds)];
154
+ pending = scanStorage(path.join(key, '.arco'), projectCheckpointRoot(arcoHome(), path.resolve(cwd)), { open });
155
+ cache.set(key, pending);
156
+ }
157
+ await respond(res, key, pending, (report) => withConversationState(key, report));
158
+ return true;
159
+ }
160
+
161
+ // Fresh per response (the scan itself is cached): each conversation's name,
162
+ // KEEP state and working state, and the project's archives, for the STORAGE
163
+ // view. KEEP changes and archive actions show without measuring again.
164
+ async function withConversationState(cwd: string, report: StorageReport): Promise<unknown> {
165
+ const conversations = await Promise.all(report.workflows.map(async (w) => {
166
+ const dir = path.join(cwd, '.arco', 'workflows', w.id);
167
+ let name: string | undefined;
168
+ try { const meta = JSON.parse(await readFile(path.join(dir, 'meta.json'), 'utf8')) as { name?: unknown }; if (typeof meta.name === 'string') name = meta.name; }
169
+ catch { /* no meta: archived or partial folder */ }
170
+ const keep = await readKeep(dir);
171
+ return {
172
+ ...w, ...(name ? { name } : {}), busy: !!workflows.get(w.id)?.busy,
173
+ keep: keep.ok ? { readable: true, whole: isKept(keep.items, '.'), items: keep.items.length } : { readable: false, whole: false, items: 0 },
174
+ };
175
+ }));
176
+ return { ...report, workflows: conversations, archives: await listArchives(cwd) };
177
+ }
178
+
179
+ async function respond(res: ServerResponse, key: string, pending: Promise<StorageReport>, shape?: (r: StorageReport) => Promise<unknown>): Promise<void> {
180
+ try {
181
+ const result = shape ? await shape(await pending) : await pending;
182
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(result));
183
+ } catch {
184
+ if (cache.get(key) === pending) cache.delete(key);
185
+ res.writeHead(500, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: 'Storage scan failed' }));
186
+ }
187
+ }
@@ -1,7 +1,6 @@
1
1
  import { IncomingMessage, ServerResponse } from 'http';
2
- import { createReadStream } from 'fs';
2
+ import { readLogLines } from '../eventLog.js';
3
3
  import { promises as fs } from 'fs';
4
- import { createInterface } from 'readline';
5
4
  import path from 'path';
6
5
  import { PORT } from '../server/constants.js';
7
6
  import type {
@@ -193,16 +192,9 @@ export function aggregateUsage(
193
192
  // (mirrors recall/index.ts's tolerant read).
194
193
  async function collectWorkflowUsage(cwd: string, wfid: string, out: unknown[]): Promise<void> {
195
194
  if (!WFID_PATTERN.test(wfid)) return;
196
- const eventsPath = path.join(cwd, '.arco', 'workflows', wfid, 'events.jsonl');
197
- let stream;
198
195
  try {
199
- stream = createReadStream(eventsPath, { encoding: 'utf8' });
200
- } catch {
201
- return;
202
- }
203
- try {
204
- const rl = createInterface({ input: stream, crlfDelay: Infinity });
205
- for await (const line of rl) {
196
+ // Sealed segments, then the live file (P7.3).
197
+ for await (const line of readLogLines(path.join(cwd, '.arco', 'workflows', wfid))) {
206
198
  // Cheap pre-filter before JSON.parse — most lines aren't usage events.
207
199
  if (!line || !line.includes('"primary_turn_token_usage"')) continue;
208
200
  let entry: unknown;
@@ -277,6 +277,7 @@ import {
277
277
  import { resolveOrphanedGate, handleGateRevoke } from './ws/gateHandlers.js';
278
278
  import { checkRequestOrigin } from './http/originGuard.js';
279
279
  import { checkUpgradeAuth, describePeer, wsAuthEnabled } from './http/wsAuth.js';
280
+ import { startStoragePolicy } from './storageOverview.js';
280
281
 
281
282
  // Strict-incognito exception list, read by the protocol fence in the ws
282
283
  // message handler below. That fence rejects every config
@@ -2228,6 +2229,9 @@ function onListening() {
2228
2229
  },
2229
2230
  });
2230
2231
  clusterIdleNudger.start();
2232
+ // P7.5: daily storage measurement for the disk-budget notice and the
2233
+ // opt-in auto-archive rule (off by default; never deletes).
2234
+ startStoragePolicy();
2231
2235
 
2232
2236
  // docs/PROTOCOL_CLUSTER.md - configure the auto-turn detector. The
2233
2237
  // detector itself has no timer (it runs inline off broadcastWorkflow's
@@ -0,0 +1,102 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import type { KeepItem } from '@arco/shared';
4
+ import { atomicWriteFile, withFileLock } from './atomicFile.js';
5
+
6
+ // Reader for the per-conversation KEEP file (docs/STORAGE_PLAN.md, "KEEP file
7
+ // format"): <project>/.arco/workflows/<id>/keep.json. Builder of the KEEP and
8
+ // MOVE TO PROJECT controls owns the writer; archive, delete, EMPTY SCRATCH and
9
+ // size warnings read it here.
10
+ export const KEEP_FILE = 'keep.json';
11
+
12
+ // One in-process lock per conversation KEEP list. The KEEP writer and every
13
+ // action that reads the list and then removes files (archive, delete, EMPTY
14
+ // SCRATCH) hold it from the read through the last removal, so a KEEP set
15
+ // meanwhile is never undone. Use exactly this key: withFileLock matches keys
16
+ // as strings.
17
+ export function keepLockKey(conversationDir: string): string {
18
+ return path.join(path.resolve(conversationDir), KEEP_FILE);
19
+ }
20
+ export function withKeepLock<T>(conversationDir: string, fn: () => Promise<T>): Promise<T> {
21
+ return withFileLock(keepLockKey(conversationDir), fn);
22
+ }
23
+
24
+ // Files of the conversation folder itself that every storage action leaves
25
+ // in place: the KEEP list and the record of size warnings already shown.
26
+ export const STAYING_FILES = new Set([KEEP_FILE, 'storage-warnings.json']);
27
+
28
+ export type KeepRead = { ok: true; items: KeepItem[] } | { ok: false };
29
+
30
+ // Normalized relative path: '/' separators, no '.', '..' or empty parts.
31
+ // Returns null for anything that could leave the conversation folder.
32
+ export function normalizeKeepPath(raw: string): string | null {
33
+ if (typeof raw !== 'string' || raw.length > 4096 || raw.includes('\0')) return null;
34
+ if (raw === '.' || raw === '') return '.';
35
+ const parts = raw.replace(/\\/g, '/').split('/').filter((p) => p !== '' && p !== '.');
36
+ if (!parts.length) return '.';
37
+ if (parts.some((p) => p === '..') || path.isAbsolute(raw) || /^[a-zA-Z]:/.test(raw)) return null;
38
+ return parts.join('/');
39
+ }
40
+
41
+ // Missing file: nothing is kept. Unreadable or malformed file: { ok: false };
42
+ // archive and delete must stop and ask instead of acting.
43
+ export async function readKeep(conversationDir: string): Promise<KeepRead> {
44
+ let raw: string;
45
+ try { raw = await fs.readFile(path.join(conversationDir, KEEP_FILE), 'utf8'); }
46
+ catch (err) { return (err as NodeJS.ErrnoException).code === 'ENOENT' ? { ok: true, items: [] } : { ok: false }; }
47
+ try {
48
+ const value = JSON.parse(raw) as { version?: unknown; items?: unknown };
49
+ if (value.version !== 1 || !Array.isArray(value.items)) return { ok: false };
50
+ const items: KeepItem[] = [];
51
+ for (const item of value.items as Array<Partial<KeepItem>>) {
52
+ const p = normalizeKeepPath(item?.path as string);
53
+ if (p === null || (item.reason !== 'operator' && item.reason !== 'size-warning')) return { ok: false };
54
+ items.push({ path: p, reason: item.reason, at: Number(item.at) || 0 });
55
+ }
56
+ return { ok: true, items };
57
+ } catch { return { ok: false }; }
58
+ }
59
+
60
+ // True when `rel` (relative to the conversation folder) is kept: the path
61
+ // itself, or a folder above it, or the whole conversation.
62
+ export function isKept(items: KeepItem[], rel: string): boolean {
63
+ const p = normalizeKeepPath(rel);
64
+ if (p === null) return false;
65
+ return items.some((k) => k.path === '.' || k.path === p || p.startsWith(`${k.path}/`));
66
+ }
67
+
68
+ // True when something below `rel` is kept (so `rel` itself cannot be removed
69
+ // as a whole).
70
+ export function holdsKept(items: KeepItem[], rel: string): boolean {
71
+ const p = normalizeKeepPath(rel);
72
+ if (p === null) return true;
73
+ return items.some((k) => k.path.startsWith(`${p}/`));
74
+ }
75
+
76
+ // Add a protection atomically; malformed existing metadata is never overwritten.
77
+ export async function addKeep(conversationDir: string, raw: string, reason: KeepItem['reason']): Promise<KeepItem[]> {
78
+ const rel = normalizeKeepPath(raw);
79
+ if (rel === null || (rel !== '.' && !/^(artifacts|scratch)(?:\/|$)/.test(rel))) throw new Error('Invalid KEEP path.');
80
+ if (reason !== 'operator' && reason !== 'size-warning') throw new Error('Invalid KEEP reason.');
81
+ const file = path.join(conversationDir, KEEP_FILE);
82
+ return withKeepLock(conversationDir, async () => {
83
+ let current = conversationDir;
84
+ const root = await fs.lstat(current);
85
+ if (!root.isDirectory() || root.isSymbolicLink()) throw new Error('Conversation is unavailable.');
86
+ for (const part of rel === '.' ? [] : rel.split('/')) {
87
+ current = path.join(current, part);
88
+ const st = await fs.lstat(current);
89
+ if (st.isSymbolicLink() || (!st.isDirectory() && !st.isFile())) throw new Error('KEEP does not follow links.');
90
+ }
91
+ try { if ((await fs.lstat(file)).isSymbolicLink()) throw new Error('KEEP file cannot be a link.'); }
92
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
93
+ const existing = await readKeep(conversationDir);
94
+ if (!existing.ok) throw new Error('The KEEP list cannot be read; nothing was changed.');
95
+ if (!isKept(existing.items, rel)) {
96
+ if (existing.items.length >= 10000) throw new Error('The KEEP list is full.');
97
+ existing.items.push({ path: rel, reason, at: Date.now() });
98
+ await atomicWriteFile(file, JSON.stringify({ version: 1, items: existing.items }) + '\n', { mode: 0o600, skipMkdir: true });
99
+ }
100
+ return existing.items;
101
+ });
102
+ }
@@ -7,7 +7,7 @@
7
7
  // their turn's completion row (a count, not one row per call) so the feed
8
8
  // stays scannable on a phone.
9
9
 
10
- import { openSync, fstatSync, readSync, closeSync } from 'node:fs';
10
+ import { readLogTailSync } from '../eventLog.js';
11
11
  import { join } from 'node:path';
12
12
  import type { ClusterActivityRow } from '@arco/shared';
13
13
 
@@ -18,18 +18,12 @@ export const ACTIVITY_MAX_ROWS = 200; // merged cap (most recent kept)
18
18
  // Bounded tail read of one member's events.jsonl → activity rows. Best-effort:
19
19
  // unreadable/absent logs yield []. Exported for the unit test.
20
20
  export function readMemberActivity(cwd: string, wfid: string): ClusterActivityRow[] {
21
- let fd: number | undefined;
22
21
  try {
23
- const path = join(cwd, '.arco', 'workflows', wfid, 'events.jsonl');
24
- fd = openSync(path, 'r');
25
- const size = fstatSync(fd).size;
26
- if (size === 0) return [];
27
- const start = Math.max(0, size - TAIL_BYTES);
28
- const len = size - start;
29
- const buf = Buffer.allocUnsafe(len);
30
- readSync(fd, buf, 0, len, start);
31
- const lines = buf.toString('utf8').split('\n');
32
- if (start > 0) lines.shift(); // drop the partial first line
22
+ // Live tail, plus sealed segments when the live file is short (P7.3).
23
+ const tail = readLogTailSync(join(cwd, '.arco', 'workflows', wfid), TAIL_BYTES);
24
+ if (!tail.text) return [];
25
+ const lines = tail.text.split('\n');
26
+ if (tail.truncated) lines.shift(); // drop the partial first line
33
27
 
34
28
  const rows: ClusterActivityRow[] = [];
35
29
  let toolCount = 0;
@@ -86,10 +80,6 @@ export function readMemberActivity(cwd: string, wfid: string): ClusterActivityRo
86
80
  return rows;
87
81
  } catch {
88
82
  return [];
89
- } finally {
90
- if (fd !== undefined) {
91
- try { closeSync(fd); } catch { /* ignore */ }
92
- }
93
83
  }
94
84
  }
95
85
 
@@ -8,7 +8,6 @@
8
8
  // routed reply/stop/continue actions — re-validating against current state.
9
9
 
10
10
  import { WebSocket } from 'ws';
11
- import { openSync, fstatSync, readSync, closeSync } from 'node:fs';
12
11
  import { join } from 'node:path';
13
12
  import { workflows, workflowCwds } from '../server/state.js';
14
13
  import { handleUserMessage } from '../ws/turnEngine.js';
@@ -74,6 +73,7 @@ import type {
74
73
  } from '@arco/shared';
75
74
  import { createHubLink, type HubLink } from './hubLink.js';
76
75
  import { buildServiceInstanceDescriptor } from './identity.js';
76
+ import { readLogTailSync } from '../eventLog.js';
77
77
 
78
78
  // Bounded read of the events.jsonl tail. Generous because ledger-snapshot
79
79
  // events (task_ledger_snapshot can be large + frequent) crowd the tail and push
@@ -92,18 +92,12 @@ function readLastMessage(
92
92
  cwd: string,
93
93
  wfid: string,
94
94
  ): { text: string; role: 'assistant'; at: number; durationMs?: number } | undefined {
95
- let fd: number | undefined;
96
95
  try {
97
- const path = join(cwd, '.arco', 'workflows', wfid, 'events.jsonl');
98
- fd = openSync(path, 'r');
99
- const size = fstatSync(fd).size;
100
- if (size === 0) return undefined;
101
- const start = Math.max(0, size - TAIL_BYTES);
102
- const len = size - start;
103
- const buf = Buffer.allocUnsafe(len);
104
- readSync(fd, buf, 0, len, start);
105
- const lines = buf.toString('utf8').split('\n');
106
- if (start > 0) lines.shift(); // drop the partial first line
96
+ // Live tail, plus sealed segments when the live file is short (P7.3).
97
+ const tail = readLogTailSync(join(cwd, '.arco', 'workflows', wfid), TAIL_BYTES);
98
+ if (!tail.text) return undefined;
99
+ const lines = tail.text.split('\n');
100
+ if (tail.truncated) lines.shift(); // drop the partial first line
107
101
 
108
102
  const chunks: string[] = [];
109
103
  let at = 0;
@@ -140,14 +134,6 @@ function readLastMessage(
140
134
  };
141
135
  } catch {
142
136
  return undefined;
143
- } finally {
144
- if (fd !== undefined) {
145
- try {
146
- closeSync(fd);
147
- } catch {
148
- /* ignore */
149
- }
150
- }
151
137
  }
152
138
  }
153
139
 
@@ -549,18 +535,11 @@ function readFullTranscript(wfid: string): { title?: string; turns: TranscriptTu
549
535
  const title = wf?.config.name;
550
536
  const cwd = workflowCwds.get(wfid) ?? wf?.config.workingDirectory;
551
537
  if (!cwd) return { ...(title ? { title } : {}), turns: [] };
552
- let fd: number | undefined;
553
538
  try {
554
- const path = join(cwd, '.arco', 'workflows', wfid, 'events.jsonl');
555
- fd = openSync(path, 'r');
556
- const size = fstatSync(fd).size;
557
- if (size === 0) return { ...(title ? { title } : {}), turns: [] };
558
- const start = Math.max(0, size - MAX_TRANSCRIPT_BYTES);
559
- const len = size - start;
560
- const buf = Buffer.allocUnsafe(len);
561
- readSync(fd, buf, 0, len, start);
562
- const lines = buf.toString('utf8').split('\n');
563
- if (start > 0) lines.shift();
539
+ const tail = readLogTailSync(join(cwd, '.arco', 'workflows', wfid), MAX_TRANSCRIPT_BYTES);
540
+ if (!tail.text) return { ...(title ? { title } : {}), turns: [] };
541
+ const lines = tail.text.split('\n');
542
+ if (tail.truncated) lines.shift();
564
543
 
565
544
  const turns: TranscriptTurn[] = [];
566
545
  let asst: string[] = [];
@@ -594,14 +573,6 @@ function readFullTranscript(wfid: string): { title?: string; turns: TranscriptTu
594
573
  return { ...(title ? { title } : {}), turns: turns.length > MAX_TURNS ? turns.slice(-MAX_TURNS) : turns };
595
574
  } catch {
596
575
  return { ...(title ? { title } : {}), turns: [] };
597
- } finally {
598
- if (fd !== undefined) {
599
- try {
600
- closeSync(fd);
601
- } catch {
602
- /* ignore */
603
- }
604
- }
605
576
  }
606
577
  }
607
578
 
@@ -161,6 +161,7 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
161
161
  reviewRequired?: boolean;
162
162
  goalMode?: boolean;
163
163
  goalMaxTurns?: number;
164
+ release?: string;
164
165
  }): Promise<{ ok: true; body: unknown } | { ok: false; err: TaskUpstreamError }> {
165
166
  const payload: Record<string, unknown> = { workflowId, title: args.title };
166
167
  if (typeof args.body === 'string') payload.body = args.body;
@@ -172,6 +173,7 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
172
173
  if (typeof args.reviewRequired === 'boolean') payload.reviewRequired = args.reviewRequired;
173
174
  if (typeof args.goalMode === 'boolean') payload.goalMode = args.goalMode;
174
175
  if (typeof args.goalMaxTurns === 'number') payload.goalMaxTurns = args.goalMaxTurns;
176
+ if (typeof args.release === 'string') payload.release = args.release;
175
177
  const r = await fetch(`${BASE_URL}/task-create`, {
176
178
  method: 'POST',
177
179
  headers: { 'Content-Type': 'application/json' },
@@ -193,10 +195,11 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
193
195
  return { ok: true, body };
194
196
  }
195
197
 
196
- async function callTaskUpdate(args: { id: string; status?: string; notes?: string; signoff?: { state: string; summary?: string } }): Promise<{ ok: true; body: unknown } | { ok: false; err: TaskUpstreamError }> {
198
+ async function callTaskUpdate(args: { id: string; status?: string; notes?: string; release?: string; signoff?: { state: string; summary?: string } }): Promise<{ ok: true; body: unknown } | { ok: false; err: TaskUpstreamError }> {
197
199
  const payload: Record<string, unknown> = { workflowId, id: args.id };
198
200
  if (typeof args.status === 'string') payload.status = args.status;
199
201
  if (typeof args.notes === 'string') payload.notes = args.notes;
202
+ if (typeof args.release === 'string') payload.release = args.release;
200
203
  if (args.signoff && typeof args.signoff === 'object') payload.signoff = args.signoff;
201
204
  const r = await fetch(`${BASE_URL}/task-update`, {
202
205
  method: 'POST',
@@ -479,6 +482,7 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
479
482
  reviewRequired: z.boolean().optional(),
480
483
  goalMode: z.boolean().optional(),
481
484
  goalMaxTurns: z.number().optional(),
485
+ release: z.string().optional().describe('Optional release label such as 0.1.4.'),
482
486
  },
483
487
  },
484
488
  async (args) => {
@@ -494,6 +498,7 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
494
498
  reviewRequired: args.reviewRequired,
495
499
  goalMode: args.goalMode,
496
500
  goalMaxTurns: args.goalMaxTurns,
501
+ release: args.release,
497
502
  });
498
503
  if (!r.ok) {
499
504
  const detail = r.err.message ?? r.err.error ?? 'unknown_error';
@@ -564,6 +569,7 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
564
569
  id: z.string().min(1).describe('Task id from cluster_task_list.'),
565
570
  status: z.enum(['triage', 'todo', 'ready', 'in_progress', 'blocked', 'review']).optional().describe("New status. 'done' and 'archived' are rejected — operator-only."),
566
571
  notes: z.string().optional().describe('Replacement notes body for the task.'),
572
+ release: z.string().optional().describe('Release label such as 0.1.4; an empty string clears it.'),
567
573
  signoff: z.object({
568
574
  state: z.enum(['met', 'not_met', 'partial']).describe('Your verdict: met / not_met / partial.'),
569
575
  summary: z.string().optional().describe('One-line reason shown on the board card.'),
@@ -572,7 +578,7 @@ export function registerClusterTools(server: McpServer, ctx: ClusterMcpToolCtx):
572
578
  },
573
579
  async (args) => {
574
580
  try {
575
- const r = await callTaskUpdate({ id: args.id, status: args.status, notes: args.notes, signoff: args.signoff });
581
+ const r = await callTaskUpdate({ id: args.id, status: args.status, notes: args.notes, release: args.release, signoff: args.signoff });
576
582
  if (!r.ok) {
577
583
  const detail = r.err.message ?? r.err.error ?? 'unknown_error';
578
584
  return textResult(`[error] ${r.err.error ?? 'task_update_failed'}: ${detail}`, true);