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
@@ -99,6 +99,7 @@ export function setMutes(muted: WorkbenchNoticeCategory[]): void {
99
99
  */
100
100
  export function emit(
101
101
  n: Omit<WorkbenchNotice, 'id' | 'ts'> & { ts?: number },
102
+ options: { transportOnly?: boolean } = {},
102
103
  ): WorkbenchNotice | null {
103
104
  if (mutedCategories.has(n.category)) return null;
104
105
  const notice: WorkbenchNotice = {
@@ -106,7 +107,7 @@ export function emit(
106
107
  id: `wn_${Date.now().toString(36)}_${(idCounter++).toString(36)}`,
107
108
  ts: n.ts ?? Date.now(),
108
109
  };
109
- broadcast?.({ type: 'workbench_notice', notice });
110
+ if (!options.transportOnly) broadcast?.({ type: 'workbench_notice', notice });
110
111
  // Fan out to external transports AFTER the in-app broadcast and only for
111
112
  // non-muted notices (muted ones returned above). Fire-and-forget: a slow or
112
113
  // failing transport must never delay or break the in-app surface.
@@ -123,7 +124,7 @@ export function emit(
123
124
  // Thin wrappers so callsites stay a one-liner and the category/severity/copy
124
125
  // conventions live in one place.
125
126
 
126
- /** Long-turn detection. Pair onTurnStarted / onTurnEnded around a primary turn. */
127
+ /** Keep long-turn events for legacy external transports, without a second BELL entry. */
127
128
  export function onTurnStarted(workflowId: string): void {
128
129
  turnStarts.set(workflowId, Date.now());
129
130
  }
@@ -144,7 +145,7 @@ export function onTurnEnded(workflowId: string, opts?: { provider?: ProviderName
144
145
  body: `Ran ${dur}.`,
145
146
  workflowId,
146
147
  provider: opts?.provider,
147
- });
148
+ }, { transportOnly: true });
148
149
  }
149
150
 
150
151
  /** A throttled provider became available again. */
@@ -9,7 +9,10 @@ import { safeDirectory, isPathWithin } from './fileAccessPolicy.js';
9
9
  import { atomicWriteFile } from './atomicFile.js';
10
10
 
11
11
  export interface StoredOutput extends Omit<WorkflowOutput, 'missing' | 'size'> { aliases?: string[]; actions?: Array<{ action: 'copy' | 'move'; from: string; to: string; at: number }>; }
12
- export interface OutputIndex { version: 1; offset: number; entries: StoredOutput[]; }
12
+ // `offset` is a byte position in the live events.jsonl. `seq` is the newest
13
+ // event sequence number already read (P7.3): sealing replaces the live file,
14
+ // so records sealed since the last read are read from the segments by number.
15
+ export interface OutputIndex { version: 1; offset: number; seq?: number; entries: StoredOutput[]; }
13
16
  export async function outputDirectory(cwd: string, workflowId: string): Promise<string> {
14
17
  if (!/^[a-z0-9_-]{1,64}$/i.test(workflowId)) throw new Error('Invalid output workflow.');
15
18
  const root = safeDirectory(cwd);
@@ -25,7 +28,7 @@ export async function readOutputIndex(cwd: string, workflowId: string): Promise<
25
28
  const st = await lstat(file);
26
29
  if (!st.isFile() || st.isSymbolicLink() || st.size > 8 * 1024 * 1024) throw new Error();
27
30
  const index = JSON.parse(await readFile(file, 'utf8')) as OutputIndex;
28
- if (index.version !== 1 || !Number.isSafeInteger(index.offset) || index.offset < 0 || !Array.isArray(index.entries) || index.entries.length > 2000
31
+ if (index.version !== 1 || !Number.isSafeInteger(index.offset) || index.offset < 0 || (index.seq !== undefined && (!Number.isSafeInteger(index.seq) || index.seq < 0)) || !Array.isArray(index.entries) || index.entries.length > 2000
29
32
  || index.entries.some(e => !e || !/^[a-f0-9]{32}$/.test(e.id) || e.workflowId !== workflowId || typeof e.title !== 'string'
30
33
  || typeof e.name !== 'string' || typeof e.cwd !== 'string' || typeof e.producer !== 'string' || typeof e.source !== 'string'
31
34
  || !['images', 'documents', 'audio', 'video', 'other'].includes(e.category) || !Number.isFinite(e.createdAt) || !Number.isFinite(e.updatedAt)
@@ -11,6 +11,7 @@ import { knownRoots, resolveBoundCwd } from './http/writeConfinement.js';
11
11
  import { workflows } from './server/state.js';
12
12
  import { matchFileEvent } from './recentFilesLedger.js';
13
13
  import { outputDirectory, readOutputIndex, writeOutputIndex, mappedOutputPath, type StoredOutput, type OutputIndex } from './outputStore.js';
14
+ import { readLogLines, sealedThroughSeq } from './eventLog.js';
14
15
 
15
16
  export interface OutputContext { cwd: string; workflowId: string; producer: string; }
16
17
  const LIMIT = 2000;
@@ -154,6 +155,32 @@ async function reconcile(ctx: OutputContext, index: OutputIndex): Promise<void>
154
155
  } catch (err) { if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err; }
155
156
  };
156
157
  await walk(root);
158
+ const handle = async (event: Record<string, unknown>, fallbackTime: number) => {
159
+ const timestamp = typeof event.ts === 'number' ? event.ts : fallbackTime;
160
+ for (const output of outputEventPaths(event, ctx.cwd, root)) {
161
+ if (output.path) await record(output.path, output.title, output.source, timestamp, output.inputPath);
162
+ else if (output.inline && !index.entries.some(e => e.id === idFor(`inline:${output.key}`)) && index.entries.length < LIMIT) index.entries.push({ ...ctx, id: idFor(`inline:${output.key}`), title: output.title || 'Inline artifact', name: output.title || 'Inline artifact', category: 'documents', createdAt: timestamp, updatedAt: timestamp, inline: output.inline, source: output.source });
163
+ }
164
+ };
165
+ const noteSeq = (event: Record<string, unknown>) => { if (typeof event.seq === 'number' && event.seq > (index.seq ?? 0)) index.seq = event.seq; };
166
+ // Records sealed into compressed segments since the last read (P7.3): read
167
+ // them by sequence number, then restart the live file from its beginning.
168
+ const sealedThrough = await sealedThroughSeq(dir);
169
+ if (sealedThrough > (index.seq ?? 0)) {
170
+ const after = index.seq ?? 0;
171
+ for await (const line of readLogLines(dir, { fromSeq: after })) {
172
+ if (Buffer.byteLength(line) > 2 * 1024 * 1024) continue;
173
+ let event: Record<string, unknown> | null = null;
174
+ try { event = JSON.parse(line); } catch { /* malformed event */ }
175
+ if (!event || typeof event.seq !== 'number' || event.seq <= after) continue;
176
+ if (event.seq > sealedThrough) break;
177
+ await handle(event, Date.now());
178
+ noteSeq(event);
179
+ }
180
+ index.seq = Math.max(index.seq ?? 0, sealedThrough);
181
+ index.offset = 0;
182
+ }
183
+ const skipThrough = index.seq ?? 0;
157
184
  const events = path.join(dir, 'events.jsonl');
158
185
  let info;
159
186
  try { info = await lstat(events); } catch { return; }
@@ -179,12 +206,9 @@ async function reconcile(ctx: OutputContext, index: OutputIndex): Promise<void>
179
206
  if (!oversized && lineBytes <= 2 * 1024 * 1024) {
180
207
  let event: Record<string, unknown> | null = null;
181
208
  try { event = JSON.parse(Buffer.concat(pending).toString('utf8')); } catch { /* malformed event */ }
182
- if (event) {
183
- const timestamp = typeof event.ts === 'number' ? event.ts : info.mtimeMs;
184
- for (const output of outputEventPaths(event, ctx.cwd, root)) {
185
- if (output.path) await record(output.path, output.title, output.source, timestamp, output.inputPath);
186
- else if (output.inline && !index.entries.some(e => e.id === idFor(`inline:${output.key}`)) && index.entries.length < LIMIT) index.entries.push({ ...ctx, id: idFor(`inline:${output.key}`), title: output.title || 'Inline artifact', name: output.title || 'Inline artifact', category: 'documents', createdAt: timestamp, updatedAt: timestamp, inline: output.inline, source: output.source });
187
- }
209
+ if (event && !(typeof event.seq === 'number' && event.seq <= skipThrough)) {
210
+ await handle(event, info.mtimeMs);
211
+ noteSeq(event);
188
212
  }
189
213
  }
190
214
  consumed += lineBytes;
@@ -0,0 +1,48 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, renameSync, unlinkSync, writeSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { ensureProjectStateIgnore } from './projectStateIgnore.js';
5
+
6
+ // Content-addressed plan history (P7.2, docs/STORAGE_PLAN.md). Each distinct
7
+ // cluster plan body is written once to <cwd>/.arco/plans/.history/<sha256>.md
8
+ // so the per-member audit copy of `cluster_plan_changed` can carry the hash
9
+ // instead of the whole body. The folder sits inside plans/, which no cleanup,
10
+ // archive or delete ever touches. Plan listing reads index.json and the plans
11
+ // watcher only reacts to top-level <id>.md files, so history files never show
12
+ // up as plans.
13
+ export function planHistoryDir(cwd: string): string {
14
+ return path.join(cwd, '.arco', 'plans', '.history');
15
+ }
16
+
17
+ export function planBodyHash(body: string): string {
18
+ return createHash('sha256').update(body, 'utf8').digest('hex');
19
+ }
20
+
21
+ // Write the body once (temporary file, flush, rename) and return its hash.
22
+ // Returns null for an empty body (a cleared plan) or when the write fails;
23
+ // callers then keep the body in the logged event so nothing is lost.
24
+ export function rememberPlanBody(cwd: string, body: string): string | null {
25
+ if (!cwd || !body) return null;
26
+ const hash = planBodyHash(body);
27
+ const dir = planHistoryDir(cwd);
28
+ const file = path.join(dir, `${hash}.md`);
29
+ try {
30
+ const st = lstatSync(file);
31
+ if (st.isFile()) return hash;
32
+ return null;
33
+ } catch (err) {
34
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') return null;
35
+ }
36
+ const tmp = path.join(dir, `.${hash}.${randomUUID()}.tmp`);
37
+ try {
38
+ ensureProjectStateIgnore(cwd);
39
+ mkdirSync(dir, { recursive: true });
40
+ const fd = openSync(tmp, 'wx', 0o600);
41
+ try { writeSync(fd, body, null, 'utf8'); fsyncSync(fd); } finally { closeSync(fd); }
42
+ renameSync(tmp, file);
43
+ return hash;
44
+ } catch {
45
+ try { unlinkSync(tmp); } catch { /* not created */ }
46
+ return null;
47
+ }
48
+ }
@@ -22,6 +22,7 @@ import {
22
22
  type ModelName,
23
23
  type EffortLevel,
24
24
  type MdTuneupCandidate,
25
+ type MdTuneupSkippedLink,
25
26
  } from '@arco/shared';
26
27
 
27
28
  // Dirs never worth scanning for instruction files — heavy, vendored, or
@@ -68,8 +69,10 @@ async function candidateMetrics(abs: string, bytes: number): Promise<Pick<MdTune
68
69
  // Discover recognized instruction files at the project root and in nested
69
70
  // folders. Results use project-relative paths and sort shallowest-first so
70
71
  // likely top-level guidance appears before files scoped to subdirectories.
71
- export async function discoverInstructionFiles(cwd: string): Promise<MdTuneupCandidate[]> {
72
+ export async function discoverInstructionFilesWithLinks(cwd: string): Promise<{ candidates: MdTuneupCandidate[]; skippedLinks: MdTuneupSkippedLink[] }> {
72
73
  const found: MdTuneupCandidate[] = [];
74
+ const links: string[] = [];
75
+ const root = await fs.realpath(cwd);
73
76
  const walk = async (dir: string, depth: number): Promise<void> => {
74
77
  if (depth > DISCOVERY_MAX_DEPTH) return;
75
78
  let entries;
@@ -82,6 +85,8 @@ export async function discoverInstructionFiles(cwd: string): Promise<MdTuneupCan
82
85
  if (ent.isDirectory()) {
83
86
  if (SKIP_DIRS.has(ent.name) || ent.name.startsWith('.')) continue;
84
87
  await walk(path.join(dir, ent.name), depth + 1);
88
+ } else if (ent.isSymbolicLink() && INSTRUCTION_NAME_SET.has(ent.name)) {
89
+ links.push(path.join(dir, ent.name));
85
90
  } else if (ent.isFile() && INSTRUCTION_NAME_SET.has(ent.name)) {
86
91
  const abs = path.join(dir, ent.name);
87
92
  let bytes = 0;
@@ -98,7 +103,32 @@ export async function discoverInstructionFiles(cwd: string): Promise<MdTuneupCan
98
103
  const db = b.path.split(path.sep).length;
99
104
  return da !== db ? da - db : a.path.localeCompare(b.path);
100
105
  });
101
- return found;
106
+ const targets = new Map<string, MdTuneupCandidate>();
107
+ for (const candidate of found) {
108
+ const abs = path.join(cwd, candidate.path);
109
+ try {
110
+ const stat = await fs.lstat(abs), real = await fs.realpath(abs);
111
+ if (stat.isFile() && !stat.isSymbolicLink() && withinRoot(root, real)) targets.set(real, candidate);
112
+ } catch { /* candidate disappeared during the scan */ }
113
+ }
114
+ const skippedLinks: MdTuneupSkippedLink[] = [];
115
+ for (const link of links) {
116
+ const relative = path.relative(cwd, link);
117
+ try {
118
+ const real = await fs.realpath(link);
119
+ if (!withinRoot(root, real)) { skippedLinks.push({ path: relative, reason: 'Target is outside this project.' }); continue; }
120
+ const target = targets.get(real);
121
+ if (!target) { skippedLinks.push({ path: relative, reason: 'Target is not a discovered instruction file.' }); continue; }
122
+ (target.alsoReadAs ??= []).push(relative);
123
+ } catch { skippedLinks.push({ path: relative, reason: 'Target cannot be resolved.' }); }
124
+ }
125
+ for (const candidate of found) candidate.alsoReadAs?.sort();
126
+ skippedLinks.sort((a, b) => a.path.localeCompare(b.path));
127
+ return { candidates: found, skippedLinks };
128
+ }
129
+
130
+ export async function discoverInstructionFiles(cwd: string): Promise<MdTuneupCandidate[]> {
131
+ return (await discoverInstructionFilesWithLinks(cwd)).candidates;
102
132
  }
103
133
 
104
134
  export interface MdTuneupEditorConfig {
@@ -161,6 +161,13 @@ function sanitizePriority(priority: unknown): number {
161
161
  return typeof priority === 'number' && Number.isFinite(priority) ? Math.trunc(priority) : 0;
162
162
  }
163
163
 
164
+ export const RELEASE_MAX = 24;
165
+
166
+ // Release label: one trimmed line, bounded. Empty means no label.
167
+ export function sanitizeRelease(value: unknown): string {
168
+ return typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, RELEASE_MAX) : '';
169
+ }
170
+
164
171
  function sanitizeGoalMaxTurns(value: unknown): { goalMaxTurns: number } | Record<string, never> {
165
172
  return typeof value === 'number' && Number.isFinite(value) && value > 0
166
173
  ? { goalMaxTurns: Math.trunc(value) }
@@ -202,6 +209,9 @@ function normalizeTask(task: LedgerTask): LedgerTask {
202
209
  ...sanitizeGoalMaxTurns(raw.goalMaxTurns),
203
210
  ...sanitizeAssignee(raw.assignee),
204
211
  };
212
+ const release = sanitizeRelease(raw.release);
213
+ if (release) next.release = release;
214
+ else delete next.release;
205
215
  if (!(typeof raw.assignee === 'string' && raw.assignee.trim().length > 0)) delete next.assignee;
206
216
  if (!(typeof raw.goalMaxTurns === 'number' && Number.isFinite(raw.goalMaxTurns) && raw.goalMaxTurns > 0)) {
207
217
  delete next.goalMaxTurns;
@@ -425,6 +435,7 @@ function toBoardRow(t: LedgerTask): Record<string, unknown> {
425
435
  ...(t.parentIds?.length ? { parentIds: t.parentIds } : {}),
426
436
  ...(t.links?.length ? { links: t.links } : {}),
427
437
  ...(t.reviewRequired ? { reviewRequired: true } : {}),
438
+ ...(t.release ? { release: t.release } : {}),
428
439
  ...(preview ? { notesPreview: preview } : {}),
429
440
  ...(notes.length > BOARD_NOTES_PREVIEW ? { notesLength: notes.length } : {}),
430
441
  createdAt: t.createdAt,
@@ -570,6 +581,7 @@ export function newTask(input: {
570
581
  goalMode?: boolean;
571
582
  goalMaxTurns?: number;
572
583
  worktreeRequired?: boolean;
584
+ release?: string;
573
585
  createdBy?: string;
574
586
  }): LedgerTask {
575
587
  const now = Date.now();
@@ -588,6 +600,7 @@ export function newTask(input: {
588
600
  goalMode: input.goalMode === true,
589
601
  worktreeRequired: input.worktreeRequired === true,
590
602
  ...sanitizeGoalMaxTurns(input.goalMaxTurns),
603
+ ...(sanitizeRelease(input.release) ? { release: sanitizeRelease(input.release) } : {}),
591
604
  ...(typeof input.createdBy === 'string' && input.createdBy.trim().length > 0
592
605
  ? { createdBy: input.createdBy.trim(), updatedBy: input.createdBy.trim() }
593
606
  : {}),
@@ -726,6 +739,8 @@ export function applyUpdate(
726
739
  goalMaxTurns?: number | null;
727
740
  assignee?: string;
728
741
  worktreeRequired?: boolean;
742
+ // Release label; '' clears it, undefined leaves it untouched.
743
+ release?: string;
729
744
  worktree?: TaskWorktree | null;
730
745
  // §D3 — director's advisory verdict. An object sets it (caller stamps
731
746
  // byWorkflowId/at); `null` clears it; `undefined` leaves it untouched.
@@ -755,6 +770,11 @@ export function applyUpdate(
755
770
  : {}),
756
771
  updatedAt: Date.now(),
757
772
  };
773
+ if (typeof patch.release === 'string') {
774
+ const label = sanitizeRelease(patch.release);
775
+ if (label) next.release = label;
776
+ else delete next.release;
777
+ }
758
778
  if (patch.goalMaxTurns !== undefined) {
759
779
  if (patch.goalMaxTurns === null) delete next.goalMaxTurns;
760
780
  else {
@@ -211,6 +211,7 @@ export function getPeerToolDefinitions(opts?: {
211
211
  reviewRequired: { type: 'boolean' },
212
212
  goalMode: { type: 'boolean' },
213
213
  goalMaxTurns: { type: 'number' },
214
+ release: { type: 'string', description: 'Optional release label such as 0.1.4.' },
214
215
  },
215
216
  required: ['title'],
216
217
  },
@@ -237,6 +238,7 @@ export function getPeerToolDefinitions(opts?: {
237
238
  id: { type: 'string', description: 'Task id from cluster_task_list.' },
238
239
  status: { type: 'string', enum: ['triage', 'todo', 'ready', 'in_progress', 'blocked', 'review'], description: "New status. 'done' and 'archived' are rejected — operator-only." },
239
240
  notes: { type: 'string', description: 'Replacement notes body for the task.' },
241
+ release: { type: 'string', description: 'Release label such as 0.1.4; an empty string clears it.' },
240
242
  signoff: {
241
243
  type: 'object',
242
244
  description: 'Advisory director verdict on whether the task met its target. Does NOT mark it done.',
@@ -466,6 +468,7 @@ export async function executePeerTool(
466
468
  ...(typeof args.reviewRequired === 'boolean' ? { reviewRequired: args.reviewRequired } : {}),
467
469
  ...(typeof args.goalMode === 'boolean' ? { goalMode: args.goalMode } : {}),
468
470
  ...(typeof args.goalMaxTurns === 'number' ? { goalMaxTurns: args.goalMaxTurns } : {}),
471
+ ...(typeof args.release === 'string' ? { release: args.release } : {}),
469
472
  ...(typeof args.status === 'string' ? { status: args.status as LedgerTaskStatus } : {}),
470
473
  },
471
474
  bcastCluster,
@@ -542,6 +545,7 @@ export async function executePeerTool(
542
545
  // non-status string falls through to applyUpdate's VALID_STATUS gate).
543
546
  ...(typeof args.status === 'string' ? { status: args.status as LedgerTaskStatus } : {}),
544
547
  ...(typeof args.notes === 'string' ? { notes: args.notes } : {}),
548
+ ...(typeof args.release === 'string' ? { release: args.release } : {}),
545
549
  // §D3 — advisory sign-off; peerTaskUpdate validates state + stamps author.
546
550
  ...(args.signoff !== undefined ? { signoff: args.signoff as { state?: string; summary?: string } | null } : {}),
547
551
  },
@@ -2,6 +2,7 @@ import { ensureProjectStateIgnore } from '../../projectStateIgnore.js';
2
2
  import { promises as fs } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { atomicWriteFile } from '../../atomicFile.js';
5
+ import { listSegments, readLogText } from '../../eventLog.js';
5
6
  import { serverFoldSeed, type ServerCompactionBlock } from './serverFold.js';
6
7
 
7
8
  const SUMMARY_CACHE_VERSION = 1;
@@ -123,6 +124,26 @@ function summaryCachePath(cwd: string, workflowId: string): string {
123
124
  return join(workflowDir(cwd, workflowId), 'resume-summary.json');
124
125
  }
125
126
 
127
+ // The history as a byte-addressed source. A plain log is read in place; a log
128
+ // with sealed segments (P7.3) is read once into memory, the same amount a
129
+ // whole-file read of the plain log took. Offsets are offsets in that text.
130
+ interface LogSource { size: number; read(start: number, length: number): Promise<string> }
131
+ async function openLogSource(cwd: string, workflowId: string): Promise<LogSource | null> {
132
+ const dir = workflowDir(cwd, workflowId);
133
+ if ((await listSegments(dir)).length > 0) {
134
+ const text = Buffer.from(await readLogText(dir), 'utf8');
135
+ return { size: text.length, read: async (start, length) => text.subarray(start, start + length).toString('utf8') };
136
+ }
137
+ const path = eventsPath(cwd, workflowId);
138
+ try {
139
+ const size = (await fs.stat(path)).size;
140
+ return { size, read: (start, length) => readByteRange(path, start, length) };
141
+ } catch (err) {
142
+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null;
143
+ throw err;
144
+ }
145
+ }
146
+
126
147
  async function readByteRange(path: string, start: number, length: number): Promise<string> {
127
148
  const fh = await fs.open(path, 'r');
128
149
  try {
@@ -134,10 +155,10 @@ async function readByteRange(path: string, start: number, length: number): Promi
134
155
  }
135
156
  }
136
157
 
137
- async function findTailReplayStart(path: string, desiredStart: number): Promise<{ start: number; completeLine: boolean }> {
158
+ async function findTailReplayStart(source: LogSource, desiredStart: number): Promise<{ start: number; completeLine: boolean }> {
138
159
  if (desiredStart <= 0) return { start: 0, completeLine: true };
139
160
  const probeStart = Math.max(0, desiredStart - TAIL_LINE_BACKTRACK_BYTES);
140
- const raw = await readByteRange(path, probeStart, desiredStart - probeStart);
161
+ const raw = await source.read(probeStart, desiredStart - probeStart);
141
162
  const lines = raw.split('\n');
142
163
  let cursor = probeStart;
143
164
  let turnStart: number | null = null;
@@ -527,16 +548,9 @@ export async function replayMessagesWithResumePolicy(
527
548
  maxSeq?: number,
528
549
  opts: ReplayOptions = {},
529
550
  ): Promise<ResumeReplayResult> {
530
- const path = eventsPath(cwd, workflowId);
531
- let stat;
532
- try {
533
- stat = await fs.stat(path);
534
- } catch (err) {
535
- if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
536
- return { messages: [], mode: 'empty', eventBytes: 0 };
537
- }
538
- throw err;
539
- }
551
+ const source = await openLogSource(cwd, workflowId);
552
+ if (!source) return { messages: [], mode: 'empty', eventBytes: 0 };
553
+ const stat = { size: source.size };
540
554
 
541
555
  const exactReplayBytes = opts.exactReplayBytes ?? RESUME_EXACT_REPLAY_BYTES;
542
556
  const recentTailBytes = opts.recentTailBytes ?? RESUME_RECENT_TAIL_BYTES;
@@ -555,7 +569,7 @@ export async function replayMessagesWithResumePolicy(
555
569
  // This is what lets post-rewind turns be included WITHOUT advancing leafSeq
556
570
  // on every turn.
557
571
  if (typeof opts.leafSeq === 'number') {
558
- const raw = await fs.readFile(path, 'utf8');
572
+ const raw = await source.read(0, stat.size);
559
573
  const events = parseJsonl(raw);
560
574
  let tailSeq: number | undefined;
561
575
  for (const e of events) {
@@ -572,7 +586,7 @@ export async function replayMessagesWithResumePolicy(
572
586
  }
573
587
 
574
588
  if (stat.size <= exactReplayBytes) {
575
- const raw = await fs.readFile(path, 'utf8');
589
+ const raw = await source.read(0, stat.size);
576
590
  const events = parseJsonl(raw);
577
591
  return {
578
592
  messages: buildMessagesFromReplayEvents(events, [], maxSeq),
@@ -585,7 +599,7 @@ export async function replayMessagesWithResumePolicy(
585
599
  // behavior so Spawn-from-here callers do not inherit a summary past maxSeq.
586
600
  if (typeof maxSeq === 'number') {
587
601
  const start = Math.max(0, stat.size - recentTailBytes);
588
- const raw = await readByteRange(path, start, stat.size - start);
602
+ const raw = await source.read(start, stat.size - start);
589
603
  const events = parseJsonl(raw, { dropFirstPartial: start > 0 });
590
604
  return {
591
605
  messages: buildMessagesFromReplayEvents(events, [], maxSeq),
@@ -596,15 +610,15 @@ export async function replayMessagesWithResumePolicy(
596
610
  }
597
611
 
598
612
  const desiredTailStartByte = Math.max(0, stat.size - recentTailBytes);
599
- const tailStart = await findTailReplayStart(path, desiredTailStartByte);
613
+ const tailStart = await findTailReplayStart(source, desiredTailStartByte);
600
614
  const tailStartByte = tailStart.start;
601
- const tailRaw = await readByteRange(path, tailStartByte, stat.size - tailStartByte);
615
+ const tailRaw = await source.read(tailStartByte, stat.size - tailStartByte);
602
616
  const tailEvents = parseJsonl(tailRaw, { dropFirstPartial: !tailStart.completeLine });
603
617
 
604
618
  const cachePath = summaryCachePath(cwd, workflowId);
605
619
  let cache = await readSummaryCache(cachePath, workflowId, stat.size, tailStartByte);
606
620
  if (!cache) {
607
- const olderRaw = tailStartByte > 0 ? await readByteRange(path, 0, tailStartByte) : '';
621
+ const olderRaw = tailStartByte > 0 ? await source.read(0, tailStartByte) : '';
608
622
  const olderEvents = parseJsonl(olderRaw, { dropLastPartial: !tailStart.completeLine });
609
623
  const built = summarizeClaudeNativePriorTurns(olderEvents);
610
624
  cache = {
@@ -9,6 +9,7 @@ import { CodexAppServerProvider, disposeCodexAppServerWorker } from './codex-app
9
9
  import { ClaudeNativeProvider, disposeClaudeNativeWorker } from './claude-native/index.js';
10
10
  import { LlamacppProvider } from './llamacpp.js';
11
11
  import { isLocalModelProvider, localModelsUnloading, localModelBusyMessage } from './localModelControl.js';
12
+ import { queueLocalProvider, type LocalProviderName } from './localProviderQueue.js';
12
13
  import { DeepSeekProvider } from './deepseek.js';
13
14
  import { StrataProvider } from './strata.js';
14
15
  import { LmstudioProvider } from './lmstudio.js';
@@ -36,16 +37,6 @@ const PROVIDERS: Record<ProviderName, Provider> = {
36
37
  // same backend; serializing matches the local-runtime pattern. (Override the
37
38
  // serial behavior via ARCO_LOCAL_PROVIDER_SERIAL_QUEUE=0, except Strata:
38
39
  // its profile manager requires the slot for the entire tool loop.)
39
- type LocalProviderName = 'ollama' | 'llamacpp' | 'lmstudio' | 'strata' | 'deepseek';
40
-
41
- const localQueues: Record<LocalProviderName, Promise<void>> = {
42
- ollama: Promise.resolve(),
43
- llamacpp: Promise.resolve(),
44
- lmstudio: Promise.resolve(),
45
- strata: Promise.resolve(),
46
- deepseek: Promise.resolve(),
47
- };
48
-
49
40
  class QueuedLocalProcess extends EventEmitter implements ProviderProcess {
50
41
  private inner: ProviderProcess | null = null;
51
42
  private killed = false;
@@ -100,12 +91,7 @@ class QueuedLocalProcess extends EventEmitter implements ProviderProcess {
100
91
  });
101
92
  };
102
93
 
103
- const prior = localQueues[this.providerName];
104
- let release!: () => void;
105
- localQueues[this.providerName] = new Promise<void>((resolve) => { release = resolve; });
106
- void prior
107
- .then(run, run)
108
- .finally(() => release());
94
+ void queueLocalProvider(this.providerName, run);
109
95
  this.emit('system_notice', `${this.providerName} local slot queued; Arco runs one ${this.providerName} worker at a time`);
110
96
  }
111
97
 
@@ -0,0 +1,13 @@
1
+ // Shared local-provider slots for worker turns and bounded side jobs.
2
+ export type LocalProviderName = 'ollama' | 'llamacpp' | 'lmstudio' | 'strata' | 'deepseek';
3
+ const queues: Record<LocalProviderName, Promise<void>> = {
4
+ ollama: Promise.resolve(), llamacpp: Promise.resolve(), lmstudio: Promise.resolve(),
5
+ strata: Promise.resolve(), deepseek: Promise.resolve(),
6
+ };
7
+
8
+ export function queueLocalProvider<T>(provider: LocalProviderName, run: () => Promise<T>): Promise<T> {
9
+ const prior = queues[provider];
10
+ let release!: () => void;
11
+ queues[provider] = new Promise<void>((resolve) => { release = resolve; });
12
+ return prior.then(run, run).finally(release);
13
+ }
@@ -0,0 +1,142 @@
1
+ // Public-project guardrails: suggestion from the Git remote and the check that
2
+ // Arco's project state stays out of Git. Read-only except for the two explicit
3
+ // fixes (restore the ignore file, stop tracking). Every git call is argv-only.
4
+ import { execFile } from 'node:child_process';
5
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { promisify } from 'node:util';
8
+ import { DEFAULT_PROJECT_IGNORE } from './projectStateIgnore.js';
9
+
10
+ const execFileAsync = promisify(execFile);
11
+ const GIT_TIMEOUT_MS = 10_000;
12
+ const FETCH_TIMEOUT_MS = 4_000;
13
+ const CACHE_MS = 24 * 60 * 60 * 1000;
14
+ export const PUBLIC_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.org', 'codeberg.org'];
15
+
16
+ export interface ParsedRemote { name: string; host: string; owner: string; repo: string }
17
+ export type RemoteSuggestion =
18
+ | { state: 'none' }
19
+ | { state: 'hosted'; host: string }
20
+ | { state: 'public'; host: string };
21
+
22
+ export function projectGitEnv(): NodeJS.ProcessEnv {
23
+ const env: NodeJS.ProcessEnv = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
24
+ for (const name of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES']) delete env[name];
25
+ return env;
26
+ }
27
+
28
+ async function git(cwd: string, args: string[]): Promise<{ code: number; stdout: string }> {
29
+ try {
30
+ const { stdout } = await execFileAsync('git', args, { cwd, timeout: GIT_TIMEOUT_MS, maxBuffer: 1024 * 1024, encoding: 'utf8', env: projectGitEnv() });
31
+ return { code: 0, stdout };
32
+ } catch (err) {
33
+ const e = err as { code?: number | string; stdout?: string };
34
+ return { code: typeof e.code === 'number' ? e.code : 1, stdout: e.stdout ?? '' };
35
+ }
36
+ }
37
+
38
+ export function parseRemoteUrl(url: string): Omit<ParsedRemote, 'name'> | null {
39
+ const text = url.trim();
40
+ const m = /^(?:[a-z+]+:\/\/)?(?:[^@/]+@)?([^/:]+)[/:](?:\d+\/)?([^/]+)\/([^/]+?)(?:\.git)?\/?$/i.exec(text);
41
+ if (!m) return null;
42
+ const host = m[1]!.toLowerCase();
43
+ if (!PUBLIC_HOSTS.includes(host)) return null;
44
+ return { host, owner: m[2]!, repo: m[3]! };
45
+ }
46
+
47
+ /** Parse `git remote -v` output; fetch lines only, origin first. */
48
+ export function parseRemotes(text: string): ParsedRemote[] {
49
+ const out: ParsedRemote[] = [];
50
+ for (const line of text.split(/\r?\n/)) {
51
+ const m = /^(\S+)\s+(\S+)\s+\(fetch\)$/.exec(line.trim());
52
+ if (!m) continue;
53
+ const parsed = parseRemoteUrl(m[2]!);
54
+ if (parsed) out.push({ name: m[1]!, ...parsed });
55
+ }
56
+ return out.sort((a, b) => Number(b.name === 'origin') - Number(a.name === 'origin'));
57
+ }
58
+
59
+ type FetchLike = (url: string, init: { signal: AbortSignal; headers: Record<string, string> }) => Promise<{ status: number; json(): Promise<unknown> }>;
60
+
61
+ /** One unauthenticated request. 200 with private:false means public; anything else is unknown. */
62
+ export async function githubIsPublic(owner: string, repo: string, fetchImpl: FetchLike = fetch as unknown as FetchLike): Promise<boolean> {
63
+ if (!/^[A-Za-z0-9._-]+$/.test(owner) || !/^[A-Za-z0-9._-]+$/.test(repo)) return false;
64
+ const ctl = new AbortController();
65
+ const timer = setTimeout(() => ctl.abort(), FETCH_TIMEOUT_MS);
66
+ try {
67
+ const res = await fetchImpl(`https://api.github.com/repos/${owner}/${repo}`, { signal: ctl.signal, headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'arco' } });
68
+ if (res.status !== 200) return false;
69
+ const body = await res.json() as { private?: unknown };
70
+ return body.private === false;
71
+ } catch { return false; } finally { clearTimeout(timer); }
72
+ }
73
+
74
+ const cache = new Map<string, { at: number; value: RemoteSuggestion }>();
75
+ export function clearRemoteCache(): void { cache.clear(); }
76
+
77
+ export async function suggestFromRemote(cwd: string, opts: { fetchImpl?: FetchLike; now?: number } = {}): Promise<RemoteSuggestion> {
78
+ const now = opts.now ?? Date.now();
79
+ const hit = cache.get(cwd);
80
+ if (hit && now - hit.at < CACHE_MS) return hit.value;
81
+ const listed = await git(cwd, ['remote', '-v']);
82
+ const remote = listed.code === 0 ? parseRemotes(listed.stdout)[0] : undefined;
83
+ let value: RemoteSuggestion = { state: 'none' };
84
+ if (remote) {
85
+ value = remote.host === 'github.com' && await githubIsPublic(remote.owner, remote.repo, opts.fetchImpl)
86
+ ? { state: 'public', host: remote.host }
87
+ : { state: 'hosted', host: remote.host };
88
+ }
89
+ cache.set(cwd, { at: now, value });
90
+ return value;
91
+ }
92
+
93
+ export interface ProjectStateReport {
94
+ isGit: boolean;
95
+ hasState: boolean;
96
+ tracked: number;
97
+ trackedSample: string[];
98
+ ignored: boolean;
99
+ ignoreFile: 'default' | 'missing' | 'edited';
100
+ }
101
+
102
+ export async function checkProjectState(cwd: string): Promise<ProjectStateReport> {
103
+ const base: ProjectStateReport = { isGit: false, hasState: false, tracked: 0, trackedSample: [], ignored: true, ignoreFile: 'default' };
104
+ if (/[\\/]isolates[\\/]/.test(cwd)) return base;
105
+ const inside = await git(cwd, ['rev-parse', '--is-inside-work-tree']);
106
+ if (inside.code !== 0 || inside.stdout.trim() !== 'true') return base;
107
+ base.isGit = true;
108
+ const dir = join(cwd, '.arco');
109
+ const file = join(dir, '.gitignore');
110
+ const listed = await git(cwd, ['ls-files', '--', '.arco']);
111
+ const tracked = listed.code === 0 ? listed.stdout.split('\n').filter(Boolean) : [];
112
+ base.tracked = tracked.length;
113
+ base.trackedSample = tracked.slice(0, 5);
114
+ base.hasState = tracked.length > 0 || (existsSync(dir) && statSync(dir).isDirectory());
115
+ if (!base.hasState) return base;
116
+ base.ignoreFile = !existsSync(file) ? 'missing' : readFileSync(file, 'utf8') === DEFAULT_PROJECT_IGNORE ? 'default' : 'edited';
117
+ base.ignored = (await git(cwd, ['check-ignore', '-q', '--no-index', '--', '.arco/workflows/.probe'])).code === 0;
118
+ return base;
119
+ }
120
+
121
+ /** Write the default ignore file; an existing different file is moved aside first. */
122
+ export function restoreIgnoreFile(cwd: string): { backup?: string } {
123
+ const dir = join(cwd, '.arco');
124
+ const file = join(dir, '.gitignore');
125
+ let backup: string | undefined;
126
+ if (existsSync(file)) {
127
+ if (readFileSync(file, 'utf8') === DEFAULT_PROJECT_IGNORE) return {};
128
+ backup = `.gitignore.backup-${new Date().toISOString().replace(/[:.]/g, '-')}`;
129
+ renameSync(file, join(dir, backup));
130
+ }
131
+ writeFileSync(file, DEFAULT_PROJECT_IGNORE, { encoding: 'utf8', flag: 'wx' });
132
+ return backup ? { backup } : {};
133
+ }
134
+
135
+ /** Remove .arco from the index only. Files stay on disk. */
136
+ export async function stopTrackingState(cwd: string): Promise<{ ok: boolean; removed: number; error?: string }> {
137
+ const before = await git(cwd, ['ls-files', '--', '.arco']);
138
+ const count = before.stdout.split('\n').filter(Boolean).length;
139
+ if (count === 0) return { ok: true, removed: 0 };
140
+ const res = await git(cwd, ['rm', '-r', '-q', '--cached', '--', '.arco']);
141
+ return res.code === 0 ? { ok: true, removed: count } : { ok: false, removed: 0, error: 'git could not stop tracking the folder' };
142
+ }