arco-workbench 0.2.2 → 0.2.5

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 (276) hide show
  1. package/CONTRIBUTING.md +1 -1
  2. package/THIRD_PARTY_NOTICES +2 -2
  3. package/client/dist/assets/{PhosphorBackdrop-BbR3xmfD.js → PhosphorBackdrop-CLILIwOQ.js} +1 -1
  4. package/client/dist/assets/{ThemedBackgroundShaderImpl-UMjbs9ZN.js → ThemedBackgroundShaderImpl-B87chcb5.js} +1 -1
  5. package/client/dist/assets/{XtermView-n135qz-f.js → XtermView-BP_j7WSN.js} +1 -1
  6. package/client/dist/assets/{galleryEditor-CFSke4by.js → galleryEditor-B90phoBI.js} +1 -1
  7. package/client/dist/assets/{index-DeoJbjI3.js → index-BfPp1Oup.js} +270 -270
  8. package/client/dist/index.html +1 -1
  9. package/client/dist/manifest-mobile.webmanifest +1 -0
  10. package/client/src/App.tsx +2 -2
  11. package/client/src/components/AuthReloginNotice.tsx +7 -6
  12. package/client/src/components/ChatMessage.tsx +41 -29
  13. package/client/src/components/ChatPanel.tsx +17 -4
  14. package/client/src/components/ClaudeNativeAccountPicker.tsx +32 -0
  15. package/client/src/components/ClaudeNativeAuthRow.tsx +71 -19
  16. package/client/src/components/ClusterRightPanel/AddWorkerSection.tsx +11 -281
  17. package/client/src/components/ClusterRightPanel/AutoPickupControl.tsx +1 -1
  18. package/client/src/components/ClusterRightPanel/FreshMemberForm.tsx +315 -0
  19. package/client/src/components/ClusterRightPanel/ReplaceMemberDialog.tsx +17 -7
  20. package/client/src/components/ClusterRightPanel/index.tsx +1 -1
  21. package/client/src/components/ClusterRightPanel/useFreshMemberPicker.ts +6 -4
  22. package/client/src/components/ClusterTab.tsx +2 -2
  23. package/client/src/components/Connections/Connections.tsx +7 -11
  24. package/client/src/components/Connections/model.ts +3 -1
  25. package/client/src/components/FileViewerModal.tsx +54 -17
  26. package/client/src/components/GitHubPanel/index.tsx +9 -5
  27. package/client/src/components/HandoffDialog.tsx +5 -3
  28. package/client/src/components/MobileShell.tsx +1 -33
  29. package/client/src/components/OperatorQuestionNotice.tsx +5 -4
  30. package/client/src/components/ProvidersPopover.tsx +6 -2
  31. package/client/src/components/RightPanel/ActivityTab.tsx +2 -1
  32. package/client/src/components/RightPanel/ConfigTab.tsx +23 -5
  33. package/client/src/components/RightPanel/OutputsPanel.tsx +21 -9
  34. package/client/src/components/RightPanel/outputsReconcile.ts +31 -0
  35. package/client/src/components/SettingsPanel.tsx +7 -10
  36. package/client/src/components/SpawnDialog.tsx +14 -3
  37. package/client/src/components/TabBar.tsx +2 -2
  38. package/client/src/components/TabContextMenu.tsx +73 -133
  39. package/client/src/components/TerminalInput.tsx +4 -3
  40. package/client/src/components/TranscriptWorkerDialog.tsx +14 -4
  41. package/client/src/components/UsageBar.tsx +37 -18
  42. package/client/src/components/WorkflowCreator/ClusterMembersSection.tsx +29 -3
  43. package/client/src/components/WorkflowCreator/index.tsx +29 -15
  44. package/client/src/components/WorkflowView.tsx +1 -1
  45. package/client/src/components/providerIndicator.ts +7 -3
  46. package/client/src/components/research/QuickResearchOverview.tsx +7 -3
  47. package/client/src/components/research/SavedQuickKeep.tsx +7 -3
  48. package/client/src/components/settings/GitHubAuthRow.tsx +34 -0
  49. package/client/src/explorer/ArtifactsLens.tsx +17 -8
  50. package/client/src/explorer/ExplorerApp.tsx +3 -3
  51. package/client/src/explorer/types.ts +3 -1
  52. package/client/src/help/content/cluster.tsx +10 -4
  53. package/client/src/help/content/composer.tsx +3 -2
  54. package/client/src/help/content/header.tsx +6 -3
  55. package/client/src/help/content/misc.tsx +9 -7
  56. package/client/src/help/content/rightPanel.tsx +11 -6
  57. package/client/src/help/content/settings.tsx +14 -3
  58. package/client/src/help/content/tabbar.tsx +1 -1
  59. package/client/src/help/manualSections/actions.tsx +5 -1
  60. package/client/src/help/manualSections/clusters.tsx +21 -15
  61. package/client/src/help/manualSections/configuration.tsx +6 -4
  62. package/client/src/help/manualSections/gettingStarted.tsx +4 -2
  63. package/client/src/help/manualSections/maintenance.tsx +24 -0
  64. package/client/src/help/manualSections/powerFeatures.tsx +4 -2
  65. package/client/src/help/manualSections/providers.tsx +11 -4
  66. package/client/src/help/manualSections/workspace.tsx +3 -3
  67. package/client/src/hooks/useClaudeNativeCatalog.ts +26 -0
  68. package/client/src/hooks/useClaudeNativeLogin.ts +16 -11
  69. package/client/src/hooks/useWebSocket.ts +4 -2
  70. package/client/src/layout/layoutRange.ts +14 -5
  71. package/client/src/main.tsx +2 -0
  72. package/client/src/questions/waitingQuestion.ts +2 -0
  73. package/client/src/stores/appStore.ts +5 -1
  74. package/client/src/stores/appStore.types.ts +2 -0
  75. package/client/src/stores/replayContext.ts +20 -0
  76. package/client/src/utils/chatFileLinks.ts +34 -3
  77. package/client/src/utils/claudeAuth.ts +9 -1
  78. package/client/src/ws/handleServerMessage.ts +11 -3
  79. package/docs/ARCHITECTURE.md +3 -3
  80. package/docs/BACKUP.md +1 -1
  81. package/docs/CHECKPOINTS.md +67 -3
  82. package/docs/CLIENT.md +11 -6
  83. package/docs/EXTENDING.md +1 -1
  84. package/docs/FEATURES.md +3 -3
  85. package/docs/GETTING_STARTED.md +5 -4
  86. package/docs/GIT_WORKBENCH.md +8 -0
  87. package/docs/GLOSSARY.md +2 -2
  88. package/docs/GOTCHAS.md +4 -4
  89. package/docs/HTTP_API.md +63 -30
  90. package/docs/OPERATIONS.md +11 -0
  91. package/docs/OPERATOR_ACTIONS.md +2 -2
  92. package/docs/OUTPUTS.md +48 -6
  93. package/docs/PERSISTENCE.md +1 -1
  94. package/docs/PRIMITIVES.md +4 -2
  95. package/docs/PROTOCOL_CLUSTER.md +12 -6
  96. package/docs/PROTOCOL_PRIMITIVES.md +1 -1
  97. package/docs/PROVIDERS.md +47 -10
  98. package/docs/RESEARCH.md +3 -3
  99. package/docs/SETTINGS.md +9 -4
  100. package/node_modules/@arco/shared/dist/protocol/clusters.d.ts +15 -3
  101. package/node_modules/@arco/shared/dist/protocol/clusters.js +1 -1
  102. package/node_modules/@arco/shared/dist/protocol/models.d.ts +6 -1
  103. package/node_modules/@arco/shared/dist/protocol/operatorQuestions.d.ts +2 -1
  104. package/node_modules/@arco/shared/dist/protocol/settings.d.ts +3 -0
  105. package/node_modules/@arco/shared/dist/protocol/settings.js +5 -0
  106. package/node_modules/@arco/shared/dist/protocol/workflows.d.ts +1 -0
  107. package/node_modules/@arco/shared/dist/protocol/workflows.js +0 -2
  108. package/node_modules/@arco/shared/package.json +1 -1
  109. package/package.json +2 -2
  110. package/scripts/packaging/services.mjs +20 -1
  111. package/scripts/packaging/update.mjs +37 -2
  112. package/server/dist/attention.d.ts +6 -0
  113. package/server/dist/attention.js +6 -0
  114. package/server/dist/auth.d.ts +5 -0
  115. package/server/dist/auth.js +31 -20
  116. package/server/dist/clusterAutoTurn.d.ts +5 -1
  117. package/server/dist/clusterAutoTurn.js +31 -9
  118. package/server/dist/clusterPresets.js +3 -3
  119. package/server/dist/effortValidation.d.ts +2 -2
  120. package/server/dist/effortValidation.js +4 -4
  121. package/server/dist/explorerArtifacts.d.ts +1 -0
  122. package/server/dist/explorerArtifacts.js +12 -1
  123. package/server/dist/explorerDocs.d.ts +1 -0
  124. package/server/dist/explorerDocs.js +4 -4
  125. package/server/dist/geminiMembers.d.ts +7 -1
  126. package/server/dist/geminiMembers.js +28 -14
  127. package/server/dist/gitSnapshots.d.ts +1 -0
  128. package/server/dist/gitSnapshots.js +547 -83
  129. package/server/dist/http/clusterRoutes.js +9 -3
  130. package/server/dist/http/conversationFiles.d.ts +36 -0
  131. package/server/dist/http/conversationFiles.js +222 -0
  132. package/server/dist/http/fileBytes.d.ts +3 -0
  133. package/server/dist/http/fileBytes.js +33 -0
  134. package/server/dist/http/fileContentRoute.d.ts +2 -0
  135. package/server/dist/http/fileContentRoute.js +139 -0
  136. package/server/dist/http/fileRead.d.ts +54 -2
  137. package/server/dist/http/fileRead.js +31 -24
  138. package/server/dist/http/outputRoutes.js +14 -21
  139. package/server/dist/http/readConfinement.d.ts +0 -11
  140. package/server/dist/http/readConfinement.js +4 -30
  141. package/server/dist/http/router.js +41 -66
  142. package/server/dist/index.js +26 -12
  143. package/server/dist/management/initHubLink.js +1 -1
  144. package/server/dist/outputs.js +8 -0
  145. package/server/dist/primitives/exportContext.d.ts +2 -0
  146. package/server/dist/primitives/exportContext.js +13 -2
  147. package/server/dist/primitives/runCompare.d.ts +7 -1
  148. package/server/dist/primitives/runCompare.js +44 -20
  149. package/server/dist/project/taskLedger.js +46 -34
  150. package/server/dist/providerAccounts.d.ts +4 -0
  151. package/server/dist/providerAccounts.js +20 -1
  152. package/server/dist/providers/antigravity/artifacts.d.ts +23 -0
  153. package/server/dist/providers/antigravity/artifacts.js +140 -0
  154. package/server/dist/providers/antigravity/index.js +85 -7
  155. package/server/dist/providers/antigravity/questions.d.ts +2 -0
  156. package/server/dist/providers/antigravity/questions.js +58 -0
  157. package/server/dist/providers/claude-native/auth.d.ts +9 -8
  158. package/server/dist/providers/claude-native/auth.js +50 -58
  159. package/server/dist/providers/claude-native/authStatus.d.ts +2 -2
  160. package/server/dist/providers/claude-native/authStatus.js +9 -7
  161. package/server/dist/providers/claude-native/catalog.d.ts +6 -5
  162. package/server/dist/providers/claude-native/catalog.js +50 -39
  163. package/server/dist/providers/claude-native/oauth.d.ts +10 -9
  164. package/server/dist/providers/claude-native/oauth.js +120 -96
  165. package/server/dist/providers/claude-native/worker.d.ts +1 -0
  166. package/server/dist/providers/claude-native/worker.js +38 -23
  167. package/server/dist/providers/codex-appserver/operatorQuestions.d.ts +5 -3
  168. package/server/dist/providers/codex-appserver/operatorQuestions.js +27 -13
  169. package/server/dist/providers/codexChatBoundary.js +6 -1
  170. package/server/dist/research/quickPromotion.d.ts +3 -0
  171. package/server/dist/research/quickPromotion.js +26 -9
  172. package/server/dist/research/savedQuickPromotion.js +2 -11
  173. package/server/dist/server/broadcast.js +6 -0
  174. package/server/dist/settings.d.ts +1 -0
  175. package/server/dist/settings.js +39 -7
  176. package/server/dist/skills.js +1 -1
  177. package/server/dist/smartPickupAdapters.d.ts +1 -0
  178. package/server/dist/smartPickupAdapters.js +2 -2
  179. package/server/dist/smartPickupObserver.js +8 -5
  180. package/server/dist/thirdPartySkills.js +11 -5
  181. package/server/dist/turnChanges.d.ts +1 -1
  182. package/server/dist/turnChanges.js +5 -4
  183. package/server/dist/usage.d.ts +1 -1
  184. package/server/dist/usage.js +39 -27
  185. package/server/dist/workers/WorkerManager.d.ts +1 -0
  186. package/server/dist/workers/WorkerManager.js +1 -0
  187. package/server/dist/workers/processKill.js +37 -24
  188. package/server/dist/workflowMeta.js +2 -2
  189. package/server/dist/ws/clusterHandlers.d.ts +2 -2
  190. package/server/dist/ws/clusterHandlers.js +127 -113
  191. package/server/dist/ws/clusterMembers.d.ts +1 -1
  192. package/server/dist/ws/clusterMembers.js +34 -4
  193. package/server/dist/ws/compactHandlers.js +30 -14
  194. package/server/dist/ws/compareHandlers.js +53 -21
  195. package/server/dist/ws/gateHandlers.js +2 -0
  196. package/server/dist/ws/genesisHandlers.js +5 -3
  197. package/server/dist/ws/handoffHandlers.d.ts +1 -1
  198. package/server/dist/ws/handoffHandlers.js +115 -39
  199. package/server/dist/ws/transcriptWorkerHandlers.js +7 -2
  200. package/server/dist/ws/turnEngine.js +37 -19
  201. package/server/dist/ws/updatePrimaryConfig.d.ts +3 -2
  202. package/server/dist/ws/updatePrimaryConfig.js +236 -133
  203. package/server/dist/ws/workflowHandlers.js +21 -4
  204. package/server/package.json +1 -1
  205. package/server/src/attention.ts +7 -0
  206. package/server/src/auth.ts +33 -20
  207. package/server/src/clusterAutoTurn.ts +31 -11
  208. package/server/src/clusterPresets.ts +2 -2
  209. package/server/src/effortValidation.ts +4 -4
  210. package/server/src/explorerArtifacts.ts +12 -1
  211. package/server/src/explorerDocs.ts +5 -5
  212. package/server/src/geminiMembers.ts +26 -15
  213. package/server/src/gitSnapshots.ts +538 -82
  214. package/server/src/http/clusterRoutes.ts +10 -3
  215. package/server/src/http/conversationFiles.ts +231 -0
  216. package/server/src/http/fileBytes.ts +34 -0
  217. package/server/src/http/fileContentRoute.ts +123 -0
  218. package/server/src/http/fileRead.ts +30 -25
  219. package/server/src/http/outputRoutes.ts +13 -13
  220. package/server/src/http/readConfinement.ts +3 -30
  221. package/server/src/http/router.ts +39 -62
  222. package/server/src/index.ts +27 -18
  223. package/server/src/management/initHubLink.ts +1 -1
  224. package/server/src/outputs.ts +8 -0
  225. package/server/src/primitives/exportContext.ts +14 -2
  226. package/server/src/primitives/runCompare.ts +73 -46
  227. package/server/src/project/taskLedger.ts +47 -30
  228. package/server/src/providerAccounts.ts +20 -1
  229. package/server/src/providers/antigravity/artifacts.ts +121 -0
  230. package/server/src/providers/antigravity/index.ts +64 -6
  231. package/server/src/providers/antigravity/questions.ts +52 -0
  232. package/server/src/providers/claude-native/auth.ts +45 -60
  233. package/server/src/providers/claude-native/authStatus.ts +9 -8
  234. package/server/src/providers/claude-native/catalog.ts +52 -35
  235. package/server/src/providers/claude-native/oauth.ts +101 -77
  236. package/server/src/providers/claude-native/worker.ts +38 -22
  237. package/server/src/providers/codex-appserver/operatorQuestions.ts +26 -12
  238. package/server/src/providers/codexChatBoundary.ts +6 -1
  239. package/server/src/research/quickPromotion.ts +24 -6
  240. package/server/src/research/savedQuickPromotion.ts +2 -8
  241. package/server/src/server/broadcast.ts +4 -0
  242. package/server/src/settings.ts +36 -8
  243. package/server/src/skills.ts +1 -1
  244. package/server/src/smartPickupAdapters.ts +3 -2
  245. package/server/src/smartPickupObserver.ts +8 -5
  246. package/server/src/thirdPartySkills.ts +11 -5
  247. package/server/src/turnChanges.ts +5 -4
  248. package/server/src/usage.ts +30 -22
  249. package/server/src/workers/WorkerManager.ts +2 -0
  250. package/server/src/workers/processKill.ts +37 -23
  251. package/server/src/workflowMeta.ts +2 -2
  252. package/server/src/ws/clusterHandlers.ts +107 -104
  253. package/server/src/ws/clusterMembers.ts +25 -6
  254. package/server/src/ws/compactHandlers.ts +29 -15
  255. package/server/src/ws/compareHandlers.ts +59 -25
  256. package/server/src/ws/gateHandlers.ts +2 -0
  257. package/server/src/ws/genesisHandlers.ts +5 -4
  258. package/server/src/ws/handoffHandlers.ts +105 -37
  259. package/server/src/ws/transcriptWorkerHandlers.ts +6 -2
  260. package/server/src/ws/turnEngine.ts +36 -18
  261. package/server/src/ws/updatePrimaryConfig.ts +230 -132
  262. package/server/src/ws/workflowHandlers.ts +20 -4
  263. package/shared/dist/protocol/clusters.d.ts +15 -3
  264. package/shared/dist/protocol/clusters.js +1 -1
  265. package/shared/dist/protocol/models.d.ts +6 -1
  266. package/shared/dist/protocol/operatorQuestions.d.ts +2 -1
  267. package/shared/dist/protocol/settings.d.ts +3 -0
  268. package/shared/dist/protocol/settings.js +5 -0
  269. package/shared/dist/protocol/workflows.d.ts +1 -0
  270. package/shared/dist/protocol/workflows.js +0 -2
  271. package/shared/src/protocol/clusters.ts +23 -5
  272. package/shared/src/protocol/compare.ts +2 -2
  273. package/shared/src/protocol/models.ts +8 -4
  274. package/shared/src/protocol/operatorQuestions.ts +2 -1
  275. package/shared/src/protocol/settings.ts +8 -1
  276. package/shared/src/protocol/workflows.ts +1 -1
@@ -25,7 +25,7 @@ import { restoreLegacyTar } from './legacyTarRestore.js';
25
25
  // would mutate the user's real index). Always pass GIT_INDEX_FILE, and always
26
26
  // use execFile with an argv array (no shell string interpolation).
27
27
 
28
- import { execFile } from 'node:child_process';
28
+ import { execFile, spawn } from 'node:child_process';
29
29
  import { promisify } from 'node:util';
30
30
  import { setImmediate } from 'node:timers/promises';
31
31
  import { promises as fs } from 'node:fs';
@@ -89,6 +89,9 @@ export interface CreateCheckpointArgs {
89
89
  // Internal admission token for the restore's own safety snapshot.
90
90
  restoreOwner?: symbol;
91
91
  onSkipped?: (message: string) => void;
92
+ // Cancels the capture: running Git commands are stopped, the operation's
93
+ // objects are discarded and no ref is published.
94
+ signal?: AbortSignal;
92
95
  }
93
96
 
94
97
  export interface CheckpointResult {
@@ -113,11 +116,15 @@ async function runGit(
113
116
  cwd: string,
114
117
  args: string[],
115
118
  extraEnv?: NodeJS.ProcessEnv,
119
+ timeout = GIT_TIMEOUT_MS,
120
+ signal?: AbortSignal,
116
121
  ): Promise<{ stdout: string; stderr: string; code: number }> {
122
+ if (signal?.aborted) return { stdout: '', stderr: 'aborted', code: 1 };
117
123
  try {
118
124
  const { stdout, stderr } = await execFileAsync('git', args, {
119
125
  cwd,
120
- timeout: GIT_TIMEOUT_MS,
126
+ timeout,
127
+ ...(signal ? { signal } : {}),
121
128
  maxBuffer: GIT_MAX_BUFFER,
122
129
  env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
123
130
  });
@@ -155,8 +162,8 @@ function refFor(workflowId: string, seq: number): string {
155
162
 
156
163
  // Count files in a tree object (recursive). Used for the fileCount surfaced to
157
164
  // the operator. `-r` recurses, one line per blob.
158
- async function countTreeFiles(cwd: string, gitDir: string, treeish: string): Promise<number> {
159
- const out = await runGit(cwd, ['--git-dir', gitDir, 'ls-tree', '-r', '--name-only', treeish]);
165
+ async function countTreeFiles(cwd: string, gitDir: string, treeish: string, env?: NodeJS.ProcessEnv): Promise<number> {
166
+ const out = await runGit(cwd, ['--git-dir', gitDir, 'ls-tree', '-r', '--name-only', treeish], env);
160
167
  if (out.code !== 0) return 0;
161
168
  return out.stdout.split('\n').filter((l) => l.trim().length > 0).length;
162
169
  }
@@ -194,6 +201,56 @@ async function pruneOldCheckpoints(
194
201
  }
195
202
  }
196
203
 
204
+ // Write the checkpoint ref unless the capture was cancelled. A cancellation
205
+ // that lands while update-ref runs is undone again, conditionally on the ref
206
+ // still pointing at this capture, so a late capture never leaves an undo point.
207
+ async function publishRef(cwd: string, gitDir: string, ref: string, sha: string, signal?: AbortSignal): Promise<boolean> {
208
+ if (signal?.aborted) return false;
209
+ const update = await runGit(cwd, ['--git-dir', gitDir, 'update-ref', ref, sha]);
210
+ if (update.code !== 0) {
211
+ console.error(`[arco] gitSnapshots update-ref failed: ${update.stderr.trim()}`);
212
+ return false;
213
+ }
214
+ if (signal?.aborted) {
215
+ await withdrawRef(cwd, gitDir, ref, sha);
216
+ return false;
217
+ }
218
+ return true;
219
+ }
220
+
221
+ // Delete a checkpoint ref only while it still points at this capture.
222
+ async function withdrawRef(cwd: string, gitDir: string, ref: string, sha: string): Promise<void> {
223
+ await runGit(cwd, ['--git-dir', gitDir, 'update-ref', '-d', ref, sha]);
224
+ }
225
+
226
+ // Sizes of the blobs just staged for `paths`, checked against the per-file
227
+ // and included-total caps. Fails closed when the sizes cannot be read.
228
+ async function stagedWithinCaps(cwd: string, gitDir: string, env: NodeJS.ProcessEnv, staged: Map<string, { mode: string; sha: string }>, paths: string[], signal?: AbortSignal): Promise<boolean> {
229
+ const shas = paths.map(p => staged.get(p)).filter((e): e is { mode: string; sha: string } => !!e && e.mode !== '160000').map(e => e.sha);
230
+ if (!shas.length) return true;
231
+ const sizes = await gitWithInput(cwd, ['--git-dir', gitDir, 'cat-file', '--batch-check=%(objectsize)'], shas.join('\n') + '\n', env, signal);
232
+ if (sizes === null) return false;
233
+ const values = sizes.split('\n').filter(Boolean).map(Number);
234
+ if (values.length !== shas.length || values.some(v => !Number.isFinite(v))) return false;
235
+ const fileCap = fileCapBytes(), totalCap = totalCapBytes();
236
+ if (fileCap > 0 && values.some(v => v > fileCap)) return false;
237
+ return !(totalCap > 0 && values.reduce((a, b) => a + b, 0) > totalCap);
238
+ }
239
+
240
+ function gitWithInput(cwd: string, args: string[], input: string, extraEnv: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<string | null> {
241
+ return new Promise((resolve) => {
242
+ const child = spawn('git', args, { cwd, env: { ...process.env, ...extraEnv }, stdio: ['pipe', 'pipe', 'ignore'], ...(signal ? { signal } : {}) });
243
+ const chunks: Buffer[] = [];
244
+ let size = 0;
245
+ const timer = setTimeout(() => child.kill(), GIT_TIMEOUT_MS);
246
+ child.stdout.on('data', (chunk: Buffer) => { size += chunk.length; if (size <= GIT_MAX_BUFFER) chunks.push(chunk); else child.kill(); });
247
+ child.on('error', () => { clearTimeout(timer); resolve(null); });
248
+ child.on('close', (code) => { clearTimeout(timer); resolve(code === 0 && size <= GIT_MAX_BUFFER ? Buffer.concat(chunks).toString('utf8') : null); });
249
+ child.stdin.on('error', () => {});
250
+ child.stdin.end(input);
251
+ });
252
+ }
253
+
197
254
  async function createGitCheckpoint(
198
255
  args: CreateCheckpointArgs,
199
256
  gitDir: string,
@@ -215,29 +272,51 @@ async function createGitCheckpoint(
215
272
  // what the operator would see). On an unborn HEAD (fresh repo, no commits)
216
273
  // skip the read-tree and let add -A build the index from scratch.
217
274
  const snapEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: snapIndex };
218
- const protectedPaths = await providerHomePaths(await gitCheckpointWorkTree(cwd, gitDir));
275
+ const root = await gitCheckpointWorkTree(cwd, gitDir);
276
+ const protectedPaths = await providerHomePaths(root);
219
277
  if (protectedPaths.includes('.')) return null;
220
- const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'])).code === 0;
278
+ const signal = args.signal;
279
+ const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'], undefined, GIT_TIMEOUT_MS, signal)).code === 0;
280
+ let quarantine: ObjectQuarantine | null = null;
281
+ let cleaned = false;
282
+ const cleanup = async () => {
283
+ cleaned = true;
284
+ await fs.rm(snapIndex, { force: true }).catch(() => {});
285
+ if (quarantine) await discardQuarantine(quarantine.dir);
286
+ };
221
287
 
222
288
  try {
223
- if (headExists) {
224
- const readTree = await runGit(cwd, ['--git-dir', gitDir, 'read-tree', 'HEAD'], snapEnv);
225
- if (readTree.code !== 0) {
226
- console.error(`[arco] gitSnapshots read-tree failed: ${readTree.stderr.trim()}`);
227
- return null;
228
- }
289
+ if (headExists && !(await seedFromHead(cwd, gitDir, snapEnv, signal))) {
290
+ console.error('[arco] gitSnapshots read-tree failed');
291
+ return null;
229
292
  }
230
- // Stage the whole working tree into the SEPARATE index (never the user's).
231
- const add = await runGit(cwd, ['--git-dir', gitDir, 'add', '-A', '--', ':/', ...protectedPaths.map(p => `:(top,exclude,literal)${p}`)], snapEnv);
232
- if (add.code !== 0) {
233
- console.error(`[arco] gitSnapshots add -A failed: ${add.stderr.trim()}`);
293
+ // Scope before staging: nothing is hashed until large inputs are known.
294
+ const scope = await scanGitScope(cwd, gitDir, root, snapEnv, protectedPaths, signal);
295
+ if (!scope) return null;
296
+ if (exceedsTotalCap(scope)) {
297
+ args.onSkipped?.(CHECKPOINT_SKIP_NOTICE);
298
+ console.error(`[arco] [${workflowId.slice(0, 8)}] gitSnapshots: snapshot skipped — new or changed files exceed the included-total cap (ARCO_CHECKPOINT_TOTAL_CAP_BYTES)`);
234
299
  return null;
235
300
  }
236
- if (protectedPaths.length) {
237
- const drop = await runGit(cwd, ['--git-dir', gitDir, 'rm', '--cached', '-r', '-q', '--ignore-unmatch', '--', ...protectedPaths.map(p => `:(top,literal)${p}`)], snapEnv);
238
- if (drop.code !== 0) return null;
301
+ const skipped = scope.largePaths;
302
+ quarantine = await openQuarantine(cwd, gitDir, signal);
303
+ if (!quarantine) return null;
304
+ const workEnv: NodeJS.ProcessEnv = { ...snapEnv, ...quarantine.env };
305
+ // Stage the measured paths into the SEPARATE index (never the user's).
306
+ const staged = await stageGitScope(cwd, gitDir, root, workEnv, {
307
+ staged: scope.stagePaths,
308
+ removed: scope.removedPaths,
309
+ dropped: [...protectedPaths, ...skipped],
310
+ pinned: [],
311
+ }, signal);
312
+ if (!staged) return null;
313
+ // A measured file can still grow between the scan and staging; the
314
+ // staged blobs are checked against the same caps before anything is kept.
315
+ if (!(await stagedWithinCaps(cwd, gitDir, workEnv, staged, scope.stagePaths, signal))) {
316
+ console.error(`[arco] [${workflowId.slice(0, 8)}] gitSnapshots: files grew past the checkpoint caps while being captured`);
317
+ return null;
239
318
  }
240
- const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], snapEnv);
319
+ const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], workEnv, GIT_TIMEOUT_MS, signal);
241
320
  if (writeTree.code !== 0) {
242
321
  console.error(`[arco] gitSnapshots write-tree failed: ${writeTree.stderr.trim()}`);
243
322
  return null;
@@ -249,7 +328,7 @@ async function createGitCheckpoint(
249
328
  // chain off the user's history. Identity is fixed so we don't depend on
250
329
  // (or pollute) the user's git config. Message carries the label + seq.
251
330
  const commitEnv: NodeJS.ProcessEnv = {
252
- ...snapEnv,
331
+ ...workEnv,
253
332
  GIT_AUTHOR_NAME: 'arco-checkpoint',
254
333
  GIT_AUTHOR_EMAIL: 'checkpoint@arco.local',
255
334
  GIT_COMMITTER_NAME: 'arco-checkpoint',
@@ -259,6 +338,8 @@ async function createGitCheckpoint(
259
338
  cwd,
260
339
  ['--git-dir', gitDir, 'commit-tree', tree, '-m', `arco checkpoint: ${label} (seq ${seq})`],
261
340
  commitEnv,
341
+ GIT_TIMEOUT_MS,
342
+ signal,
262
343
  );
263
344
  if (commit.code !== 0) {
264
345
  console.error(`[arco] gitSnapshots commit-tree failed: ${commit.stderr.trim()}`);
@@ -266,21 +347,41 @@ async function createGitCheckpoint(
266
347
  }
267
348
  const sha = commit.stdout.trim();
268
349
  if (!sha) return null;
350
+ const fileCount = await countTreeFiles(cwd, gitDir, tree, workEnv);
351
+ // Objects reach the real store only once the whole capture succeeded,
352
+ // and a cancelled capture publishes nothing.
353
+ if (signal?.aborted) return null;
354
+ if (!(await migrateQuarantine(quarantine, signal))) {
355
+ console.error('[arco] gitSnapshots: could not move checkpoint objects into the object store');
356
+ return null;
357
+ }
269
358
 
270
359
  const ref = refFor(workflowId, seq);
271
- const update = await runGit(cwd, ['--git-dir', gitDir, 'update-ref', ref, sha]);
272
- if (update.code !== 0) {
273
- console.error(`[arco] gitSnapshots update-ref failed: ${update.stderr.trim()}`);
360
+ const metadataRoot = checkpointStoreRoot(cwd);
361
+ if (skipped.length) await writeSkippedManifest(cwd, workflowId, seq, skipped);
362
+ else await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => {});
363
+ if (!(await publishRef(cwd, gitDir, ref, sha, signal))) {
364
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => {});
274
365
  return null;
275
366
  }
367
+ // Finish every await before the last cancellation check. If the deadline
368
+ // passed meanwhile, withdraw the ref so a turn that missed its cutoff has
369
+ // no undo point. After the check nothing awaits until the result reaches
370
+ // the caller, and pruning starts only for a kept checkpoint, so a
371
+ // discarded attempt never removes an older usable one.
372
+ await cleanup();
373
+ if (signal?.aborted) {
374
+ await withdrawRef(cwd, gitDir, ref, sha);
375
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => {});
376
+ return null;
377
+ }
378
+ void pruneOldCheckpoints(cwd, gitDir, workflowId, metadataRoot).catch(() => {});
276
379
 
277
- const fileCount = await countTreeFiles(cwd, gitDir, tree);
278
- await pruneOldCheckpoints(cwd, gitDir, workflowId).catch(() => {});
279
-
280
- return { ref, fileCount, ts, backend: 'git', label };
380
+ return { ref, fileCount, ts, backend: 'git', label, ...(skipped.length ? { skippedLargeFiles: skipped.length } : {}) };
281
381
  } finally {
282
- // Clean up the separate index; harmless if it's already gone.
283
- await fs.rm(snapIndex, { force: true }).catch(() => {});
382
+ // Clean up the separate index and quarantine unless already done. A kept
383
+ // checkpoint has cleaned up before its last check, so no await runs here.
384
+ if (!cleaned) await cleanup();
284
385
  }
285
386
  }
286
387
 
@@ -308,7 +409,8 @@ async function createGitCheckpoint(
308
409
  // bytes backstops pathological many-small-file trees; over it the snapshot is
309
410
  // skipped entirely (null = "no checkpoint this turn"). Overrides:
310
411
  // ARCO_CHECKPOINT_FILE_CAP_BYTES / ARCO_CHECKPOINT_TOTAL_CAP_BYTES
311
- // (0 disables either). Caps apply only to this fallback, never to real repos.
412
+ // (0 disables either). Git-backed checkpoints apply the same caps before
413
+ // staging; see the Git-backed scope section below.
312
414
  const DEFAULT_FILE_CAP_BYTES = 32 * 1024 * 1024; // 32 MiB per file
313
415
  const DEFAULT_TOTAL_CAP_BYTES = 1024 * 1024 * 1024; // 1 GiB included total
314
416
  // `git add` re-hashes every listed file (the object store dedupes writes, not
@@ -343,6 +445,290 @@ function shadowGitDir(cwd: string): string {
343
445
  return path.join(checkpointStoreRoot(cwd), 'git');
344
446
  }
345
447
 
448
+ // ── Operation-owned object quarantine ──
449
+ //
450
+ // Every checkpoint operation writes its new Git objects into its own
451
+ // directory under the store's objects folder (`arco-incoming-*`), with the
452
+ // real object store as an alternate so existing objects still dedupe. A
453
+ // successful capture moves its finished objects into the real store before
454
+ // its ref is published; a failed, timed-out or cancelled capture removes only
455
+ // its own directory. Restore comparisons always discard theirs. Interrupted
456
+ // staging therefore cannot leave temporary packs or loose objects in the
457
+ // project, and nothing pre-existing in the store is ever deleted. Git refuses
458
+ // ref updates while GIT_QUARANTINE_PATH is set, so a ref can never point at
459
+ // objects that are about to be discarded. A directory left behind by a
460
+ // crashed server is never swept automatically: its age and name alone do not
461
+ // prove that no other process still owns it.
462
+ const QUARANTINE_PREFIX = 'arco-incoming-';
463
+
464
+ interface ObjectQuarantine {
465
+ dir: string;
466
+ objects: string;
467
+ env: NodeJS.ProcessEnv;
468
+ }
469
+
470
+ async function openQuarantine(cwd: string, gitDir: string, signal?: AbortSignal): Promise<ObjectQuarantine | null> {
471
+ const located = await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--git-path', 'objects'], undefined, GIT_TIMEOUT_MS, signal);
472
+ if (located.code !== 0 || !located.stdout.trim()) return null;
473
+ const objects = path.resolve(cwd, located.stdout.trim());
474
+ const dir = await fs.mkdtemp(path.join(objects, QUARANTINE_PREFIX)).catch(() => null);
475
+ if (!dir) return null;
476
+ return { dir, objects, env: { GIT_OBJECT_DIRECTORY: dir, GIT_ALTERNATE_OBJECT_DIRECTORIES: objects, GIT_QUARANTINE_PATH: dir } };
477
+ }
478
+
479
+ async function discardQuarantine(dir: string): Promise<void> {
480
+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => {});
481
+ }
482
+
483
+ // Make one finished object file visible in the real store under its final
484
+ // name in a single step. A hard link does that directly. Where links are not
485
+ // available the bytes are first copied to a temporary name that Git itself
486
+ // treats as garbage (`tmp_obj_*`), then renamed, so no reader can see a
487
+ // partly written object. An object that already exists is identical by
488
+ // content address and is left alone.
489
+ async function placeObject(src: string, dst: string): Promise<'placed' | 'existed' | 'failed'> {
490
+ try {
491
+ await fs.link(src, dst);
492
+ return 'placed';
493
+ } catch (err) {
494
+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') return 'existed';
495
+ }
496
+ const staged = path.join(path.dirname(dst), `tmp_obj_arco_${process.pid}_${randomUUID()}`);
497
+ try {
498
+ await fs.copyFile(src, staged, fs.constants.COPYFILE_EXCL);
499
+ try {
500
+ await fs.link(staged, dst);
501
+ return 'placed';
502
+ } catch (err) {
503
+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') return 'existed';
504
+ await fs.rename(staged, dst);
505
+ return 'placed';
506
+ }
507
+ } catch {
508
+ return 'failed';
509
+ } finally {
510
+ await fs.rm(staged, { force: true }).catch(() => {});
511
+ }
512
+ }
513
+
514
+ // Move completed objects into the real store, never Git's own incomplete
515
+ // temporary files. Nothing placed under a final name is ever removed again,
516
+ // even when a later step fails: another operation may already have found the
517
+ // object or pack and published a ref that needs it. Pack data goes before its
518
+ // index, so a pack only becomes usable once complete. A failure can therefore
519
+ // leave unreferenced loose objects, or pack data without its index, which
520
+ // ordinary `git gc` handles or which stay as bounded garbage. Cancellation is
521
+ // checked between objects, so a cancelled capture stops moving promptly.
522
+ async function migrateQuarantine(q: ObjectQuarantine, signal?: AbortSignal): Promise<boolean> {
523
+ try {
524
+ for (const name of await fs.readdir(q.dir)) {
525
+ if (!/^[0-9a-f]{2}$/.test(name)) continue;
526
+ const files = (await fs.readdir(path.join(q.dir, name))).filter(file => /^[0-9a-f]{38,62}$/.test(file));
527
+ if (!files.length) continue;
528
+ await fs.mkdir(path.join(q.objects, name), { recursive: true });
529
+ for (const file of files) {
530
+ if (signal?.aborted) return false;
531
+ if (await placeObject(path.join(q.dir, name, file), path.join(q.objects, name, file)) === 'failed') return false;
532
+ }
533
+ }
534
+ const packDir = path.join(q.dir, 'pack');
535
+ const indexes = (await fs.readdir(packDir).catch(() => [] as string[])).filter(name => /^pack-[0-9a-f]+\.idx$/.test(name));
536
+ if (indexes.length) await fs.mkdir(path.join(q.objects, 'pack'), { recursive: true });
537
+ for (const index of indexes) {
538
+ const base = index.slice(0, -'.idx'.length);
539
+ for (const name of [`${base}.pack`, `${base}.rev`, `${base}.bitmap`, index]) {
540
+ if (signal?.aborted) return false;
541
+ const src = path.join(packDir, name);
542
+ if (!name.endsWith('.idx') && !(await fs.access(src).then(() => true, () => false))) continue;
543
+ if (await placeObject(src, path.join(q.objects, 'pack', name)) === 'failed') return false;
544
+ }
545
+ }
546
+ return true;
547
+ } catch {
548
+ return false;
549
+ }
550
+ }
551
+
552
+ // ── Git-backed scope ──
553
+ //
554
+ // The scratch index starts from the HEAD tree but borrows the stat data of
555
+ // the user's own index for entries that match HEAD (`read-tree -m`), so Git
556
+ // can tell unchanged files apart without reading them. Only paths that may
557
+ // differ from HEAD and untracked, non-ignored files are then measured. Large
558
+ // changed or untracked files are left out of the checkpoint, recorded in the
559
+ // skipped-path manifest, and preserved by undo; an unchanged committed large
560
+ // file keeps its committed entry without being read. The remaining new or
561
+ // modified bytes are bounded by the included-total cap: over it, the
562
+ // checkpoint is skipped instead of copying them. Unchanged committed data is
563
+ // never charged against that cap.
564
+ interface GitScope {
565
+ largePaths: string[];
566
+ // The measured in-scope paths that may differ from the seed. Only these are
567
+ // staged, so a file appearing after the scan is never admitted unmeasured.
568
+ stagePaths: string[];
569
+ // Tracked paths that no longer hold a file or link; recorded as deletions.
570
+ removedPaths: string[];
571
+ eligibleBytes: number;
572
+ }
573
+
574
+ async function seedFromHead(cwd: string, gitDir: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<boolean> {
575
+ const index = env.GIT_INDEX_FILE!;
576
+ const userIndex = path.join(gitDir, 'index');
577
+ // Read-only use of the user's index: copy it, keep its timestamp so Git's
578
+ // racy-clean detection still applies, and merge HEAD into the copy.
579
+ const st = await fs.stat(userIndex).catch(() => null);
580
+ if (st) {
581
+ const copied = await fs.copyFile(userIndex, index).then(() => fs.utimes(index, st.atime, st.mtime)).then(() => true, () => false);
582
+ if (copied && (await runGit(cwd, ['--git-dir', gitDir, 'read-tree', '-m', 'HEAD'], env, GIT_TIMEOUT_MS, signal)).code === 0) return true;
583
+ await fs.rm(index, { force: true }).catch(() => {});
584
+ }
585
+ return (await runGit(cwd, ['--git-dir', gitDir, 'read-tree', 'HEAD'], env, GIT_TIMEOUT_MS, signal)).code === 0;
586
+ }
587
+
588
+ function gitPathList(stdout: string, protectedPaths: string[]): string[] {
589
+ return stdout.split('\0').filter(item => item && !item.endsWith('/') && !protectedPaths.some(folder => pathsOverlap(item, folder)));
590
+ }
591
+
592
+ async function scanGitScope(cwd: string, gitDir: string, root: string, env: NodeJS.ProcessEnv, protectedPaths: string[], signal?: AbortSignal): Promise<GitScope | null> {
593
+ const fileCap = fileCapBytes();
594
+ // Paths whose working file may differ from the seeded entry. Entries without
595
+ // borrowed stat data are listed too, so this errs toward measuring more.
596
+ const changed = await runGit(cwd, ['--git-dir', gitDir, 'diff-files', '--name-only', '-z', '--no-renames', '--', ':/'], env, GIT_TIMEOUT_MS, signal);
597
+ const untracked = await runGit(cwd, ['--git-dir', gitDir, 'ls-files', '-z', '--full-name', '--others', '--exclude-standard', '--', ':/'], env, GIT_TIMEOUT_MS, signal);
598
+ const seeded = await indexEntries(cwd, gitDir, env, signal);
599
+ if (changed.code !== 0 || untracked.code !== 0 || !seeded) return null;
600
+ const largePaths: string[] = [];
601
+ const stagePaths: string[] = [];
602
+ const removedPaths: string[] = [];
603
+ let eligibleBytes = 0;
604
+ const candidates = [...new Set([...gitPathList(changed.stdout, protectedPaths), ...gitPathList(untracked.stdout, protectedPaths)])];
605
+ for (let i = 0; i < candidates.length; i += 128) {
606
+ if (signal?.aborted) return null;
607
+ await Promise.all(candidates.slice(i, i + 128).map(async (rel) => {
608
+ const st = await fs.lstat(path.join(root, rel)).catch(() => null);
609
+ const entry = seeded.get(rel);
610
+ if (st?.isFile()) {
611
+ if (fileCap > 0 && st.size > fileCap) largePaths.push(rel);
612
+ else { eligibleBytes += st.size; stagePaths.push(rel); }
613
+ } else if (st?.isSymbolicLink() || (st?.isDirectory() && entry?.mode === '160000')) {
614
+ // Links and submodule commits are recorded without reading contents.
615
+ stagePaths.push(rel);
616
+ } else if (entry) {
617
+ // A tracked path that is gone, or is now a folder or special file, is
618
+ // recorded as a deletion without staging anything below it. Files in
619
+ // a folder that replaced it are listed and measured on their own.
620
+ removedPaths.push(rel);
621
+ }
622
+ }));
623
+ }
624
+ return { largePaths: largePaths.sort(), stagePaths: stagePaths.sort(), removedPaths: removedPaths.sort(), eligibleBytes };
625
+ }
626
+
627
+ // Stage-0 entries of a scratch index: path -> mode and blob id.
628
+ async function indexEntries(cwd: string, gitDir: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<Map<string, { mode: string; sha: string }> | null> {
629
+ const listed = await runGit(cwd, ['--git-dir', gitDir, 'ls-files', '-s', '-z', '--full-name', '--', ':/'], env, GIT_TIMEOUT_MS, signal);
630
+ if (listed.code !== 0) return null;
631
+ const entries = new Map<string, { mode: string; sha: string }>();
632
+ for (const line of listed.stdout.split('\0')) {
633
+ const match = /^(\d+) ([0-9a-f]+) (\d)\t(.+)$/s.exec(line);
634
+ if (match) entries.set(match[4], { mode: match[1], sha: match[2] });
635
+ }
636
+ return entries;
637
+ }
638
+
639
+ function exceedsTotalCap(scope: GitScope): boolean {
640
+ const cap = totalCapBytes();
641
+ return cap > 0 && scope.eligibleBytes > cap;
642
+ }
643
+
644
+ // Blob id and mode for each path of a tree, so a large file can be compared
645
+ // with what the tree records without hashing it into the store.
646
+ async function treeBlobs(cwd: string, gitDir: string, treeish: string): Promise<Map<string, { mode: string; sha: string }> | null> {
647
+ const out = await runGit(cwd, ['--git-dir', gitDir, 'ls-tree', '-r', '-z', '--full-tree', treeish]);
648
+ if (out.code !== 0) return null;
649
+ const blobs = new Map<string, { mode: string; sha: string }>();
650
+ for (const line of out.stdout.split('\0')) {
651
+ const match = /^(\d+) blob ([0-9a-f]+)\t(.+)$/s.exec(line);
652
+ if (match) blobs.set(match[3], { mode: match[1], sha: match[2] });
653
+ }
654
+ return blobs;
655
+ }
656
+
657
+ // Git resolves index and pathname arguments against the invocation prefix.
658
+ function fromCwd(cwd: string, root: string, rel: string): string {
659
+ return path.relative(cwd, path.join(root, rel)).split(path.sep).join('/') || '.';
660
+ }
661
+
662
+ // Hash without -w: reads the file through the path's filters, writes nothing.
663
+ async function matchesBlob(cwd: string, gitDir: string, root: string, rel: string, sha: string): Promise<boolean> {
664
+ const local = fromCwd(cwd, root, rel);
665
+ const out = await runGit(cwd, ['--git-dir', gitDir, 'hash-object', `--path=${local}`, '--', local], undefined, STAGE_TIMEOUT_MS);
666
+ return out.code === 0 && out.stdout.trim() === sha;
667
+ }
668
+
669
+ async function withPathspecFile<T>(specs: string[], fn: (file: string) => Promise<T>): Promise<T> {
670
+ const file = path.join(tmpdir(), `arco-pathspec-${process.pid}-${randomUUID()}.txt`);
671
+ await fs.writeFile(file, specs.join('\0') + '\0');
672
+ try { return await fn(file); }
673
+ finally { await fs.rm(file, { force: true }).catch(() => {}); }
674
+ }
675
+
676
+ interface GitStagePlan {
677
+ // The measured paths to stage; every other seeded entry stays as it is.
678
+ staged: string[];
679
+ // Seeded entries recorded as deletions before anything is staged.
680
+ removed: string[];
681
+ // Removed from the scratch index after staging.
682
+ dropped: string[];
683
+ // Recorded with an existing blob id instead of hashing the file again.
684
+ pinned: { path: string; mode: string; sha: string }[];
685
+ }
686
+
687
+ // Stage the working tree into a scratch index without hashing out-of-scope
688
+ // large files.
689
+ async function stageGitScope(cwd: string, gitDir: string, root: string, env: NodeJS.ProcessEnv, plan: GitStagePlan, signal?: AbortSignal): Promise<Map<string, { mode: string; sha: string }> | null> {
690
+ // Plain arguments in small batches: `git rm --pathspec-from-file` is
691
+ // refused when Git adds the invocation prefix of a subdirectory work tree.
692
+ const unstage = async (paths: string[], recursive: boolean): Promise<boolean> => {
693
+ for (let i = 0; i < paths.length; i += 200) {
694
+ const drop = await runGit(cwd, ['--git-dir', gitDir, 'rm', '--cached', ...(recursive ? ['-r'] : []), '-q', '--ignore-unmatch', '--',
695
+ ...paths.slice(i, i + 200).map(p => `:(top,literal)${p}`)], env, GIT_TIMEOUT_MS, signal);
696
+ if (drop.code !== 0) { console.error(`[arco] gitSnapshots rm --cached failed: ${drop.stderr.trim()}`); return false; }
697
+ }
698
+ return true;
699
+ };
700
+ if (!(await unstage(plan.removed, false))) return null;
701
+ const before = await indexEntries(cwd, gitDir, env, signal);
702
+ if (!before) return null;
703
+ // A measured path that disappears before staging fails the capture; the
704
+ // next turn captures again.
705
+ const add = plan.staged.length ? await withPathspecFile(plan.staged.map(p => `:(top,literal)${p}`), file =>
706
+ runGit(cwd, ['--git-dir', gitDir, 'add', '-A', '--pathspec-from-file', file, '--pathspec-file-nul'], env, GIT_TIMEOUT_MS, signal)) : { code: 0, stderr: '' };
707
+ if (add.code !== 0) {
708
+ console.error(`[arco] gitSnapshots add -A failed: ${add.stderr.trim()}`);
709
+ return null;
710
+ }
711
+ if (!(await unstage(plan.dropped, true))) return null;
712
+ for (const pin of plan.pinned) {
713
+ const set = await runGit(cwd, ['--git-dir', gitDir, 'update-index', '--add', '--cacheinfo', `${pin.mode},${pin.sha},${fromCwd(cwd, root, pin.path)}`], env);
714
+ if (set.code !== 0) return null;
715
+ }
716
+ // A measured file replaced by a folder before staging would make `add`
717
+ // record the folder's contents unmeasured. Any entry that was neither
718
+ // seeded nor measured fails the whole operation, and its objects are
719
+ // discarded with the quarantine.
720
+ const after = await indexEntries(cwd, gitDir, env, signal);
721
+ if (!after) return null;
722
+ const expected = new Set([...plan.staged, ...plan.pinned.map(pin => pin.path)]);
723
+ for (const file of after.keys()) {
724
+ if (!before.has(file) && !expected.has(file)) {
725
+ console.error('[arco] gitSnapshots: an unmeasured path appeared during staging');
726
+ return null;
727
+ }
728
+ }
729
+ return after;
730
+ }
731
+
346
732
  interface SnapshotWalk {
347
733
  // cwd-relative POSIX paths a snapshot covers, sorted for determinism.
348
734
  files: string[];
@@ -363,6 +749,7 @@ async function collectSnapshotFiles(
363
749
  root: string,
364
750
  fileCap: number,
365
751
  totalCap: number,
752
+ signal?: AbortSignal,
366
753
  ): Promise<SnapshotWalk> {
367
754
  const files: string[] = [];
368
755
  const protectedPaths = await providerHomePaths(root);
@@ -374,7 +761,7 @@ async function collectSnapshotFiles(
374
761
  let remaining = Math.max(1, Math.floor(scanLimit('ARCO_CHECKPOINT_SCAN_ENTRIES', 20_000)));
375
762
  const deadline = performance.now() + scanLimit('ARCO_CHECKPOINT_SCAN_MS', 5000);
376
763
  while (stack.length > 0) {
377
- if (remaining <= 0 || performance.now() >= deadline) return { files, skippedLargePaths, exceededTotal: false, exceededScan: true };
764
+ if (remaining <= 0 || performance.now() >= deadline || signal?.aborted) return { files, skippedLargePaths, exceededTotal: false, exceededScan: true };
378
765
  await setImmediate();
379
766
  const rel = stack.pop()!;
380
767
  const abs = rel ? path.join(root, rel) : root;
@@ -454,6 +841,8 @@ async function stagePathspecs(
454
841
  gitDir: string,
455
842
  indexFile: string,
456
843
  files: string[],
844
+ extraEnv: NodeJS.ProcessEnv = {},
845
+ signal?: AbortSignal,
457
846
  ): Promise<boolean> {
458
847
  if (files.length === 0) return true; // empty tree is a valid snapshot
459
848
  const pathspecFile = path.join(gitDir, `pathspec-${process.pid}-${randomUUID()}.tmp`);
@@ -469,9 +858,18 @@ async function stagePathspecs(
469
858
  cwd,
470
859
  timeout: STAGE_TIMEOUT_MS,
471
860
  maxBuffer: GIT_MAX_BUFFER,
472
- env: { ...process.env, GIT_INDEX_FILE: indexFile },
861
+ env: { ...process.env, ...extraEnv, GIT_INDEX_FILE: indexFile },
862
+ ...(signal ? { signal } : {}),
473
863
  },
474
864
  );
865
+ // A listed file replaced by a folder before staging would bring the
866
+ // folder's contents in unwalked; such a staging fails as a whole.
867
+ const listed = await runGit(cwd, ['--git-dir', gitDir, '--work-tree', cwd, 'ls-files', '-z', '--full-name'], { ...extraEnv, GIT_INDEX_FILE: indexFile }, GIT_TIMEOUT_MS, signal);
868
+ const walked = new Set(files);
869
+ if (listed.code !== 0 || listed.stdout.split('\0').some(file => file && !walked.has(file))) {
870
+ console.error('[arco] gitSnapshots shadow staging failed: an unwalked path appeared during staging');
871
+ return false;
872
+ }
475
873
  return true;
476
874
  } catch (err) {
477
875
  console.error(`[arco] gitSnapshots shadow staging failed: ${(err as Error).message}`);
@@ -559,7 +957,9 @@ async function createShadowGitCheckpoint(args: CreateCheckpointArgs): Promise<Ch
559
957
  const label = args.label ?? `before turn ${seq}`;
560
958
  const ts = Date.now();
561
959
 
562
- const walk = await collectSnapshotFiles(cwd, fileCapBytes(), totalCapBytes());
960
+ const signal = args.signal;
961
+ const walk = await collectSnapshotFiles(cwd, fileCapBytes(), totalCapBytes(), signal);
962
+ if (signal?.aborted) return null;
563
963
  if (walk.exceededTotal || walk.exceededScan) {
564
964
  args.onSkipped?.(CHECKPOINT_SKIP_NOTICE);
565
965
  console.error(
@@ -576,11 +976,19 @@ async function createShadowGitCheckpoint(args: CreateCheckpointArgs): Promise<Ch
576
976
  // here (unlike the revert path) because snapshotting never runs `-u`.
577
977
  // Per-operation naming prevents same-cwd workflows from sharing a lock.
578
978
  const snapIndex = path.join(gitDir, `snap-${process.pid}-${randomUUID()}.index`);
579
- const env: NodeJS.ProcessEnv = { GIT_INDEX_FILE: snapIndex };
979
+ const quarantine = await openQuarantine(cwd, gitDir, signal);
980
+ if (!quarantine) return null;
981
+ const env: NodeJS.ProcessEnv = { GIT_INDEX_FILE: snapIndex, ...quarantine.env };
982
+ let cleaned = false;
983
+ const cleanup = async () => {
984
+ cleaned = true;
985
+ await fs.rm(snapIndex, { force: true }).catch(() => {});
986
+ await discardQuarantine(quarantine.dir);
987
+ };
580
988
  try {
581
- if (!(await stagePathspecs(cwd, gitDir, snapIndex, walk.files))) return null;
989
+ if (!(await stagePathspecs(cwd, gitDir, snapIndex, walk.files, quarantine.env, signal))) return null;
582
990
 
583
- const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], env);
991
+ const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], env, GIT_TIMEOUT_MS, signal);
584
992
  if (writeTree.code !== 0) {
585
993
  console.error(`[arco] gitSnapshots shadow write-tree failed: ${writeTree.stderr.trim()}`);
586
994
  return null;
@@ -599,6 +1007,8 @@ async function createShadowGitCheckpoint(args: CreateCheckpointArgs): Promise<Ch
599
1007
  cwd,
600
1008
  ['--git-dir', gitDir, 'commit-tree', tree, '-m', `arco checkpoint: ${label} (seq ${seq})`],
601
1009
  commitEnv,
1010
+ GIT_TIMEOUT_MS,
1011
+ signal,
602
1012
  );
603
1013
  if (commit.code !== 0) {
604
1014
  console.error(`[arco] gitSnapshots shadow commit-tree failed: ${commit.stderr.trim()}`);
@@ -606,23 +1016,36 @@ async function createShadowGitCheckpoint(args: CreateCheckpointArgs): Promise<Ch
606
1016
  }
607
1017
  const sha = commit.stdout.trim();
608
1018
  if (!sha) return null;
1019
+ const fileCount = await countTreeFiles(cwd, gitDir, tree, env);
1020
+ if (signal?.aborted) return null;
1021
+ if (!(await migrateQuarantine(quarantine, signal))) {
1022
+ console.error('[arco] gitSnapshots: could not move shadow checkpoint objects into its object store');
1023
+ return null;
1024
+ }
609
1025
 
610
1026
  const ref = refFor(workflowId, seq);
611
1027
  await writeSkippedManifest(cwd, workflowId, seq, [...walk.skippedLargePaths, ...(walk.skippedNestedPaths ?? [])], walk.skippedNestedPaths ?? []);
612
- const update = await runGit(cwd, ['--git-dir', gitDir, 'update-ref', ref, sha]);
613
- if (update.code !== 0) {
1028
+ if (!(await publishRef(cwd, gitDir, ref, sha, signal))) {
614
1029
  await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => {});
615
- console.error(`[arco] gitSnapshots shadow update-ref failed: ${update.stderr.trim()}`);
616
1030
  return null;
617
1031
  }
618
1032
 
619
- await pruneOldCheckpoints(cwd, gitDir, workflowId, checkpointStoreRoot(cwd)).catch(() => {});
620
- // Best-effort repack so pruned checkpoints' objects don't pile up loose.
621
- await runGit(cwd, ['--git-dir', gitDir, 'gc', '--auto', '-q']).catch(() => {});
1033
+ // Same contract as the Git-backed capture: every await finishes before
1034
+ // the last cancellation check, and pruning starts only once kept.
1035
+ await cleanup();
1036
+ if (signal?.aborted) {
1037
+ await withdrawRef(cwd, gitDir, ref, sha);
1038
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => {});
1039
+ return null;
1040
+ }
1041
+ // Best-effort repack afterwards so pruned checkpoints' objects don't pile up loose.
1042
+ void pruneOldCheckpoints(cwd, gitDir, workflowId, checkpointStoreRoot(cwd))
1043
+ .then(() => runGit(cwd, ['--git-dir', gitDir, 'gc', '--auto', '-q']))
1044
+ .catch(() => {});
622
1045
 
623
1046
  return {
624
1047
  ref,
625
- fileCount: await countTreeFiles(cwd, gitDir, tree),
1048
+ fileCount,
626
1049
  ts,
627
1050
  backend: 'shadow-git',
628
1051
  label,
@@ -630,7 +1053,7 @@ async function createShadowGitCheckpoint(args: CreateCheckpointArgs): Promise<Ch
630
1053
  ...(walk.skippedLargePaths.length > 0 ? { skippedLargeFiles: walk.skippedLargePaths.length } : {}),
631
1054
  };
632
1055
  } finally {
633
- await fs.rm(snapIndex, { force: true }).catch(() => {});
1056
+ if (!cleaned) await cleanup();
634
1057
  }
635
1058
  }
636
1059
 
@@ -750,9 +1173,16 @@ interface PreparedRestore {
750
1173
  tree: string;
751
1174
  env: NodeJS.ProcessEnv;
752
1175
  index: string;
1176
+ // Objects written while comparing or seeding are never kept.
1177
+ quarantine: string;
753
1178
  limitation?: string;
754
1179
  }
755
1180
 
1181
+ async function releasePrepared(p: { index: string; quarantine?: string }): Promise<void> {
1182
+ await fs.rm(p.index, { force: true }).catch(() => {});
1183
+ if (p.quarantine) await discardQuarantine(p.quarantine);
1184
+ }
1185
+
756
1186
  type PrepareOutcome = PreparedRestore | { problem: 'missing' | 'legacy' | 'failed' | 'too-large' | 'capped-overlap' | 'nested-overlap' | 'legacy-overlap' | 'provider-overlap'; limitation?: string };
757
1187
 
758
1188
  function scratchIndex(cwd: string, workflowId: string, seq: number): string {
@@ -773,8 +1203,16 @@ async function prepareGitRestore(cwd: string, gitDir: string, workflowId: string
773
1203
  const root = await gitCheckpointWorkTree(cwd, gitDir);
774
1204
  if (await protectedTree(cwd, gitDir, tree, root)) return { problem: 'provider-overlap' };
775
1205
  const protectedPaths = await providerHomePaths(root);
1206
+ // Paths left out when the target was captured stay out of the seed, so the
1207
+ // restore neither deletes nor rewrites them. Checkpoints without a manifest
1208
+ // recorded everything.
1209
+ const targetSkipped = await readSkippedManifest(cwd, workflowId, seq);
1210
+ if (!targetSkipped) {
1211
+ console.error('[arco] gitSnapshots revert aborted: skipped-path manifest is unreadable');
1212
+ return { problem: 'failed' };
1213
+ }
776
1214
  const index = scratchIndex(cwd, workflowId, seq);
777
- const env: NodeJS.ProcessEnv = { GIT_INDEX_FILE: index };
1215
+ const seedEnv: NodeJS.ProcessEnv = { GIT_INDEX_FILE: index };
778
1216
  await fs.rm(index, { force: true }).catch(() => {});
779
1217
  // Seed the scratch index from the LIVE working tree so every currently
780
1218
  // present file (tracked + untracked) is registered there. `read-tree -u
@@ -786,42 +1224,58 @@ async function prepareGitRestore(cwd: string, gitDir: string, workflowId: string
786
1224
  // seed so a revert never sweeps them even if a project failed to gitignore
787
1225
  // .arco. Checkpoint trees normally don't contain .arco anyway (it's
788
1226
  // gitignored in a project cwd), so the target tree won't re-create it.
789
- const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'], env)).code === 0;
790
- if (headExists) {
791
- const rt = await runGit(cwd, ['--git-dir', gitDir, 'read-tree', 'HEAD'], env);
792
- if (rt.code !== 0) {
793
- console.error(`[arco] gitSnapshots revert seed read-tree failed: ${rt.stderr.trim()}`);
794
- await fs.rm(index, { force: true }).catch(() => {});
795
- return { problem: 'failed' };
1227
+ const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'], seedEnv)).code === 0;
1228
+ if (headExists && !(await seedFromHead(cwd, gitDir, seedEnv))) {
1229
+ console.error('[arco] gitSnapshots revert seed read-tree failed');
1230
+ await releasePrepared({ index });
1231
+ return { problem: 'failed' };
1232
+ }
1233
+ const scope = await scanGitScope(cwd, gitDir, root, seedEnv, protectedPaths);
1234
+ if (!scope) { await releasePrepared({ index }); return { problem: 'failed' }; }
1235
+ if (exceedsTotalCap(scope)) { await releasePrepared({ index }); return { problem: 'too-large' }; }
1236
+ // A changed or untracked file over the per-file cap is never hashed into the
1237
+ // store. If the target would write that path, its current bytes must already
1238
+ // match the target, because neither the target nor the safety snapshot can
1239
+ // hold them. An unchanged committed large file is held by HEAD and by the
1240
+ // safety snapshot, so the restore may replace it.
1241
+ const target = scope.largePaths.length ? await treeBlobs(cwd, gitDir, tree) : null;
1242
+ if (scope.largePaths.length && !target) { await releasePrepared({ index }); return { problem: 'failed' }; }
1243
+ const pinned: GitStagePlan['pinned'] = [];
1244
+ for (const rel of scope.largePaths) {
1245
+ const blob = target?.get(rel);
1246
+ const overlapping = !blob && target && [...target.keys()].some(file => pathsOverlap(file, rel));
1247
+ if (overlapping || (blob && !(await matchesBlob(cwd, gitDir, root, rel, blob.sha)))) {
1248
+ console.error('[arco] gitSnapshots revert aborted: a file over the per-file cap overlaps the target tree');
1249
+ await releasePrepared({ index });
1250
+ return { problem: 'capped-overlap' };
796
1251
  }
1252
+ if (blob) pinned.push({ path: rel, ...blob });
797
1253
  }
1254
+ const quarantine = await openQuarantine(cwd, gitDir);
1255
+ if (!quarantine) { await releasePrepared({ index }); return { problem: 'failed' }; }
1256
+ const env: NodeJS.ProcessEnv = { ...seedEnv, ...quarantine.env };
798
1257
  // NOTE: this used to be `add -A -- ':!.arco' ':!.git'`, but an
799
1258
  // exclude-only pathspec makes git treat matched-but-IGNORED dirs as
800
1259
  // explicitly requested — with a global `**/.arco/` ignore rule (the operator's
801
1260
  // ~/.config/git/ignore) the add REFUSED (.arco "ignored by one of your
802
1261
  // .gitignore files") and every revert in a repo containing .arco failed
803
- // (found 2026-08-19). Plain `add -A` skips ignored files silently; the
804
- // follow-up `rm --cached` then drops .arco from the seed where a project
805
- // does NOT ignore it. Both must succeed — a seeded .arco would be swept
806
- // from the working tree by `read-tree -u --reset` (it's absent from every
807
- // checkpoint tree).
808
- const add = await runGit(cwd, ['--git-dir', gitDir, 'add', '-A', '--', ':/', ...protectedPaths.map(p => `:(top,exclude,literal)${p}`)], env);
809
- if (add.code !== 0) {
810
- console.error(`[arco] gitSnapshots revert seed add -A failed: ${add.stderr.trim()}`);
811
- await fs.rm(index, { force: true }).catch(() => {});
1262
+ // (found 2026-08-19). Plain `add -A` with a positive `:/` skips ignored files
1263
+ // silently; the dropped `.arco` then leaves the seed where a project does
1264
+ // NOT ignore it. Both must succeed — a seeded .arco would be swept from the
1265
+ // working tree by `read-tree -u --reset` (it's absent from every checkpoint
1266
+ // tree).
1267
+ const outOfScope = [...protectedPaths, ...scope.largePaths, ...targetSkipped.paths];
1268
+ const stateDir = path.relative(root, path.join(await fs.realpath(cwd), '.arco')).split(path.sep).join('/');
1269
+ // Only measured paths enter the seed. A file that appears after the scan is
1270
+ // absent from the seed, so the restore leaves it in place.
1271
+ const inScope = (file: string) => ![stateDir, ...targetSkipped.paths].some(out => pathsOverlap(file, out));
1272
+ const staged = scope.stagePaths.filter(inScope);
1273
+ if (!(await stageGitScope(cwd, gitDir, root, env, { staged, removed: scope.removedPaths.filter(inScope), dropped: [stateDir, ...outOfScope], pinned }))) {
1274
+ console.error('[arco] gitSnapshots revert seed failed');
1275
+ await releasePrepared({ index, quarantine: quarantine.dir });
812
1276
  return { problem: 'failed' };
813
1277
  }
814
- const drop = await runGit(
815
- cwd,
816
- ['--git-dir', gitDir, 'rm', '--cached', '-r', '-q', '--ignore-unmatch', '--', '.arco', ...protectedPaths.map(p => `:(top,literal)${p}`)],
817
- env,
818
- );
819
- if (drop.code !== 0) {
820
- console.error(`[arco] gitSnapshots revert seed .arco drop failed: ${drop.stderr.trim()}`);
821
- await fs.rm(index, { force: true }).catch(() => {});
822
- return { problem: 'failed' };
823
- }
824
- return { gitDir, workTree: [], ref, tree, env, index };
1278
+ return { gitDir, workTree: [], ref, tree, env, index, quarantine: quarantine.dir };
825
1279
  }
826
1280
 
827
1281
  // Shadow store: the scratch index is seeded from the current capped walk plus
@@ -885,11 +1339,13 @@ async function prepareShadowRestore(cwd: string, workflowId: string, seq: number
885
1339
  legacyFolders.size ? `Older checkpoint left unrecorded folders unchanged: ${namedScope([...legacyFolders])}.` : ''].filter(Boolean).join(' ');
886
1340
  const index = scratchIndex(cwd, workflowId, seq);
887
1341
  await fs.rm(index, { force: true }).catch(() => {});
888
- if (!(await stagePathspecs(cwd, gitDir, index, seedFiles))) {
889
- await fs.rm(index, { force: true }).catch(() => {});
1342
+ const quarantine = await openQuarantine(cwd, gitDir);
1343
+ if (!quarantine) return { problem: 'failed' };
1344
+ if (!(await stagePathspecs(cwd, gitDir, index, seedFiles, quarantine.env))) {
1345
+ await releasePrepared({ index, quarantine: quarantine.dir });
890
1346
  return { problem: 'failed' };
891
1347
  }
892
- return { gitDir, workTree: ['--work-tree', cwd], ref, tree, env: { GIT_INDEX_FILE: index }, index, ...(limitation ? { limitation } : {}) };
1348
+ return { gitDir, workTree: ['--work-tree', cwd], ref, tree, env: { GIT_INDEX_FILE: index, ...quarantine.env }, index, quarantine: quarantine.dir, ...(limitation ? { limitation } : {}) };
893
1349
  }
894
1350
 
895
1351
  async function prepareRestore(cwd: string, workflowId: string, seq: number): Promise<PrepareOutcome> {
@@ -898,7 +1354,7 @@ async function prepareRestore(cwd: string, workflowId: string, seq: number): Pro
898
1354
  }
899
1355
 
900
1356
  // The live tree a restore would replace, as a tree object (written into the
901
- // same object store; unreferenced, so ordinary gc reclaims it).
1357
+ // operation's quarantine and discarded with it).
902
1358
  async function liveTree(cwd: string, p: PreparedRestore): Promise<string | null> {
903
1359
  const out = await runGit(cwd, ['--git-dir', p.gitDir, 'write-tree'], p.env);
904
1360
  return out.code === 0 && out.stdout.trim() ? out.stdout.trim() : null;
@@ -907,7 +1363,7 @@ async function liveTree(cwd: string, p: PreparedRestore): Promise<string | null>
907
1363
  async function countRestoreChanges(cwd: string, p: PreparedRestore): Promise<CheckpointRestoreChanges | null> {
908
1364
  const live = await liveTree(cwd, p);
909
1365
  if (!live) return null;
910
- const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff-tree', '-r', '-z', '--no-renames', '--name-status', live, p.tree]);
1366
+ const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff-tree', '-r', '-z', '--no-renames', '--name-status', live, p.tree], p.env);
911
1367
  if (diff.code !== 0) return null;
912
1368
  const parts = diff.stdout.split('\0');
913
1369
  const changes: CheckpointRestoreChanges = { changed: 0, removed: 0, restored: 0, unchanged: 0, paths: [], pathsTruncated: false };
@@ -948,7 +1404,7 @@ export async function previewCheckpointRevert(args: RevertCheckpointArgs): Promi
948
1404
  const changes = await countRestoreChanges(cwd, p);
949
1405
  return changes ? { ok: true, changes, ...(p.limitation ? { limitation: p.limitation } : {}) } : { ok: false, error: PREVIEW_PROBLEMS.failed };
950
1406
  } finally {
951
- await fs.rm(p.index, { force: true }).catch(() => {});
1407
+ await releasePrepared(p);
952
1408
  }
953
1409
  }
954
1410
 
@@ -965,10 +1421,10 @@ export async function diffCheckpointToNow(cwd: string, workflowId: string, seq:
965
1421
  try {
966
1422
  const live = await liveTree(cwd, p);
967
1423
  if (!live) return { problem: 'failed' };
968
- const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff', '--no-ext-diff', '--no-textconv', '--no-color', p.tree, live]);
1424
+ const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff', '--no-ext-diff', '--no-textconv', '--no-color', p.tree, live], p.env);
969
1425
  return diff.code === 0 ? { patch: diff.stdout } : { problem: 'failed' };
970
1426
  } finally {
971
- await fs.rm(p.index, { force: true }).catch(() => {});
1427
+ await releasePrepared(p);
972
1428
  }
973
1429
  }
974
1430
 
@@ -988,7 +1444,7 @@ async function revertPrepared(cwd: string, p: PreparedRestore): Promise<RevertRe
988
1444
  const fileCount = await countTreeFiles(cwd, p.gitDir, p.tree);
989
1445
  return { fileCount, backend: 'git', restoredFrom: p.ref, ...(changes ? { changes } : {}), ...(p.limitation ? { limitation: p.limitation } : {}) };
990
1446
  } finally {
991
- await fs.rm(p.index, { force: true }).catch(() => {});
1447
+ await releasePrepared(p);
992
1448
  }
993
1449
  }
994
1450