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
@@ -33,6 +33,7 @@ import { ensureProjectStateIgnore } from '../projectStateIgnore.js';
33
33
  import { promises as fs } from 'fs';
34
34
  import path from 'path';
35
35
  import { atomicWriteFile, withFileLock } from '../atomicFile.js';
36
+ import { readLogLines } from '../eventLog.js';
36
37
  const WFID_PATTERN = /^[a-zA-Z0-9-]{1,64}$/;
37
38
  const CURRENT_INDEX_VERSION = 1;
38
39
  const TITLE_MAX = 100;
@@ -123,29 +124,33 @@ function newestCliSession(meta) {
123
124
  export async function scanOperatorMessages(cwd, wfid) {
124
125
  if (!WFID_PATTERN.test(wfid))
125
126
  return [];
126
- const eventsPath = path.join(cwd, '.arco', 'workflows', wfid, 'events.jsonl');
127
- let raw;
127
+ const out = [];
128
+ let lines;
128
129
  try {
129
- raw = await fs.readFile(eventsPath, 'utf8');
130
+ lines = readLogLines(path.join(cwd, '.arco', 'workflows', wfid));
130
131
  }
131
132
  catch {
132
133
  return [];
133
134
  }
134
- const out = [];
135
- for (const line of raw.split('\n')) {
136
- if (!line || !line.includes('"user_message_echo"'))
137
- continue;
138
- let entry;
139
- try {
140
- entry = JSON.parse(line);
141
- }
142
- catch {
143
- continue;
135
+ try {
136
+ for await (const line of lines) {
137
+ if (!line || !line.includes('"user_message_echo"'))
138
+ continue;
139
+ let entry;
140
+ try {
141
+ entry = JSON.parse(line);
142
+ }
143
+ catch {
144
+ continue;
145
+ }
146
+ if (entry.type !== 'user_message_echo')
147
+ continue;
148
+ if (typeof entry.content === 'string' && entry.content.trim())
149
+ out.push(entry.content.trim());
144
150
  }
145
- if (entry.type !== 'user_message_echo')
146
- continue;
147
- if (typeof entry.content === 'string' && entry.content.trim())
148
- out.push(entry.content.trim());
151
+ }
152
+ catch {
153
+ return out;
149
154
  }
150
155
  return out;
151
156
  }
@@ -13,7 +13,7 @@
13
13
  import * as clusterStore from '../clusterStore.js';
14
14
  import * as taskLedger from '../project/taskLedger.js';
15
15
  import { workflows, workflowCwds } from '../server/state.js';
16
- import { broadcastWorkflow, send } from '../server/broadcast.js';
16
+ import { broadcastWorkflow, send, sendWorkflowLive } from '../server/broadcast.js';
17
17
  // Per-cwd mutation serialization. Each cwd gets a tail promise; a new mutation
18
18
  // chains off it so the load-mutate-save sequence never interleaves.
19
19
  const cwdLocks = new Map();
@@ -80,9 +80,12 @@ export async function appendLedgerComment(cwd, comment, boardKey) {
80
80
  }
81
81
  // Re-snapshot the cwd to every observer of the originating workflow. We
82
82
  // broadcast on the originating workflow so the snapshot fans out to the tab(s)
83
- // looking at this cwd; the client keys it by `cwd`.
83
+ // looking at this cwd; the client keys it by `cwd`. Live only (P7.2): a full
84
+ // board copy is not written to events.jsonl. The ledger store holds the board,
85
+ // emitEvent below persists each change, and a reconnecting tab gets a fresh
86
+ // copy from sendTaskLedgerSnapshot.
84
87
  export function broadcastSnapshot(workflowId, cwd, tasks, boardKey) {
85
- broadcastWorkflow(workflowId, {
88
+ sendWorkflowLive(workflowId, {
86
89
  type: 'task_ledger_snapshot',
87
90
  workflowId,
88
91
  cwd,
@@ -129,6 +132,7 @@ export async function handleTaskLedgerCreate(ws, msg) {
129
132
  goalMode: msg.goalMode,
130
133
  goalMaxTurns: msg.goalMaxTurns,
131
134
  worktreeRequired: msg.worktreeRequired,
135
+ release: msg.release,
132
136
  createdBy: msg.workflowId,
133
137
  });
134
138
  const next = [...tasks, task];
@@ -159,6 +163,7 @@ export async function handleTaskLedgerUpdate(ws, msg) {
159
163
  goalMode: msg.goalMode,
160
164
  goalMaxTurns: msg.goalMaxTurns,
161
165
  worktreeRequired: msg.worktreeRequired,
166
+ release: msg.release,
162
167
  assignee: msg.assignee,
163
168
  updatedBy: msg.workflowId,
164
169
  });
@@ -30,7 +30,7 @@ import { buildClusterPlanReviewContent, buildPlanReviewContent, buildPreviewCapt
30
30
  import { runReviewer } from '../primitives/runReviewer.js';
31
31
  import { runResearch } from '../primitives/runResearch.js';
32
32
  import { runDocEdit } from '../primitives/runDocEdit.js';
33
- import { runMdTuneup, backupAndWriteInstructionFile, discoverInstructionFiles } from '../primitives/runMdTuneup.js';
33
+ import { runMdTuneup, backupAndWriteInstructionFile, discoverInstructionFilesWithLinks } from '../primitives/runMdTuneup.js';
34
34
  import { rememberTuneupUndo, undoTuneup } from '../primitives/mdTuneupUndo.js';
35
35
  import { resolveWithinCwd } from '../providers/ollamaTools.js';
36
36
  import { RESEARCH_MAX_ROUNDS_CEILING } from '@arco/shared';
@@ -1317,6 +1317,7 @@ async function restoreAdmittedCheckpoint(ws, msg, cwd, restoreOwner) {
1317
1317
  type: 'checkpoint_reverted',
1318
1318
  workflowId: msg.workflowId,
1319
1319
  seq: msg.seq,
1320
+ restoredSeq: msg.seq,
1320
1321
  fileCount: result.fileCount,
1321
1322
  safetySnapshotRef: safety.ref,
1322
1323
  safetySnapshotSeq: safetyGuardSeq,
@@ -1887,10 +1888,10 @@ export async function handleMdTuneupCandidatesRequest(ws, session, msg) {
1887
1888
  send(ws, { type: 'md_tuneup_candidates', workflowId: msg.workflowId, candidates: [] });
1888
1889
  return;
1889
1890
  }
1890
- const candidates = await discoverInstructionFiles(cwd).catch(() => []);
1891
+ const { candidates, skippedLinks } = await discoverInstructionFilesWithLinks(cwd).catch(() => ({ candidates: [], skippedLinks: [] }));
1891
1892
  const providerDefault = tuneupBaseNameForProvider(wf.primary.provider);
1892
- const defaultPath = candidates.find((c) => c.path === providerDefault)?.path;
1893
- send(ws, { type: 'md_tuneup_candidates', workflowId: msg.workflowId, candidates, defaultPath });
1893
+ const defaultPath = candidates.find((c) => c.path === providerDefault || c.alsoReadAs?.includes(providerDefault))?.path;
1894
+ send(ws, { type: 'md_tuneup_candidates', workflowId: msg.workflowId, candidates, skippedLinks, defaultPath });
1894
1895
  }
1895
1896
  export async function handleMdTuneupRequest(ws, session, msg) {
1896
1897
  void session;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arco/server",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "private": true,
5
5
  "type": "module"
6
6
  }
@@ -0,0 +1,254 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants, createReadStream } from 'node:fs';
3
+ import { promises as fs } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { execFile } from 'node:child_process';
7
+ import { promisify } from 'node:util';
8
+ import { normalizeKeepPath } from './keepStore.js';
9
+ import { outputDirectory } from './outputStore.js';
10
+ import { assertSafePath, confinedPath, isPathWithin, safeDirectory } from './fileAccessPolicy.js';
11
+ import { projectGitEnv, suggestFromRemote } from './publicProject.js';
12
+ import { publicSafetyRules } from '@arco/shared';
13
+
14
+ const git = promisify(execFile);
15
+ async function gitCall(cwd: string, args: string[]): Promise<void> {
16
+ await git('git', args, { cwd, timeout: 10000, env: projectGitEnv() });
17
+ }
18
+ const MiB = 1024 * 1024;
19
+ const MB = 1000 * 1000;
20
+ const TEXT = /\.(?:txt|md|markdown|csv|json|ya?ml|xml|html?|svg|js|mjs|cjs|jsx|ts|tsx|py|rs|go|java|css|sh|sql|diff|patch|log|ini|toml|env)$/i;
21
+ const MEDIA = /\.(?:png|jpe?g|webp|gif|bmp|svg|mp3|wav|ogg|flac|m4a|mp4|webm|mov|mkv|avi)$/i;
22
+ const safeUsers = new Set(['operator', 'example', 'user', 'username', 'u', 'op', 'root', 'nobody', 'glob', 'real', 'test', 'runner', 'node']);
23
+ const patterns: ReadonlyArray<readonly [string, RegExp]> = [
24
+ ...publicSafetyRules,
25
+ ['password-or-secret', /\b(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*["']?[^\s"']{1,}/i],
26
+ ['ip-address', /\b(?:\d{1,3}\.){3}\d{1,3}\b|(?<![A-Za-z0-9])(?:[a-fA-F0-9]{0,4}:){2,}[a-fA-F0-9]{0,4}(?![A-Za-z0-9])/],
27
+ ];
28
+ export function scanCopyLine(line: string): string[] {
29
+ const rules = patterns.filter(([, re]) => re.test(line)).map(([name]) => name);
30
+ if (/[A-Za-z0-9_.+%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/.test(line)) rules.push('email-address');
31
+ const decoded = line.replace(/%([0-9a-f]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
32
+ for (const m of decoded.matchAll(/(?:(?<![A-Za-z0-9_/])\/(?:home|Users)\/|[A-Za-z]:[\\/]Users[\\/])([A-Za-z0-9_.-]+)(?=[\\/])/g)) if (!safeUsers.has(m[1])) rules.push('personal-home-path');
33
+ return [...new Set(rules)];
34
+ }
35
+ interface FileEntry { rel: string; bytes: number; hash: string; media: boolean; unscanned: boolean; findings: Array<{ line: number; rule: string }> }
36
+ interface CopyInspection { source: string; target: string; bytes: number; ignored: boolean; publicRepository: boolean; files: FileEntry[]; directories: string[]; token: string }
37
+ async function scanFile(file: string, rel: string, maxFindings = 1000): Promise<FileEntry> {
38
+ const fh = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
39
+ try {
40
+ const info = await fh.stat(); if (!info.isFile()) throw new Error('Only regular files can be copied.');
41
+ const hash = createHash('sha256'); const findings: FileEntry['findings'] = [];
42
+ const media = MEDIA.test(rel); const scanText = !media || TEXT.test(rel); let line = 1; let pending = ''; let unscanned = !scanText;
43
+ const decoder = new TextDecoder('utf-8');
44
+ for await (const chunk of createReadStream('', { fd: fh.fd, autoClose: false, emitClose: false })) {
45
+ const buffer = chunk as Buffer; hash.update(buffer);
46
+ if (!scanText) continue;
47
+ const textBuffer = buffer.includes(0) ? Buffer.from(buffer.filter(byte => byte !== 0)) : buffer;
48
+ const text = decoder.decode(textBuffer, { stream: true });
49
+ if (text.includes('\ufffd')) unscanned = true;
50
+ pending += text;
51
+ for (;;) {
52
+ const i = pending.indexOf('\n'); if (i < 0) break;
53
+ for (const rule of scanCopyLine(pending.slice(0, i))) { if (findings.length >= maxFindings) throw new Error('Too many findings to show; split the artifact.'); findings.push({ line, rule }); }
54
+ pending = pending.slice(i + 1); line++;
55
+ }
56
+ if (pending.length > MiB) throw new Error('A text line is too long to scan; split the artifact.');
57
+ }
58
+ if (scanText) {
59
+ const remainder = decoder.decode();
60
+ if (remainder.includes('\ufffd')) unscanned = true;
61
+ pending += remainder;
62
+ for (const rule of scanCopyLine(pending)) { if (findings.length >= maxFindings) throw new Error('Too many findings to show; split the artifact.'); findings.push({ line, rule }); }
63
+ }
64
+ return { rel, bytes: info.size, hash: hash.digest('hex'), media, unscanned, findings };
65
+ } finally { await fh.close(); }
66
+ }
67
+ async function gitIgnored(cwd: string, target: string): Promise<boolean> {
68
+ try {
69
+ await gitCall(cwd, ['ls-files', '--error-unmatch', '--', target]);
70
+ return false;
71
+ } catch (e) {
72
+ const code = (e as { code?: unknown }).code;
73
+ if (code !== 1 && code !== 128) throw new Error('Git tracking status is unavailable.');
74
+ if (code === 128) return false;
75
+ }
76
+ try { await gitCall(cwd, ['check-ignore', '-q', '--no-index', '--', target]); return true; }
77
+ catch (e) {
78
+ const code = (e as { code?: unknown }).code;
79
+ if (code === 1) return false;
80
+ if (code === 128) { try { await gitCall(cwd, ['rev-parse', '--is-inside-work-tree']); } catch (err) { if ((err as { code?: unknown }).code === 128) return false; } }
81
+ throw new Error('Git ignore status is unavailable.');
82
+ }
83
+ }
84
+ async function ensureNoLinks(root: string, rel: string): Promise<void> {
85
+ let current = root;
86
+ const base = await fs.lstat(root);
87
+ if (base.isSymbolicLink()) throw new Error('Artifact links cannot be copied.');
88
+ for (const part of rel ? rel.split('/') : []) {
89
+ current = path.join(current, part);
90
+ if ((await fs.lstat(current)).isSymbolicLink()) throw new Error('Artifact links cannot be copied.');
91
+ }
92
+ if (await fs.realpath(current) !== current) throw new Error('Artifact path changed; review it again.');
93
+ }
94
+ async function listSource(root: string): Promise<{ files: Array<{ path: string; rel: string }>; directories: string[] }> {
95
+ const out: Array<{ path: string; rel: string }> = []; const directories: string[] = [];
96
+ async function walk(file: string, rel: string) {
97
+ const st = await fs.lstat(file);
98
+ if (st.isSymbolicLink()) throw new Error('Artifact links cannot be copied.');
99
+ if (st.isDirectory()) {
100
+ if (rel) directories.push(rel);
101
+ if (directories.length > 10000) throw new Error('Too many folders; copy a smaller folder.');
102
+ const names: string[] = [];
103
+ for await (const entry of await fs.opendir(file)) {
104
+ if (names.length >= 10000) throw new Error('Too many entries; copy a smaller folder.');
105
+ names.push(entry.name);
106
+ }
107
+ for (const name of names.sort()) await walk(path.join(file, name), rel ? `${rel}/${name}` : name);
108
+ return;
109
+ }
110
+ if (!st.isFile()) throw new Error('Only regular files and folders can be copied.');
111
+ if (out.length >= 10000) throw new Error('Too many files; copy a smaller folder.');
112
+ out.push({ path: file, rel });
113
+ }
114
+ await walk(root, ''); return { files: out, directories };
115
+ }
116
+ export async function inspectArtifactCopy(cwd: string, workflowId: string, itemPath: string, destinationFolder: string, declaredPublic: boolean): Promise<CopyInspection> {
117
+ const rel = normalizeKeepPath(itemPath);
118
+ if (!rel || (rel !== 'artifacts' && !rel.startsWith('artifacts/'))) throw new Error('Choose an artifact file or folder.');
119
+ const dir = await fs.realpath(await outputDirectory(cwd, workflowId)); let source = dir;
120
+ for (const part of rel.split('/')) { source = path.join(source, part); const st = await fs.lstat(source); if (st.isSymbolicLink()) throw new Error('Artifact links cannot be copied.'); }
121
+ source = await fs.realpath(source);
122
+ if (!isPathWithin(path.join(dir, 'artifacts'), source)) throw new Error('Artifact path changed; review it again.');
123
+ const project = await fs.realpath(safeDirectory(cwd));
124
+ const folder = await fs.realpath(confinedPath(destinationFolder, [cwd], 'directory'));
125
+ const target = path.join(folder, path.basename(source));
126
+ assertSafePath(target);
127
+ if (!isPathWithin(project, target) || target.split(path.sep).includes('.arco')) throw new Error('Choose a project folder outside Arco state.');
128
+ try { await fs.lstat(target); throw new Error('The destination already exists.'); } catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; }
129
+ const listed = await listSource(source); const files: FileEntry[] = []; let findingCount = 0; let ignored = listed.files.length ? true : await gitIgnored(project, target);
130
+ for (const f of listed.files) {
131
+ const dest = f.rel ? path.join(target, ...f.rel.split('/')) : target;
132
+ assertSafePath(dest);
133
+ ignored = await gitIgnored(project, dest) && ignored;
134
+ await ensureNoLinks(source, f.rel);
135
+ const scanned = await scanFile(f.path, f.rel || path.basename(source));
136
+ findingCount += scanned.findings.length;
137
+ if (findingCount > 2000) throw new Error('Too many findings to show; copy a smaller artifact.');
138
+ files.push(scanned);
139
+ await ensureNoLinks(source, f.rel);
140
+ }
141
+ const bytes = files.reduce((n, f) => n + f.bytes, 0);
142
+ const publicRepository = declaredPublic || (await suggestFromRemote(project)).state === 'public';
143
+ const directories = listed.directories;
144
+ for (const rel of directories) assertSafePath(path.join(target, ...rel.split('/')));
145
+ const token = createHash('sha256').update(JSON.stringify({ source, target, ignored, publicRepository, files, directories })).digest('hex');
146
+ return { source, target, bytes, ignored, publicRepository, files, directories, token };
147
+ }
148
+
149
+ // Re-scan immediately before copying and require an unchanged review token.
150
+ // Each destination is exclusively created; source bytes are checked against
151
+ // the preflight hash before success is reported. Originals are never removed.
152
+ export async function copyReviewedArtifact(cwd: string, workflowId: string, itemPath: string, destinationFolder: string, declaredPublic: boolean, token: string, beforePublish?: (index: number) => Promise<void>, confirmUnscanned = false): Promise<CopyInspection> {
153
+ const check = await inspectArtifactCopy(cwd, workflowId, itemPath, destinationFolder, declaredPublic);
154
+ if (!token || token !== check.token) throw new Error('The artifact or destination changed. Review it again.');
155
+ if (!check.ignored && check.publicRepository && check.files.some((file) => file.unscanned) && !confirmUnscanned) throw new Error('Confirm the files that were not scanned before copying into a public repository.');
156
+ if (!check.ignored && check.bytes > 100 * MB) throw new Error('Over 100 MB cannot be copied into a folder included in Git. Choose an ignored folder.');
157
+ const sourceInfo = await fs.lstat(check.source);
158
+ const tempRoot = await fs.realpath(tmpdir());
159
+ if (isPathWithin(await fs.realpath(safeDirectory(cwd)), tempRoot)) throw new Error('The temporary folder must be outside the project.');
160
+ for (let ancestor = tempRoot; ;) {
161
+ try { await fs.lstat(path.join(ancestor, '.git')); throw new Error('The temporary folder must be outside Git repositories.'); }
162
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
163
+ const parent = path.dirname(ancestor); if (parent === ancestor) break; ancestor = parent;
164
+ }
165
+ const temp = await fs.mkdtemp(path.join(tempRoot, 'arco-reviewed-copy-'));
166
+ let published = false;
167
+ try {
168
+ // Stage outside the project in a private temporary directory. Only the
169
+ // exact bytes reviewed above can be published, even if a worker edits the
170
+ // artifact while it is being read.
171
+ for (let i = 0; i < check.files.length; i++) {
172
+ const entry = check.files[i];
173
+ const rel = sourceInfo.isDirectory() ? entry.rel : '';
174
+ const inputPath = rel ? path.join(check.source, ...rel.split('/')) : check.source;
175
+ await ensureNoLinks(check.source, rel);
176
+ const input = await fs.open(inputPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
177
+ try {
178
+ const st = await input.stat();
179
+ if (!st.isFile() || st.size !== entry.bytes) throw new Error('The artifact changed. Review it again.');
180
+ const output = await fs.open(path.join(temp, String(i)), constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
181
+ try {
182
+ const hash = createHash('sha256');
183
+ for await (const chunk of createReadStream('', { fd: input.fd, autoClose: false, emitClose: false })) { hash.update(chunk as Buffer); await output.writeFile(chunk as Buffer); }
184
+ if (hash.digest('hex') !== entry.hash) throw new Error('The artifact changed. Review it again.');
185
+ await ensureNoLinks(check.source, rel);
186
+ await output.sync();
187
+ } finally { await output.close(); }
188
+ } finally { await input.close(); }
189
+ }
190
+ let ignored = check.files.length ? true : await gitIgnored(cwd, check.target);
191
+ for (const entry of check.files) {
192
+ const dest = sourceInfo.isDirectory() ? path.join(check.target, ...entry.rel.split('/')) : check.target;
193
+ ignored = await gitIgnored(cwd, dest) && ignored;
194
+ }
195
+ if (ignored !== check.ignored) throw new Error('Git ignore status changed. Review again.');
196
+ if (!ignored && check.bytes > 100 * MB) throw new Error('Over 100 MB cannot be copied into a folder included in Git. Choose an ignored folder.');
197
+ const isPublic = declaredPublic || (await suggestFromRemote(cwd)).state === 'public';
198
+ if (isPublic !== check.publicRepository) throw new Error('Repository visibility changed. Review again.');
199
+ if (await fs.realpath(path.dirname(check.target)) !== path.dirname(check.target)) throw new Error('Destination folder changed.');
200
+ if (sourceInfo.isDirectory()) { await fs.mkdir(check.target); published = true; }
201
+ for (const rel of check.directories) await fs.mkdir(path.join(check.target, ...rel.split('/')));
202
+ for (let i = 0; i < check.files.length; i++) {
203
+ const entry = check.files[i];
204
+ const outputPath = sourceInfo.isDirectory() ? path.join(check.target, ...entry.rel.split('/')) : check.target;
205
+ await beforePublish?.(i);
206
+ if (await fs.realpath(path.dirname(outputPath)) !== path.dirname(outputPath)) throw new Error('Destination folder changed.');
207
+ const output = await fs.open(outputPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
208
+ published = true;
209
+ try {
210
+ const opened = await output.stat(); const target = await fs.lstat(outputPath);
211
+ if (!opened.isFile() || target.isSymbolicLink() || opened.dev !== target.dev || opened.ino !== target.ino || await fs.realpath(outputPath) !== outputPath) throw new Error('Destination folder changed.');
212
+ const input = await fs.open(path.join(temp, String(i)), constants.O_RDONLY | constants.O_NOFOLLOW);
213
+ try { for await (const chunk of createReadStream('', { fd: input.fd, autoClose: false, emitClose: false })) await output.writeFile(chunk as Buffer); }
214
+ finally { await input.close(); }
215
+ await output.sync();
216
+ } finally { await output.close(); }
217
+ }
218
+ return check;
219
+ } catch (err) {
220
+ const detail = err instanceof Error ? err.message : 'Copy failed.';
221
+ throw new Error(published ? `${detail} Some copied files may remain; the original stays in Arco.` : detail);
222
+ } finally { await fs.rm(temp, { recursive: true, force: true }); }
223
+ }
224
+
225
+ // Append one literal root-relative rule. Never replace an edited ignore file.
226
+ export async function ignoreCopyDestination(cwd: string, target: string): Promise<void> {
227
+ const project = await fs.realpath(safeDirectory(cwd));
228
+ if (!isPathWithin(project, target) || target === project) throw new Error('Choose a destination inside this project.');
229
+ try { await gitCall(project, ['rev-parse', '--is-inside-work-tree']); }
230
+ catch { throw new Error('This project is not a Git repository.'); }
231
+ const rel = path.relative(project, target).split(path.sep).join('/');
232
+ if (/[\r\n\0]/.test(rel)) throw new Error('This filename cannot be written to .gitignore.');
233
+ const rule = '/' + rel.replace(/([\\*?\[\] ])/g, '\\$1');
234
+ const ignore = path.join(project, '.gitignore');
235
+ const flags = constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW;
236
+ let handle: Awaited<ReturnType<typeof fs.open>>;
237
+ try { handle = await fs.open(ignore, flags); }
238
+ catch (e) { if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e; handle = await fs.open(ignore, flags | constants.O_CREAT | constants.O_EXCL, 0o600); }
239
+ try {
240
+ const opened = await handle.stat();
241
+ const current = await fs.lstat(ignore);
242
+ if (!opened.isFile() || current.isSymbolicLink() || opened.dev !== current.dev || opened.ino !== current.ino || opened.size > MiB) throw new Error('The project ignore file cannot be edited.');
243
+ let prefix = '';
244
+ if (opened.size) {
245
+ const reader = await fs.open(ignore, constants.O_RDONLY | constants.O_NOFOLLOW);
246
+ try { const last = Buffer.alloc(1); await reader.read(last, 0, 1, opened.size - 1); if (last[0] !== 10) prefix = '\n'; }
247
+ finally { await reader.close(); }
248
+ }
249
+ const content = Buffer.from(`${prefix}${rule}\n`);
250
+ const result = await handle.write(content);
251
+ if (result.bytesWritten !== content.length) throw new Error('The ignore rule was only partially written. Review .gitignore.');
252
+ await handle.sync();
253
+ } finally { await handle.close(); }
254
+ }
@@ -41,7 +41,7 @@ const RENAME_RETRY_LIMIT_MS = 5_000;
41
41
  const isWindows = process.platform === 'win32';
42
42
  const retryable = (e: unknown): boolean => isWindows && RENAME_RETRY_CODES.has((e as NodeJS.ErrnoException)?.code ?? '');
43
43
 
44
- async function renameWithRetry(from: string, to: string): Promise<void> {
44
+ export async function renameWithRetry(from: string, to: string): Promise<void> {
45
45
  const started = Date.now();
46
46
  for (let delay = 5; ; delay = Math.min(delay * 2, 100)) {
47
47
  try { await fs.rename(from, to); return; } catch (e) {
@@ -1,6 +1,6 @@
1
1
  // Attention alerts: a turn finished, failed, or is waiting on the operator.
2
2
  //
3
- // Opt-in per event and per channel (this computer, phone), off by default.
3
+ // Desktop and phone alerts are opt-in; quiet in-app notices are on by default.
4
4
  // The server watches workflow messages, applies the preferences, sends the
5
5
  // phone message through ntfy itself (no hub and no client needed) and tells
6
6
  // connected browsers with an `attention_event` so each can decide whether to
@@ -16,7 +16,7 @@ import { broadcastToClients } from './notifications.js';
16
16
  import * as clusterStore from './clusterStore.js';
17
17
  import { isClusterDirector } from '@arco/shared';
18
18
 
19
- // A turn shorter than this is not worth an alert: the operator was watching.
19
+ // Desktop and phone finished alerts require a longer turn.
20
20
  export const MIN_FINISHED_TURN_MS = 15_000;
21
21
  const TEXT_MAX = 200;
22
22
 
@@ -119,20 +119,19 @@ function shouldRaise(kind: AttentionKind, workflowId: string): boolean {
119
119
  return isClusterDirector(clusterStore.getMemberRole(clusterId, workflowId));
120
120
  }
121
121
 
122
- export function raise(kind: AttentionKind, workflowId: string, info: WorkflowInfo, text?: string): void {
122
+ export function raise(kind: AttentionKind, workflowId: string, info: WorkflowInfo, text?: string, longEnough = true): void {
123
123
  if (info.incognito) return;
124
- const wantDesktop = channels.desktop[kind];
125
- const target = channels.phone[kind] ? resolvePhoneTarget() : null;
126
- if (!wantDesktop && !target) return;
127
- if (!shouldRaise(kind, workflowId)) return;
124
+ const externalEligible = longEnough && shouldRaise(kind, workflowId);
125
+ const wantDesktop = channels.desktop[kind] && externalEligible;
126
+ const target = channels.phone[kind] && externalEligible ? resolvePhoneTarget() : null;
128
127
  // One alert per workflow and kind per few seconds, whatever produced it.
129
128
  const key = `${workflowId}:${kind}`;
130
129
  const now = Date.now();
131
130
  if (now - (lastAlertAt.get(key) ?? 0) < 3000) return;
132
131
  lastAlertAt.set(key, now);
133
132
  const name = ascii(info.name || workflowId.slice(0, 8), 60);
134
- if (wantDesktop) {
135
- broadcastToClients({ type: 'attention_event', id: `at_${now.toString(36)}_${(idCounter++).toString(36)}`, kind, workflowId, workflowName: name });
133
+ {
134
+ broadcastToClients({ type: 'attention_event', id: `at_${now.toString(36)}_${(idCounter++).toString(36)}`, kind, workflowId, workflowName: name, desktopEligible: wantDesktop });
136
135
  }
137
136
  if (target) {
138
137
  const body = channels.phoneText && text ? ascii(text, TEXT_MAX) : `Open Arco to see it.`;
@@ -157,7 +156,7 @@ export function observeAttention(workflowId: string, message: ServerMessage, inf
157
156
  turnStarts.delete(workflowId);
158
157
  const text = lastText.get(workflowId);
159
158
  lastText.delete(workflowId);
160
- if (start !== undefined && Date.now() - start >= MIN_FINISHED_TURN_MS) raise('finished', workflowId, info, text ? text.slice(0, TEXT_MAX) : undefined);
159
+ if (start !== undefined) raise('finished', workflowId, info, text ? text.slice(0, TEXT_MAX) : undefined, Date.now() - start >= MIN_FINISHED_TURN_MS);
161
160
  break;
162
161
  }
163
162
  case 'operator_question':
@@ -1,13 +1,14 @@
1
- import { lstat, open, realpath } from 'node:fs/promises';
2
- import { join, relative, isAbsolute, sep } from 'node:path';
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import { dirname, join, relative, isAbsolute, sep } from 'node:path';
3
3
  import type { UtilityJobFact } from '@arco/shared';
4
4
  import { flushWorkflowBuffer } from './workflowStore.js';
5
+ import { readLogTail } from './eventLog.js';
5
6
 
6
7
  const MAX_TAIL_BYTES = 1024 * 1024;
7
8
  const MAX_FACTS = 32;
8
9
  const TEXT_LIMIT = 350;
9
10
  const DAY_MS = 24 * 60 * 60 * 1000;
10
- export interface CatchUpEvent { ts?: number; type?: string; text?: unknown; content?: unknown; contentPreview?: unknown; op?: unknown; task?: { title?: unknown; status?: unknown }; }
11
+ export interface CatchUpEvent { ts?: number; type?: string; text?: unknown; content?: unknown; contentPreview?: unknown; op?: unknown; task?: { title?: unknown; status?: unknown; release?: unknown }; }
11
12
  export interface CatchUpSource { id: string; label: string; events: CatchUpEvent[]; truncated?: boolean; unavailable?: boolean; }
12
13
 
13
14
  function catchUpValue(e: CatchUpEvent): { kind: string; value: string } | null {
@@ -18,12 +19,33 @@ function catchUpValue(e: CatchUpEvent): { kind: string; value: string } | null {
18
19
  if (e.type === 'task_ledger_event') {
19
20
  return {
20
21
  kind: 'Board',
21
- value: `${String(e.op ?? 'changed')}: ${typeof e.task?.title === 'string' ? e.task.title : 'task'}${typeof e.task?.status === 'string' ? ` (${e.task.status})` : ''}`,
22
+ value: `${String(e.op ?? 'changed')}: ${typeof e.task?.title === 'string' ? e.task.title : 'task'}${typeof e.task?.status === 'string' ? ` (${e.task.status})` : ''}${typeof e.task?.release === 'string' && e.task.release ? ` [release ${e.task.release.slice(0, 24)}]` : ''}`,
22
23
  };
23
24
  }
24
25
  return null;
25
26
  }
26
27
 
28
+ // Counts the board changes inside (from, to] by the status they left a task in
29
+ // and, if labeled, by release. Deterministic; null when the board did not move.
30
+ export function boardMovement(sources: CatchUpSource[], from: number, to: number): string | null {
31
+ const byStatus = new Map<string, number>();
32
+ const byRelease = new Map<string, number>();
33
+ let changes = 0;
34
+ for (const source of sources) {
35
+ for (const e of source.events) {
36
+ if (e.type !== 'task_ledger_event' || typeof e.ts !== 'number' || e.ts <= from || e.ts > to) continue;
37
+ changes++;
38
+ const status = typeof e.task?.status === 'string' ? e.task.status : 'changed';
39
+ byStatus.set(status, (byStatus.get(status) ?? 0) + 1);
40
+ if (typeof e.task?.release === 'string' && e.task.release) byRelease.set(e.task.release.slice(0, 24), (byRelease.get(e.task.release.slice(0, 24)) ?? 0) + 1);
41
+ }
42
+ }
43
+ if (changes === 0) return null;
44
+ const parts = [`${changes} board change${changes === 1 ? '' : 's'}`, [...byStatus].map(([s, n]) => `${n} ${s}`).join(', ')];
45
+ if (byRelease.size) parts.push(`by release: ${[...byRelease].map(([r, n]) => `${r} ${n}`).join(', ')}`);
46
+ return parts.join('; ');
47
+ }
48
+
27
49
  /** When no visit marker exists: empty tab, or from = tab start / last 24 hours. */
28
50
  export function resolveCatchUpWindow(sources: CatchUpSource[], end: number): { empty: true } | { from: number } {
29
51
  let earliest: number | null = null;
@@ -65,6 +87,10 @@ export function collectCatchUpFacts(sources: CatchUpSource[], from: number, to:
65
87
  if (row.value.length > TEXT_LIMIT) truncated = true;
66
88
  return { label: `${new Date(row.ts).toISOString()} ${row.label} ${row.kind}`, value: row.value.slice(0, TEXT_LIMIT) };
67
89
  });
90
+ // One line on how the board moved in the range: changes by resulting status,
91
+ // and by release label when any task carries one.
92
+ const movement = boardMovement(sources, from, to);
93
+ if (movement) facts.push({ label: 'Board movement in this range', value: movement });
68
94
  // A member that is not loaded or is incognito is skipped, and said so.
69
95
  for (const source of sources) if (source.unavailable) facts.push({ label: source.label.slice(0, 64), value: 'activity not available' });
70
96
  return { facts, truncated };
@@ -73,7 +99,6 @@ export function collectCatchUpFacts(sources: CatchUpSource[], from: number, to:
73
99
  export async function readCatchUpEvents(cwd: string, id: string): Promise<{ events: CatchUpEvent[]; truncated: boolean }> {
74
100
  if (!/^[a-zA-Z0-9-]{1,64}$/.test(id)) throw new Error('Invalid workflow.');
75
101
  await flushWorkflowBuffer(cwd, id);
76
- let file;
77
102
  const eventPath = join(cwd, '.arco', 'workflows', id, 'events.jsonl');
78
103
  try {
79
104
  const stat = await lstat(eventPath);
@@ -81,16 +106,13 @@ export async function readCatchUpEvents(cwd: string, id: string): Promise<{ even
81
106
  const root = await realpath(cwd), resolved = await realpath(eventPath);
82
107
  const rel = relative(root, resolved);
83
108
  if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) throw new Error('Workflow activity escapes the project.');
84
- file = await open(eventPath, 'r');
85
109
  }
86
110
  catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { events: [], truncated: false }; throw error; }
87
- try {
88
- const size = (await file.stat()).size, length = Math.min(size, MAX_TAIL_BYTES), data = Buffer.alloc(length);
89
- const { bytesRead } = await file.read(data, 0, length, size - length);
90
- const lines = data.subarray(0, bytesRead).toString('utf8').split('\n');
91
- if (size > length) lines.shift();
92
- const events: CatchUpEvent[] = [];
93
- for (const line of lines) { try { const value = JSON.parse(line); if (value && typeof value === 'object') events.push(value as CatchUpEvent); } catch { /* partial or invalid record */ } }
94
- return { events, truncated: size > length };
95
- } finally { await file.close(); }
111
+ // The live tail, plus the newest sealed segments when it is short (P7.3).
112
+ const tail = await readLogTail(dirname(eventPath), MAX_TAIL_BYTES);
113
+ const lines = tail.text.split('\n');
114
+ if (tail.truncated) lines.shift();
115
+ const events: CatchUpEvent[] = [];
116
+ for (const line of lines) { try { const value = JSON.parse(line); if (value && typeof value === 'object') events.push(value as CatchUpEvent); } catch { /* partial or invalid record */ } }
117
+ return { events, truncated: tail.truncated };
96
118
  }
@@ -834,6 +834,7 @@ export async function peerTaskCreate(
834
834
  reviewRequired?: boolean;
835
835
  goalMode?: boolean;
836
836
  goalMaxTurns?: number;
837
+ release?: string;
837
838
  status?: LedgerTaskStatus;
838
839
  },
839
840
  broadcastCluster: (msg: ServerMessage) => void,
@@ -888,6 +889,7 @@ export async function peerTaskCreate(
888
889
  reviewRequired: args.reviewRequired,
889
890
  goalMode: args.goalMode,
890
891
  goalMaxTurns: args.goalMaxTurns,
892
+ release: args.release,
891
893
  createdBy: ctx.workflowId,
892
894
  });
893
895
  if (assignee) {
@@ -992,6 +994,8 @@ export async function peerTaskUpdate(
992
994
  id: string;
993
995
  status?: LedgerTaskStatus;
994
996
  notes?: string;
997
+ // Release label such as "0.1.4"; an empty string clears it.
998
+ release?: string;
995
999
  // §D3 — the director's advisory verdict. The model passes `{ state, summary }`;
996
1000
  // the server stamps `byWorkflowId`/`at` so it's attributable and unspoofable.
997
1001
  // `null` explicitly clears a prior sign-off (back to PENDING).
@@ -1045,6 +1049,7 @@ export async function peerTaskUpdate(
1045
1049
  const applied = taskLedger.applyUpdate(tasks, args.id, {
1046
1050
  ...(args.status ? { status: args.status } : {}),
1047
1051
  ...(typeof args.notes === 'string' ? { notes: args.notes } : {}),
1052
+ ...(typeof args.release === 'string' ? { release: args.release } : {}),
1048
1053
  ...(signoffPatch !== undefined ? { signoff: signoffPatch } : {}),
1049
1054
  });
1050
1055
  if (!applied) {
@@ -44,6 +44,7 @@ import { readClusterPlan } from './clusterPlanBridge.js';
44
44
  import { rememberCwd } from './crashRecovery.js';
45
45
  import { atomicWriteFile } from './atomicFile.js';
46
46
  import { arcoHome } from './arcoHome.js';
47
+ import { listSegments, readLogText } from './eventLog.js';
47
48
 
48
49
  const NAME_MAX = 64;
49
50
  const MAX_SNAPSHOTS = 100;
@@ -332,6 +333,13 @@ function portableWorkflowMeta(input: WorkflowMeta): WorkflowMeta {
332
333
  // Snapshot the live cluster. Reads the in-memory/on-disk ClusterState, flushes
333
334
  // each member's event buffer (so the copy captures the latest events), then
334
335
  // copies each member's meta.json + events.jsonl into the snapshot dir.
336
+ function memberLogTooLarge(wfid: string, bytes: number): SnapshotValidationError {
337
+ return new SnapshotValidationError(
338
+ 'member_log_too_large',
339
+ `member ${wfid.slice(0, 8)} events.jsonl is ${Math.round(bytes / (1024 * 1024))}MB, over the ${MAX_MEMBER_EVENTS_BYTES / (1024 * 1024)}MB snapshot cap`,
340
+ );
341
+ }
342
+
335
343
  export async function saveSnapshot(input: SaveSnapshotInput): Promise<ClusterSnapshotSummary> {
336
344
  const name = validateName(input.name);
337
345
 
@@ -389,21 +397,20 @@ export async function saveSnapshot(input: SaveSnapshotInput): Promise<ClusterSna
389
397
  JSON.stringify(portableWorkflowMeta(meta), null, 2) + '\n',
390
398
  'utf8',
391
399
  );
392
- const srcEvents = path.join(cwd, '.arco', 'workflows', oldWfid, 'events.jsonl');
400
+ // The whole history, sealed segments included (P7.3); the snapshot
401
+ // keeps one plain log per member, so the cap applies to the plain text.
402
+ const srcDir = path.join(cwd, '.arco', 'workflows', oldWfid);
393
403
  let eventsText = '';
394
- try {
395
- const st = await fs.stat(srcEvents);
396
- if (st.size > MAX_MEMBER_EVENTS_BYTES) {
397
- throw new SnapshotValidationError(
398
- 'member_log_too_large',
399
- `member ${oldWfid.slice(0, 8)} events.jsonl is ${Math.round(st.size / (1024 * 1024))}MB, over the ${MAX_MEMBER_EVENTS_BYTES / (1024 * 1024)}MB snapshot cap`,
400
- );
401
- }
402
- eventsText = await fs.readFile(srcEvents, 'utf8');
403
- } catch (err) {
404
- if (err instanceof SnapshotValidationError) throw err;
405
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
404
+ let eventsBytes = 0;
405
+ const sealed = await listSegments(srcDir);
406
+ if (!sealed.length) {
407
+ try { eventsBytes = (await fs.stat(path.join(srcDir, 'events.jsonl'))).size; }
408
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
406
409
  }
410
+ if (eventsBytes > MAX_MEMBER_EVENTS_BYTES) throw memberLogTooLarge(oldWfid, eventsBytes);
411
+ eventsText = await readLogText(srcDir);
412
+ eventsBytes = Buffer.byteLength(eventsText);
413
+ if (eventsBytes > MAX_MEMBER_EVENTS_BYTES) throw memberLogTooLarge(oldWfid, eventsBytes);
407
414
  await fs.writeFile(path.join(destDir, 'events.jsonl'), eventsText, 'utf8');
408
415
 
409
416
  members.push({