arco-workbench 0.2.1 → 0.2.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 (50) hide show
  1. package/CONTRIBUTING.md +26 -24
  2. package/client/dist/assets/{PhosphorBackdrop-BbR3xmfD.js → PhosphorBackdrop-CHXVFLGT.js} +1 -1
  3. package/client/dist/assets/{ThemedBackgroundShaderImpl-UMjbs9ZN.js → ThemedBackgroundShaderImpl-Bhs4I9jA.js} +1 -1
  4. package/client/dist/assets/{XtermView-n135qz-f.js → XtermView-CdfurwFx.js} +1 -1
  5. package/client/dist/assets/{galleryEditor-CFSke4by.js → galleryEditor-DYjZZ4cf.js} +1 -1
  6. package/client/dist/assets/{index-DeoJbjI3.js → index-BjDmFvqG.js} +219 -219
  7. package/client/dist/index.html +1 -1
  8. package/client/dist/manifest-mobile.webmanifest +1 -0
  9. package/client/src/components/Connections/Connections.tsx +3 -3
  10. package/client/src/components/research/QuickResearchOverview.tsx +7 -3
  11. package/client/src/components/research/SavedQuickKeep.tsx +7 -3
  12. package/client/src/help/content/misc.tsx +2 -2
  13. package/client/src/help/content/rightPanel.tsx +3 -2
  14. package/client/src/help/manualSections/clusters.tsx +1 -1
  15. package/client/src/help/manualSections/powerFeatures.tsx +3 -2
  16. package/client/src/layout/layoutRange.ts +10 -0
  17. package/client/src/main.tsx +2 -0
  18. package/docs/CHECKPOINTS.md +67 -3
  19. package/docs/CLIENT.md +1 -1
  20. package/docs/HTTP_API.md +9 -7
  21. package/docs/PROVIDERS.md +1 -1
  22. package/docs/RESEARCH.md +2 -2
  23. package/node_modules/@arco/shared/package.json +1 -1
  24. package/package.json +2 -2
  25. package/server/dist/capabilities.d.ts +6 -0
  26. package/server/dist/capabilities.js +13 -4
  27. package/server/dist/explorerDocs.d.ts +1 -0
  28. package/server/dist/explorerDocs.js +4 -4
  29. package/server/dist/gitSnapshots.d.ts +1 -0
  30. package/server/dist/gitSnapshots.js +547 -83
  31. package/server/dist/http/clusterRoutes.js +9 -3
  32. package/server/dist/http/router.js +1 -0
  33. package/server/dist/providers/codexChatBoundary.js +6 -1
  34. package/server/dist/research/quickPromotion.d.ts +3 -0
  35. package/server/dist/research/quickPromotion.js +26 -9
  36. package/server/dist/research/savedQuickPromotion.js +2 -11
  37. package/server/dist/turnChanges.d.ts +1 -1
  38. package/server/dist/turnChanges.js +5 -4
  39. package/server/dist/ws/turnEngine.js +4 -1
  40. package/server/package.json +1 -1
  41. package/server/src/capabilities.ts +14 -4
  42. package/server/src/explorerDocs.ts +5 -5
  43. package/server/src/gitSnapshots.ts +538 -82
  44. package/server/src/http/clusterRoutes.ts +10 -3
  45. package/server/src/http/router.ts +1 -0
  46. package/server/src/providers/codexChatBoundary.ts +6 -1
  47. package/server/src/research/quickPromotion.ts +24 -6
  48. package/server/src/research/savedQuickPromotion.ts +2 -8
  49. package/server/src/turnChanges.ts +5 -4
  50. package/server/src/ws/turnEngine.ts +4 -1
@@ -24,7 +24,7 @@ import { restoreLegacyTar } from './legacyTarRestore.js';
24
24
  // GOTCHAS invariant: the snapshot path must NEVER run a bare `git add` (which
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
- import { execFile } from 'node:child_process';
27
+ import { execFile, spawn } from 'node:child_process';
28
28
  import { promisify } from 'node:util';
29
29
  import { setImmediate } from 'node:timers/promises';
30
30
  import { promises as fs } from 'node:fs';
@@ -80,11 +80,14 @@ async function protectedTree(cwd, gitDir, tree, root) {
80
80
  const paths = await listTreePaths(cwd, gitDir, tree);
81
81
  return !paths || protectedPaths.includes('.') || paths.some(file => protectedPaths.some(folder => pathsOverlap(file, folder)));
82
82
  }
83
- async function runGit(cwd, args, extraEnv) {
83
+ async function runGit(cwd, args, extraEnv, timeout = GIT_TIMEOUT_MS, signal) {
84
+ if (signal?.aborted)
85
+ return { stdout: '', stderr: 'aborted', code: 1 };
84
86
  try {
85
87
  const { stdout, stderr } = await execFileAsync('git', args, {
86
88
  cwd,
87
- timeout: GIT_TIMEOUT_MS,
89
+ timeout,
90
+ ...(signal ? { signal } : {}),
88
91
  maxBuffer: GIT_MAX_BUFFER,
89
92
  env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
90
93
  });
@@ -120,8 +123,8 @@ function refFor(workflowId, seq) {
120
123
  }
121
124
  // Count files in a tree object (recursive). Used for the fileCount surfaced to
122
125
  // the operator. `-r` recurses, one line per blob.
123
- async function countTreeFiles(cwd, gitDir, treeish) {
124
- const out = await runGit(cwd, ['--git-dir', gitDir, 'ls-tree', '-r', '--name-only', treeish]);
126
+ async function countTreeFiles(cwd, gitDir, treeish, env) {
127
+ const out = await runGit(cwd, ['--git-dir', gitDir, 'ls-tree', '-r', '--name-only', treeish], env);
125
128
  if (out.code !== 0)
126
129
  return 0;
127
130
  return out.stdout.split('\n').filter((l) => l.trim().length > 0).length;
@@ -155,6 +158,60 @@ async function pruneOldCheckpoints(cwd, gitDir, workflowId, metadataRoot) {
155
158
  }
156
159
  }
157
160
  }
161
+ // Write the checkpoint ref unless the capture was cancelled. A cancellation
162
+ // that lands while update-ref runs is undone again, conditionally on the ref
163
+ // still pointing at this capture, so a late capture never leaves an undo point.
164
+ async function publishRef(cwd, gitDir, ref, sha, signal) {
165
+ if (signal?.aborted)
166
+ return false;
167
+ const update = await runGit(cwd, ['--git-dir', gitDir, 'update-ref', ref, sha]);
168
+ if (update.code !== 0) {
169
+ console.error(`[arco] gitSnapshots update-ref failed: ${update.stderr.trim()}`);
170
+ return false;
171
+ }
172
+ if (signal?.aborted) {
173
+ await withdrawRef(cwd, gitDir, ref, sha);
174
+ return false;
175
+ }
176
+ return true;
177
+ }
178
+ // Delete a checkpoint ref only while it still points at this capture.
179
+ async function withdrawRef(cwd, gitDir, ref, sha) {
180
+ await runGit(cwd, ['--git-dir', gitDir, 'update-ref', '-d', ref, sha]);
181
+ }
182
+ // Sizes of the blobs just staged for `paths`, checked against the per-file
183
+ // and included-total caps. Fails closed when the sizes cannot be read.
184
+ async function stagedWithinCaps(cwd, gitDir, env, staged, paths, signal) {
185
+ const shas = paths.map(p => staged.get(p)).filter((e) => !!e && e.mode !== '160000').map(e => e.sha);
186
+ if (!shas.length)
187
+ return true;
188
+ const sizes = await gitWithInput(cwd, ['--git-dir', gitDir, 'cat-file', '--batch-check=%(objectsize)'], shas.join('\n') + '\n', env, signal);
189
+ if (sizes === null)
190
+ return false;
191
+ const values = sizes.split('\n').filter(Boolean).map(Number);
192
+ if (values.length !== shas.length || values.some(v => !Number.isFinite(v)))
193
+ return false;
194
+ const fileCap = fileCapBytes(), totalCap = totalCapBytes();
195
+ if (fileCap > 0 && values.some(v => v > fileCap))
196
+ return false;
197
+ return !(totalCap > 0 && values.reduce((a, b) => a + b, 0) > totalCap);
198
+ }
199
+ function gitWithInput(cwd, args, input, extraEnv, signal) {
200
+ return new Promise((resolve) => {
201
+ const child = spawn('git', args, { cwd, env: { ...process.env, ...extraEnv }, stdio: ['pipe', 'pipe', 'ignore'], ...(signal ? { signal } : {}) });
202
+ const chunks = [];
203
+ let size = 0;
204
+ const timer = setTimeout(() => child.kill(), GIT_TIMEOUT_MS);
205
+ child.stdout.on('data', (chunk) => { size += chunk.length; if (size <= GIT_MAX_BUFFER)
206
+ chunks.push(chunk);
207
+ else
208
+ child.kill(); });
209
+ child.on('error', () => { clearTimeout(timer); resolve(null); });
210
+ child.on('close', (code) => { clearTimeout(timer); resolve(code === 0 && size <= GIT_MAX_BUFFER ? Buffer.concat(chunks).toString('utf8') : null); });
211
+ child.stdin.on('error', () => { });
212
+ child.stdin.end(input);
213
+ });
214
+ }
158
215
  async function createGitCheckpoint(args, gitDir) {
159
216
  const { cwd, workflowId, seq } = args;
160
217
  const label = args.label ?? `before turn ${seq}`;
@@ -169,30 +226,55 @@ async function createGitCheckpoint(args, gitDir) {
169
226
  // what the operator would see). On an unborn HEAD (fresh repo, no commits)
170
227
  // skip the read-tree and let add -A build the index from scratch.
171
228
  const snapEnv = { GIT_INDEX_FILE: snapIndex };
172
- const protectedPaths = await providerHomePaths(await gitCheckpointWorkTree(cwd, gitDir));
229
+ const root = await gitCheckpointWorkTree(cwd, gitDir);
230
+ const protectedPaths = await providerHomePaths(root);
173
231
  if (protectedPaths.includes('.'))
174
232
  return null;
175
- const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'])).code === 0;
233
+ const signal = args.signal;
234
+ const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'], undefined, GIT_TIMEOUT_MS, signal)).code === 0;
235
+ let quarantine = null;
236
+ let cleaned = false;
237
+ const cleanup = async () => {
238
+ cleaned = true;
239
+ await fs.rm(snapIndex, { force: true }).catch(() => { });
240
+ if (quarantine)
241
+ await discardQuarantine(quarantine.dir);
242
+ };
176
243
  try {
177
- if (headExists) {
178
- const readTree = await runGit(cwd, ['--git-dir', gitDir, 'read-tree', 'HEAD'], snapEnv);
179
- if (readTree.code !== 0) {
180
- console.error(`[arco] gitSnapshots read-tree failed: ${readTree.stderr.trim()}`);
181
- return null;
182
- }
244
+ if (headExists && !(await seedFromHead(cwd, gitDir, snapEnv, signal))) {
245
+ console.error('[arco] gitSnapshots read-tree failed');
246
+ return null;
183
247
  }
184
- // Stage the whole working tree into the SEPARATE index (never the user's).
185
- const add = await runGit(cwd, ['--git-dir', gitDir, 'add', '-A', '--', ':/', ...protectedPaths.map(p => `:(top,exclude,literal)${p}`)], snapEnv);
186
- if (add.code !== 0) {
187
- console.error(`[arco] gitSnapshots add -A failed: ${add.stderr.trim()}`);
248
+ // Scope before staging: nothing is hashed until large inputs are known.
249
+ const scope = await scanGitScope(cwd, gitDir, root, snapEnv, protectedPaths, signal);
250
+ if (!scope)
251
+ return null;
252
+ if (exceedsTotalCap(scope)) {
253
+ args.onSkipped?.(CHECKPOINT_SKIP_NOTICE);
254
+ console.error(`[arco] [${workflowId.slice(0, 8)}] gitSnapshots: snapshot skipped — new or changed files exceed the included-total cap (ARCO_CHECKPOINT_TOTAL_CAP_BYTES)`);
188
255
  return null;
189
256
  }
190
- if (protectedPaths.length) {
191
- const drop = await runGit(cwd, ['--git-dir', gitDir, 'rm', '--cached', '-r', '-q', '--ignore-unmatch', '--', ...protectedPaths.map(p => `:(top,literal)${p}`)], snapEnv);
192
- if (drop.code !== 0)
193
- return null;
257
+ const skipped = scope.largePaths;
258
+ quarantine = await openQuarantine(cwd, gitDir, signal);
259
+ if (!quarantine)
260
+ return null;
261
+ const workEnv = { ...snapEnv, ...quarantine.env };
262
+ // Stage the measured paths into the SEPARATE index (never the user's).
263
+ const staged = await stageGitScope(cwd, gitDir, root, workEnv, {
264
+ staged: scope.stagePaths,
265
+ removed: scope.removedPaths,
266
+ dropped: [...protectedPaths, ...skipped],
267
+ pinned: [],
268
+ }, signal);
269
+ if (!staged)
270
+ return null;
271
+ // A measured file can still grow between the scan and staging; the
272
+ // staged blobs are checked against the same caps before anything is kept.
273
+ if (!(await stagedWithinCaps(cwd, gitDir, workEnv, staged, scope.stagePaths, signal))) {
274
+ console.error(`[arco] [${workflowId.slice(0, 8)}] gitSnapshots: files grew past the checkpoint caps while being captured`);
275
+ return null;
194
276
  }
195
- const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], snapEnv);
277
+ const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], workEnv, GIT_TIMEOUT_MS, signal);
196
278
  if (writeTree.code !== 0) {
197
279
  console.error(`[arco] gitSnapshots write-tree failed: ${writeTree.stderr.trim()}`);
198
280
  return null;
@@ -204,13 +286,13 @@ async function createGitCheckpoint(args, gitDir) {
204
286
  // chain off the user's history. Identity is fixed so we don't depend on
205
287
  // (or pollute) the user's git config. Message carries the label + seq.
206
288
  const commitEnv = {
207
- ...snapEnv,
289
+ ...workEnv,
208
290
  GIT_AUTHOR_NAME: 'arco-checkpoint',
209
291
  GIT_AUTHOR_EMAIL: 'checkpoint@arco.local',
210
292
  GIT_COMMITTER_NAME: 'arco-checkpoint',
211
293
  GIT_COMMITTER_EMAIL: 'checkpoint@arco.local',
212
294
  };
213
- const commit = await runGit(cwd, ['--git-dir', gitDir, 'commit-tree', tree, '-m', `arco checkpoint: ${label} (seq ${seq})`], commitEnv);
295
+ const commit = await runGit(cwd, ['--git-dir', gitDir, 'commit-tree', tree, '-m', `arco checkpoint: ${label} (seq ${seq})`], commitEnv, GIT_TIMEOUT_MS, signal);
214
296
  if (commit.code !== 0) {
215
297
  console.error(`[arco] gitSnapshots commit-tree failed: ${commit.stderr.trim()}`);
216
298
  return null;
@@ -218,19 +300,44 @@ async function createGitCheckpoint(args, gitDir) {
218
300
  const sha = commit.stdout.trim();
219
301
  if (!sha)
220
302
  return null;
303
+ const fileCount = await countTreeFiles(cwd, gitDir, tree, workEnv);
304
+ // Objects reach the real store only once the whole capture succeeded,
305
+ // and a cancelled capture publishes nothing.
306
+ if (signal?.aborted)
307
+ return null;
308
+ if (!(await migrateQuarantine(quarantine, signal))) {
309
+ console.error('[arco] gitSnapshots: could not move checkpoint objects into the object store');
310
+ return null;
311
+ }
221
312
  const ref = refFor(workflowId, seq);
222
- const update = await runGit(cwd, ['--git-dir', gitDir, 'update-ref', ref, sha]);
223
- if (update.code !== 0) {
224
- console.error(`[arco] gitSnapshots update-ref failed: ${update.stderr.trim()}`);
313
+ const metadataRoot = checkpointStoreRoot(cwd);
314
+ if (skipped.length)
315
+ await writeSkippedManifest(cwd, workflowId, seq, skipped);
316
+ else
317
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => { });
318
+ if (!(await publishRef(cwd, gitDir, ref, sha, signal))) {
319
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => { });
320
+ return null;
321
+ }
322
+ // Finish every await before the last cancellation check. If the deadline
323
+ // passed meanwhile, withdraw the ref so a turn that missed its cutoff has
324
+ // no undo point. After the check nothing awaits until the result reaches
325
+ // the caller, and pruning starts only for a kept checkpoint, so a
326
+ // discarded attempt never removes an older usable one.
327
+ await cleanup();
328
+ if (signal?.aborted) {
329
+ await withdrawRef(cwd, gitDir, ref, sha);
330
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => { });
225
331
  return null;
226
332
  }
227
- const fileCount = await countTreeFiles(cwd, gitDir, tree);
228
- await pruneOldCheckpoints(cwd, gitDir, workflowId).catch(() => { });
229
- return { ref, fileCount, ts, backend: 'git', label };
333
+ void pruneOldCheckpoints(cwd, gitDir, workflowId, metadataRoot).catch(() => { });
334
+ return { ref, fileCount, ts, backend: 'git', label, ...(skipped.length ? { skippedLargeFiles: skipped.length } : {}) };
230
335
  }
231
336
  finally {
232
- // Clean up the separate index; harmless if it's already gone.
233
- await fs.rm(snapIndex, { force: true }).catch(() => { });
337
+ // Clean up the separate index and quarantine unless already done. A kept
338
+ // checkpoint has cleaned up before its last check, so no await runs here.
339
+ if (!cleaned)
340
+ await cleanup();
234
341
  }
235
342
  }
236
343
  // ── Non-git fallback: shadow git store ──
@@ -257,7 +364,8 @@ async function createGitCheckpoint(args, gitDir) {
257
364
  // bytes backstops pathological many-small-file trees; over it the snapshot is
258
365
  // skipped entirely (null = "no checkpoint this turn"). Overrides:
259
366
  // ARCO_CHECKPOINT_FILE_CAP_BYTES / ARCO_CHECKPOINT_TOTAL_CAP_BYTES
260
- // (0 disables either). Caps apply only to this fallback, never to real repos.
367
+ // (0 disables either). Git-backed checkpoints apply the same caps before
368
+ // staging; see the Git-backed scope section below.
261
369
  const DEFAULT_FILE_CAP_BYTES = 32 * 1024 * 1024; // 32 MiB per file
262
370
  const DEFAULT_TOTAL_CAP_BYTES = 1024 * 1024 * 1024; // 1 GiB included total
263
371
  // `git add` re-hashes every listed file (the object store dedupes writes, not
@@ -288,9 +396,280 @@ export function checkpointStoreRoot(cwd) {
288
396
  function shadowGitDir(cwd) {
289
397
  return path.join(checkpointStoreRoot(cwd), 'git');
290
398
  }
399
+ // ── Operation-owned object quarantine ──
400
+ //
401
+ // Every checkpoint operation writes its new Git objects into its own
402
+ // directory under the store's objects folder (`arco-incoming-*`), with the
403
+ // real object store as an alternate so existing objects still dedupe. A
404
+ // successful capture moves its finished objects into the real store before
405
+ // its ref is published; a failed, timed-out or cancelled capture removes only
406
+ // its own directory. Restore comparisons always discard theirs. Interrupted
407
+ // staging therefore cannot leave temporary packs or loose objects in the
408
+ // project, and nothing pre-existing in the store is ever deleted. Git refuses
409
+ // ref updates while GIT_QUARANTINE_PATH is set, so a ref can never point at
410
+ // objects that are about to be discarded. A directory left behind by a
411
+ // crashed server is never swept automatically: its age and name alone do not
412
+ // prove that no other process still owns it.
413
+ const QUARANTINE_PREFIX = 'arco-incoming-';
414
+ async function openQuarantine(cwd, gitDir, signal) {
415
+ const located = await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--git-path', 'objects'], undefined, GIT_TIMEOUT_MS, signal);
416
+ if (located.code !== 0 || !located.stdout.trim())
417
+ return null;
418
+ const objects = path.resolve(cwd, located.stdout.trim());
419
+ const dir = await fs.mkdtemp(path.join(objects, QUARANTINE_PREFIX)).catch(() => null);
420
+ if (!dir)
421
+ return null;
422
+ return { dir, objects, env: { GIT_OBJECT_DIRECTORY: dir, GIT_ALTERNATE_OBJECT_DIRECTORIES: objects, GIT_QUARANTINE_PATH: dir } };
423
+ }
424
+ async function discardQuarantine(dir) {
425
+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 3 }).catch(() => { });
426
+ }
427
+ // Make one finished object file visible in the real store under its final
428
+ // name in a single step. A hard link does that directly. Where links are not
429
+ // available the bytes are first copied to a temporary name that Git itself
430
+ // treats as garbage (`tmp_obj_*`), then renamed, so no reader can see a
431
+ // partly written object. An object that already exists is identical by
432
+ // content address and is left alone.
433
+ async function placeObject(src, dst) {
434
+ try {
435
+ await fs.link(src, dst);
436
+ return 'placed';
437
+ }
438
+ catch (err) {
439
+ if (err.code === 'EEXIST')
440
+ return 'existed';
441
+ }
442
+ const staged = path.join(path.dirname(dst), `tmp_obj_arco_${process.pid}_${randomUUID()}`);
443
+ try {
444
+ await fs.copyFile(src, staged, fs.constants.COPYFILE_EXCL);
445
+ try {
446
+ await fs.link(staged, dst);
447
+ return 'placed';
448
+ }
449
+ catch (err) {
450
+ if (err.code === 'EEXIST')
451
+ return 'existed';
452
+ await fs.rename(staged, dst);
453
+ return 'placed';
454
+ }
455
+ }
456
+ catch {
457
+ return 'failed';
458
+ }
459
+ finally {
460
+ await fs.rm(staged, { force: true }).catch(() => { });
461
+ }
462
+ }
463
+ // Move completed objects into the real store, never Git's own incomplete
464
+ // temporary files. Nothing placed under a final name is ever removed again,
465
+ // even when a later step fails: another operation may already have found the
466
+ // object or pack and published a ref that needs it. Pack data goes before its
467
+ // index, so a pack only becomes usable once complete. A failure can therefore
468
+ // leave unreferenced loose objects, or pack data without its index, which
469
+ // ordinary `git gc` handles or which stay as bounded garbage. Cancellation is
470
+ // checked between objects, so a cancelled capture stops moving promptly.
471
+ async function migrateQuarantine(q, signal) {
472
+ try {
473
+ for (const name of await fs.readdir(q.dir)) {
474
+ if (!/^[0-9a-f]{2}$/.test(name))
475
+ continue;
476
+ const files = (await fs.readdir(path.join(q.dir, name))).filter(file => /^[0-9a-f]{38,62}$/.test(file));
477
+ if (!files.length)
478
+ continue;
479
+ await fs.mkdir(path.join(q.objects, name), { recursive: true });
480
+ for (const file of files) {
481
+ if (signal?.aborted)
482
+ return false;
483
+ if (await placeObject(path.join(q.dir, name, file), path.join(q.objects, name, file)) === 'failed')
484
+ return false;
485
+ }
486
+ }
487
+ const packDir = path.join(q.dir, 'pack');
488
+ const indexes = (await fs.readdir(packDir).catch(() => [])).filter(name => /^pack-[0-9a-f]+\.idx$/.test(name));
489
+ if (indexes.length)
490
+ await fs.mkdir(path.join(q.objects, 'pack'), { recursive: true });
491
+ for (const index of indexes) {
492
+ const base = index.slice(0, -'.idx'.length);
493
+ for (const name of [`${base}.pack`, `${base}.rev`, `${base}.bitmap`, index]) {
494
+ if (signal?.aborted)
495
+ return false;
496
+ const src = path.join(packDir, name);
497
+ if (!name.endsWith('.idx') && !(await fs.access(src).then(() => true, () => false)))
498
+ continue;
499
+ if (await placeObject(src, path.join(q.objects, 'pack', name)) === 'failed')
500
+ return false;
501
+ }
502
+ }
503
+ return true;
504
+ }
505
+ catch {
506
+ return false;
507
+ }
508
+ }
509
+ async function seedFromHead(cwd, gitDir, env, signal) {
510
+ const index = env.GIT_INDEX_FILE;
511
+ const userIndex = path.join(gitDir, 'index');
512
+ // Read-only use of the user's index: copy it, keep its timestamp so Git's
513
+ // racy-clean detection still applies, and merge HEAD into the copy.
514
+ const st = await fs.stat(userIndex).catch(() => null);
515
+ if (st) {
516
+ const copied = await fs.copyFile(userIndex, index).then(() => fs.utimes(index, st.atime, st.mtime)).then(() => true, () => false);
517
+ if (copied && (await runGit(cwd, ['--git-dir', gitDir, 'read-tree', '-m', 'HEAD'], env, GIT_TIMEOUT_MS, signal)).code === 0)
518
+ return true;
519
+ await fs.rm(index, { force: true }).catch(() => { });
520
+ }
521
+ return (await runGit(cwd, ['--git-dir', gitDir, 'read-tree', 'HEAD'], env, GIT_TIMEOUT_MS, signal)).code === 0;
522
+ }
523
+ function gitPathList(stdout, protectedPaths) {
524
+ return stdout.split('\0').filter(item => item && !item.endsWith('/') && !protectedPaths.some(folder => pathsOverlap(item, folder)));
525
+ }
526
+ async function scanGitScope(cwd, gitDir, root, env, protectedPaths, signal) {
527
+ const fileCap = fileCapBytes();
528
+ // Paths whose working file may differ from the seeded entry. Entries without
529
+ // borrowed stat data are listed too, so this errs toward measuring more.
530
+ const changed = await runGit(cwd, ['--git-dir', gitDir, 'diff-files', '--name-only', '-z', '--no-renames', '--', ':/'], env, GIT_TIMEOUT_MS, signal);
531
+ const untracked = await runGit(cwd, ['--git-dir', gitDir, 'ls-files', '-z', '--full-name', '--others', '--exclude-standard', '--', ':/'], env, GIT_TIMEOUT_MS, signal);
532
+ const seeded = await indexEntries(cwd, gitDir, env, signal);
533
+ if (changed.code !== 0 || untracked.code !== 0 || !seeded)
534
+ return null;
535
+ const largePaths = [];
536
+ const stagePaths = [];
537
+ const removedPaths = [];
538
+ let eligibleBytes = 0;
539
+ const candidates = [...new Set([...gitPathList(changed.stdout, protectedPaths), ...gitPathList(untracked.stdout, protectedPaths)])];
540
+ for (let i = 0; i < candidates.length; i += 128) {
541
+ if (signal?.aborted)
542
+ return null;
543
+ await Promise.all(candidates.slice(i, i + 128).map(async (rel) => {
544
+ const st = await fs.lstat(path.join(root, rel)).catch(() => null);
545
+ const entry = seeded.get(rel);
546
+ if (st?.isFile()) {
547
+ if (fileCap > 0 && st.size > fileCap)
548
+ largePaths.push(rel);
549
+ else {
550
+ eligibleBytes += st.size;
551
+ stagePaths.push(rel);
552
+ }
553
+ }
554
+ else if (st?.isSymbolicLink() || (st?.isDirectory() && entry?.mode === '160000')) {
555
+ // Links and submodule commits are recorded without reading contents.
556
+ stagePaths.push(rel);
557
+ }
558
+ else if (entry) {
559
+ // A tracked path that is gone, or is now a folder or special file, is
560
+ // recorded as a deletion without staging anything below it. Files in
561
+ // a folder that replaced it are listed and measured on their own.
562
+ removedPaths.push(rel);
563
+ }
564
+ }));
565
+ }
566
+ return { largePaths: largePaths.sort(), stagePaths: stagePaths.sort(), removedPaths: removedPaths.sort(), eligibleBytes };
567
+ }
568
+ // Stage-0 entries of a scratch index: path -> mode and blob id.
569
+ async function indexEntries(cwd, gitDir, env, signal) {
570
+ const listed = await runGit(cwd, ['--git-dir', gitDir, 'ls-files', '-s', '-z', '--full-name', '--', ':/'], env, GIT_TIMEOUT_MS, signal);
571
+ if (listed.code !== 0)
572
+ return null;
573
+ const entries = new Map();
574
+ for (const line of listed.stdout.split('\0')) {
575
+ const match = /^(\d+) ([0-9a-f]+) (\d)\t(.+)$/s.exec(line);
576
+ if (match)
577
+ entries.set(match[4], { mode: match[1], sha: match[2] });
578
+ }
579
+ return entries;
580
+ }
581
+ function exceedsTotalCap(scope) {
582
+ const cap = totalCapBytes();
583
+ return cap > 0 && scope.eligibleBytes > cap;
584
+ }
585
+ // Blob id and mode for each path of a tree, so a large file can be compared
586
+ // with what the tree records without hashing it into the store.
587
+ async function treeBlobs(cwd, gitDir, treeish) {
588
+ const out = await runGit(cwd, ['--git-dir', gitDir, 'ls-tree', '-r', '-z', '--full-tree', treeish]);
589
+ if (out.code !== 0)
590
+ return null;
591
+ const blobs = new Map();
592
+ for (const line of out.stdout.split('\0')) {
593
+ const match = /^(\d+) blob ([0-9a-f]+)\t(.+)$/s.exec(line);
594
+ if (match)
595
+ blobs.set(match[3], { mode: match[1], sha: match[2] });
596
+ }
597
+ return blobs;
598
+ }
599
+ // Git resolves index and pathname arguments against the invocation prefix.
600
+ function fromCwd(cwd, root, rel) {
601
+ return path.relative(cwd, path.join(root, rel)).split(path.sep).join('/') || '.';
602
+ }
603
+ // Hash without -w: reads the file through the path's filters, writes nothing.
604
+ async function matchesBlob(cwd, gitDir, root, rel, sha) {
605
+ const local = fromCwd(cwd, root, rel);
606
+ const out = await runGit(cwd, ['--git-dir', gitDir, 'hash-object', `--path=${local}`, '--', local], undefined, STAGE_TIMEOUT_MS);
607
+ return out.code === 0 && out.stdout.trim() === sha;
608
+ }
609
+ async function withPathspecFile(specs, fn) {
610
+ const file = path.join(tmpdir(), `arco-pathspec-${process.pid}-${randomUUID()}.txt`);
611
+ await fs.writeFile(file, specs.join('\0') + '\0');
612
+ try {
613
+ return await fn(file);
614
+ }
615
+ finally {
616
+ await fs.rm(file, { force: true }).catch(() => { });
617
+ }
618
+ }
619
+ // Stage the working tree into a scratch index without hashing out-of-scope
620
+ // large files.
621
+ async function stageGitScope(cwd, gitDir, root, env, plan, signal) {
622
+ // Plain arguments in small batches: `git rm --pathspec-from-file` is
623
+ // refused when Git adds the invocation prefix of a subdirectory work tree.
624
+ const unstage = async (paths, recursive) => {
625
+ for (let i = 0; i < paths.length; i += 200) {
626
+ const drop = await runGit(cwd, ['--git-dir', gitDir, 'rm', '--cached', ...(recursive ? ['-r'] : []), '-q', '--ignore-unmatch', '--',
627
+ ...paths.slice(i, i + 200).map(p => `:(top,literal)${p}`)], env, GIT_TIMEOUT_MS, signal);
628
+ if (drop.code !== 0) {
629
+ console.error(`[arco] gitSnapshots rm --cached failed: ${drop.stderr.trim()}`);
630
+ return false;
631
+ }
632
+ }
633
+ return true;
634
+ };
635
+ if (!(await unstage(plan.removed, false)))
636
+ return null;
637
+ const before = await indexEntries(cwd, gitDir, env, signal);
638
+ if (!before)
639
+ return null;
640
+ // A measured path that disappears before staging fails the capture; the
641
+ // next turn captures again.
642
+ const add = plan.staged.length ? await withPathspecFile(plan.staged.map(p => `:(top,literal)${p}`), file => runGit(cwd, ['--git-dir', gitDir, 'add', '-A', '--pathspec-from-file', file, '--pathspec-file-nul'], env, GIT_TIMEOUT_MS, signal)) : { code: 0, stderr: '' };
643
+ if (add.code !== 0) {
644
+ console.error(`[arco] gitSnapshots add -A failed: ${add.stderr.trim()}`);
645
+ return null;
646
+ }
647
+ if (!(await unstage(plan.dropped, true)))
648
+ return null;
649
+ for (const pin of plan.pinned) {
650
+ const set = await runGit(cwd, ['--git-dir', gitDir, 'update-index', '--add', '--cacheinfo', `${pin.mode},${pin.sha},${fromCwd(cwd, root, pin.path)}`], env);
651
+ if (set.code !== 0)
652
+ return null;
653
+ }
654
+ // A measured file replaced by a folder before staging would make `add`
655
+ // record the folder's contents unmeasured. Any entry that was neither
656
+ // seeded nor measured fails the whole operation, and its objects are
657
+ // discarded with the quarantine.
658
+ const after = await indexEntries(cwd, gitDir, env, signal);
659
+ if (!after)
660
+ return null;
661
+ const expected = new Set([...plan.staged, ...plan.pinned.map(pin => pin.path)]);
662
+ for (const file of after.keys()) {
663
+ if (!before.has(file) && !expected.has(file)) {
664
+ console.error('[arco] gitSnapshots: an unmeasured path appeared during staging');
665
+ return null;
666
+ }
667
+ }
668
+ return after;
669
+ }
291
670
  // Shadow snapshots exclude nested Git repositories as whole directories. The
292
671
  // scope manifest preserves those folders even if their Git marker later moves.
293
- async function collectSnapshotFiles(root, fileCap, totalCap) {
672
+ async function collectSnapshotFiles(root, fileCap, totalCap, signal) {
294
673
  const files = [];
295
674
  const protectedPaths = await providerHomePaths(root);
296
675
  if (protectedPaths.includes('.'))
@@ -302,7 +681,7 @@ async function collectSnapshotFiles(root, fileCap, totalCap) {
302
681
  let remaining = Math.max(1, Math.floor(scanLimit('ARCO_CHECKPOINT_SCAN_ENTRIES', 20_000)));
303
682
  const deadline = performance.now() + scanLimit('ARCO_CHECKPOINT_SCAN_MS', 5000);
304
683
  while (stack.length > 0) {
305
- if (remaining <= 0 || performance.now() >= deadline)
684
+ if (remaining <= 0 || performance.now() >= deadline || signal?.aborted)
306
685
  return { files, skippedLargePaths, exceededTotal: false, exceededScan: true };
307
686
  await setImmediate();
308
687
  const rel = stack.pop();
@@ -394,7 +773,7 @@ async function initializeShadowRepo(cwd, gitDir) {
394
773
  // whole staging — ignore rules are the project's business, not the snapshot's.
395
774
  // A file deleted between walk and add fails the staging (unmatched pathspec);
396
775
  // that's an acceptable best-effort miss — the next turn snapshots again.
397
- async function stagePathspecs(cwd, gitDir, indexFile, files) {
776
+ async function stagePathspecs(cwd, gitDir, indexFile, files, extraEnv = {}, signal) {
398
777
  if (files.length === 0)
399
778
  return true; // empty tree is a valid snapshot
400
779
  const pathspecFile = path.join(gitDir, `pathspec-${process.pid}-${randomUUID()}.tmp`);
@@ -407,8 +786,17 @@ async function stagePathspecs(cwd, gitDir, indexFile, files) {
407
786
  cwd,
408
787
  timeout: STAGE_TIMEOUT_MS,
409
788
  maxBuffer: GIT_MAX_BUFFER,
410
- env: { ...process.env, GIT_INDEX_FILE: indexFile },
789
+ env: { ...process.env, ...extraEnv, GIT_INDEX_FILE: indexFile },
790
+ ...(signal ? { signal } : {}),
411
791
  });
792
+ // A listed file replaced by a folder before staging would bring the
793
+ // folder's contents in unwalked; such a staging fails as a whole.
794
+ 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);
795
+ const walked = new Set(files);
796
+ if (listed.code !== 0 || listed.stdout.split('\0').some(file => file && !walked.has(file))) {
797
+ console.error('[arco] gitSnapshots shadow staging failed: an unwalked path appeared during staging');
798
+ return false;
799
+ }
412
800
  return true;
413
801
  }
414
802
  catch (err) {
@@ -489,7 +877,10 @@ async function createShadowGitCheckpoint(args) {
489
877
  const { cwd, workflowId, seq } = args;
490
878
  const label = args.label ?? `before turn ${seq}`;
491
879
  const ts = Date.now();
492
- const walk = await collectSnapshotFiles(cwd, fileCapBytes(), totalCapBytes());
880
+ const signal = args.signal;
881
+ const walk = await collectSnapshotFiles(cwd, fileCapBytes(), totalCapBytes(), signal);
882
+ if (signal?.aborted)
883
+ return null;
493
884
  if (walk.exceededTotal || walk.exceededScan) {
494
885
  args.onSkipped?.(CHECKPOINT_SKIP_NOTICE);
495
886
  console.error(`[arco] [${workflowId.slice(0, 8)}] gitSnapshots: shadow snapshot skipped — ` +
@@ -503,11 +894,20 @@ async function createShadowGitCheckpoint(args) {
503
894
  // here (unlike the revert path) because snapshotting never runs `-u`.
504
895
  // Per-operation naming prevents same-cwd workflows from sharing a lock.
505
896
  const snapIndex = path.join(gitDir, `snap-${process.pid}-${randomUUID()}.index`);
506
- const env = { GIT_INDEX_FILE: snapIndex };
897
+ const quarantine = await openQuarantine(cwd, gitDir, signal);
898
+ if (!quarantine)
899
+ return null;
900
+ const env = { GIT_INDEX_FILE: snapIndex, ...quarantine.env };
901
+ let cleaned = false;
902
+ const cleanup = async () => {
903
+ cleaned = true;
904
+ await fs.rm(snapIndex, { force: true }).catch(() => { });
905
+ await discardQuarantine(quarantine.dir);
906
+ };
507
907
  try {
508
- if (!(await stagePathspecs(cwd, gitDir, snapIndex, walk.files)))
908
+ if (!(await stagePathspecs(cwd, gitDir, snapIndex, walk.files, quarantine.env, signal)))
509
909
  return null;
510
- const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], env);
910
+ const writeTree = await runGit(cwd, ['--git-dir', gitDir, 'write-tree'], env, GIT_TIMEOUT_MS, signal);
511
911
  if (writeTree.code !== 0) {
512
912
  console.error(`[arco] gitSnapshots shadow write-tree failed: ${writeTree.stderr.trim()}`);
513
913
  return null;
@@ -522,7 +922,7 @@ async function createShadowGitCheckpoint(args) {
522
922
  GIT_COMMITTER_NAME: 'arco-checkpoint',
523
923
  GIT_COMMITTER_EMAIL: 'checkpoint@arco.local',
524
924
  };
525
- const commit = await runGit(cwd, ['--git-dir', gitDir, 'commit-tree', tree, '-m', `arco checkpoint: ${label} (seq ${seq})`], commitEnv);
925
+ const commit = await runGit(cwd, ['--git-dir', gitDir, 'commit-tree', tree, '-m', `arco checkpoint: ${label} (seq ${seq})`], commitEnv, GIT_TIMEOUT_MS, signal);
526
926
  if (commit.code !== 0) {
527
927
  console.error(`[arco] gitSnapshots shadow commit-tree failed: ${commit.stderr.trim()}`);
528
928
  return null;
@@ -530,20 +930,34 @@ async function createShadowGitCheckpoint(args) {
530
930
  const sha = commit.stdout.trim();
531
931
  if (!sha)
532
932
  return null;
933
+ const fileCount = await countTreeFiles(cwd, gitDir, tree, env);
934
+ if (signal?.aborted)
935
+ return null;
936
+ if (!(await migrateQuarantine(quarantine, signal))) {
937
+ console.error('[arco] gitSnapshots: could not move shadow checkpoint objects into its object store');
938
+ return null;
939
+ }
533
940
  const ref = refFor(workflowId, seq);
534
941
  await writeSkippedManifest(cwd, workflowId, seq, [...walk.skippedLargePaths, ...(walk.skippedNestedPaths ?? [])], walk.skippedNestedPaths ?? []);
535
- const update = await runGit(cwd, ['--git-dir', gitDir, 'update-ref', ref, sha]);
536
- if (update.code !== 0) {
942
+ if (!(await publishRef(cwd, gitDir, ref, sha, signal))) {
537
943
  await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => { });
538
- console.error(`[arco] gitSnapshots shadow update-ref failed: ${update.stderr.trim()}`);
539
944
  return null;
540
945
  }
541
- await pruneOldCheckpoints(cwd, gitDir, workflowId, checkpointStoreRoot(cwd)).catch(() => { });
542
- // Best-effort repack so pruned checkpoints' objects don't pile up loose.
543
- await runGit(cwd, ['--git-dir', gitDir, 'gc', '--auto', '-q']).catch(() => { });
946
+ // Same contract as the Git-backed capture: every await finishes before
947
+ // the last cancellation check, and pruning starts only once kept.
948
+ await cleanup();
949
+ if (signal?.aborted) {
950
+ await withdrawRef(cwd, gitDir, ref, sha);
951
+ await fs.rm(skippedManifestPath(cwd, workflowId, seq), { force: true }).catch(() => { });
952
+ return null;
953
+ }
954
+ // Best-effort repack afterwards so pruned checkpoints' objects don't pile up loose.
955
+ void pruneOldCheckpoints(cwd, gitDir, workflowId, checkpointStoreRoot(cwd))
956
+ .then(() => runGit(cwd, ['--git-dir', gitDir, 'gc', '--auto', '-q']))
957
+ .catch(() => { });
544
958
  return {
545
959
  ref,
546
- fileCount: await countTreeFiles(cwd, gitDir, tree),
960
+ fileCount,
547
961
  ts,
548
962
  backend: 'shadow-git',
549
963
  label,
@@ -552,7 +966,8 @@ async function createShadowGitCheckpoint(args) {
552
966
  };
553
967
  }
554
968
  finally {
555
- await fs.rm(snapIndex, { force: true }).catch(() => { });
969
+ if (!cleaned)
970
+ await cleanup();
556
971
  }
557
972
  }
558
973
  // Snapshot the working tree before a turn that may write. Returns null when
@@ -610,6 +1025,11 @@ async function resolveCheckpointTree(cwd, gitDir, ref) {
610
1025
  const tree = out.stdout.trim();
611
1026
  return tree || null;
612
1027
  }
1028
+ async function releasePrepared(p) {
1029
+ await fs.rm(p.index, { force: true }).catch(() => { });
1030
+ if (p.quarantine)
1031
+ await discardQuarantine(p.quarantine);
1032
+ }
613
1033
  function scratchIndex(cwd, workflowId, seq) {
614
1034
  // CRUCIAL: OUTSIDE the working tree. `read-tree -u --reset` sweeps
615
1035
  // working-tree files (and now-empty dirs) absent from the target tree; an
@@ -628,8 +1048,16 @@ async function prepareGitRestore(cwd, gitDir, workflowId, seq) {
628
1048
  if (await protectedTree(cwd, gitDir, tree, root))
629
1049
  return { problem: 'provider-overlap' };
630
1050
  const protectedPaths = await providerHomePaths(root);
1051
+ // Paths left out when the target was captured stay out of the seed, so the
1052
+ // restore neither deletes nor rewrites them. Checkpoints without a manifest
1053
+ // recorded everything.
1054
+ const targetSkipped = await readSkippedManifest(cwd, workflowId, seq);
1055
+ if (!targetSkipped) {
1056
+ console.error('[arco] gitSnapshots revert aborted: skipped-path manifest is unreadable');
1057
+ return { problem: 'failed' };
1058
+ }
631
1059
  const index = scratchIndex(cwd, workflowId, seq);
632
- const env = { GIT_INDEX_FILE: index };
1060
+ const seedEnv = { GIT_INDEX_FILE: index };
633
1061
  await fs.rm(index, { force: true }).catch(() => { });
634
1062
  // Seed the scratch index from the LIVE working tree so every currently
635
1063
  // present file (tracked + untracked) is registered there. `read-tree -u
@@ -641,38 +1069,71 @@ async function prepareGitRestore(cwd, gitDir, workflowId, seq) {
641
1069
  // seed so a revert never sweeps them even if a project failed to gitignore
642
1070
  // .arco. Checkpoint trees normally don't contain .arco anyway (it's
643
1071
  // gitignored in a project cwd), so the target tree won't re-create it.
644
- const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'], env)).code === 0;
645
- if (headExists) {
646
- const rt = await runGit(cwd, ['--git-dir', gitDir, 'read-tree', 'HEAD'], env);
647
- if (rt.code !== 0) {
648
- console.error(`[arco] gitSnapshots revert seed read-tree failed: ${rt.stderr.trim()}`);
649
- await fs.rm(index, { force: true }).catch(() => { });
650
- return { problem: 'failed' };
1072
+ const headExists = (await runGit(cwd, ['--git-dir', gitDir, 'rev-parse', '--verify', 'HEAD'], seedEnv)).code === 0;
1073
+ if (headExists && !(await seedFromHead(cwd, gitDir, seedEnv))) {
1074
+ console.error('[arco] gitSnapshots revert seed read-tree failed');
1075
+ await releasePrepared({ index });
1076
+ return { problem: 'failed' };
1077
+ }
1078
+ const scope = await scanGitScope(cwd, gitDir, root, seedEnv, protectedPaths);
1079
+ if (!scope) {
1080
+ await releasePrepared({ index });
1081
+ return { problem: 'failed' };
1082
+ }
1083
+ if (exceedsTotalCap(scope)) {
1084
+ await releasePrepared({ index });
1085
+ return { problem: 'too-large' };
1086
+ }
1087
+ // A changed or untracked file over the per-file cap is never hashed into the
1088
+ // store. If the target would write that path, its current bytes must already
1089
+ // match the target, because neither the target nor the safety snapshot can
1090
+ // hold them. An unchanged committed large file is held by HEAD and by the
1091
+ // safety snapshot, so the restore may replace it.
1092
+ const target = scope.largePaths.length ? await treeBlobs(cwd, gitDir, tree) : null;
1093
+ if (scope.largePaths.length && !target) {
1094
+ await releasePrepared({ index });
1095
+ return { problem: 'failed' };
1096
+ }
1097
+ const pinned = [];
1098
+ for (const rel of scope.largePaths) {
1099
+ const blob = target?.get(rel);
1100
+ const overlapping = !blob && target && [...target.keys()].some(file => pathsOverlap(file, rel));
1101
+ if (overlapping || (blob && !(await matchesBlob(cwd, gitDir, root, rel, blob.sha)))) {
1102
+ console.error('[arco] gitSnapshots revert aborted: a file over the per-file cap overlaps the target tree');
1103
+ await releasePrepared({ index });
1104
+ return { problem: 'capped-overlap' };
651
1105
  }
1106
+ if (blob)
1107
+ pinned.push({ path: rel, ...blob });
652
1108
  }
1109
+ const quarantine = await openQuarantine(cwd, gitDir);
1110
+ if (!quarantine) {
1111
+ await releasePrepared({ index });
1112
+ return { problem: 'failed' };
1113
+ }
1114
+ const env = { ...seedEnv, ...quarantine.env };
653
1115
  // NOTE: this used to be `add -A -- ':!.arco' ':!.git'`, but an
654
1116
  // exclude-only pathspec makes git treat matched-but-IGNORED dirs as
655
1117
  // explicitly requested — with a global `**/.arco/` ignore rule (the operator's
656
1118
  // ~/.config/git/ignore) the add REFUSED (.arco "ignored by one of your
657
1119
  // .gitignore files") and every revert in a repo containing .arco failed
658
- // (found 2026-08-19). Plain `add -A` skips ignored files silently; the
659
- // follow-up `rm --cached` then drops .arco from the seed where a project
660
- // does NOT ignore it. Both must succeed — a seeded .arco would be swept
661
- // from the working tree by `read-tree -u --reset` (it's absent from every
662
- // checkpoint tree).
663
- const add = await runGit(cwd, ['--git-dir', gitDir, 'add', '-A', '--', ':/', ...protectedPaths.map(p => `:(top,exclude,literal)${p}`)], env);
664
- if (add.code !== 0) {
665
- console.error(`[arco] gitSnapshots revert seed add -A failed: ${add.stderr.trim()}`);
666
- await fs.rm(index, { force: true }).catch(() => { });
1120
+ // (found 2026-08-19). Plain `add -A` with a positive `:/` skips ignored files
1121
+ // silently; the dropped `.arco` then leaves the seed where a project does
1122
+ // NOT ignore it. Both must succeed — a seeded .arco would be swept from the
1123
+ // working tree by `read-tree -u --reset` (it's absent from every checkpoint
1124
+ // tree).
1125
+ const outOfScope = [...protectedPaths, ...scope.largePaths, ...targetSkipped.paths];
1126
+ const stateDir = path.relative(root, path.join(await fs.realpath(cwd), '.arco')).split(path.sep).join('/');
1127
+ // Only measured paths enter the seed. A file that appears after the scan is
1128
+ // absent from the seed, so the restore leaves it in place.
1129
+ const inScope = (file) => ![stateDir, ...targetSkipped.paths].some(out => pathsOverlap(file, out));
1130
+ const staged = scope.stagePaths.filter(inScope);
1131
+ if (!(await stageGitScope(cwd, gitDir, root, env, { staged, removed: scope.removedPaths.filter(inScope), dropped: [stateDir, ...outOfScope], pinned }))) {
1132
+ console.error('[arco] gitSnapshots revert seed failed');
1133
+ await releasePrepared({ index, quarantine: quarantine.dir });
667
1134
  return { problem: 'failed' };
668
1135
  }
669
- const drop = await runGit(cwd, ['--git-dir', gitDir, 'rm', '--cached', '-r', '-q', '--ignore-unmatch', '--', '.arco', ...protectedPaths.map(p => `:(top,literal)${p}`)], env);
670
- if (drop.code !== 0) {
671
- console.error(`[arco] gitSnapshots revert seed .arco drop failed: ${drop.stderr.trim()}`);
672
- await fs.rm(index, { force: true }).catch(() => { });
673
- return { problem: 'failed' };
674
- }
675
- return { gitDir, workTree: [], ref, tree, env, index };
1136
+ return { gitDir, workTree: [], ref, tree, env, index, quarantine: quarantine.dir };
676
1137
  }
677
1138
  // Shadow store: the scratch index is seeded from the current capped walk plus
678
1139
  // the target ref's skipped-path manifest. This is load-bearing: seeding an
@@ -739,18 +1200,21 @@ async function prepareShadowRestore(cwd, workflowId, seq) {
739
1200
  legacyFolders.size ? `Older checkpoint left unrecorded folders unchanged: ${namedScope([...legacyFolders])}.` : ''].filter(Boolean).join(' ');
740
1201
  const index = scratchIndex(cwd, workflowId, seq);
741
1202
  await fs.rm(index, { force: true }).catch(() => { });
742
- if (!(await stagePathspecs(cwd, gitDir, index, seedFiles))) {
743
- await fs.rm(index, { force: true }).catch(() => { });
1203
+ const quarantine = await openQuarantine(cwd, gitDir);
1204
+ if (!quarantine)
1205
+ return { problem: 'failed' };
1206
+ if (!(await stagePathspecs(cwd, gitDir, index, seedFiles, quarantine.env))) {
1207
+ await releasePrepared({ index, quarantine: quarantine.dir });
744
1208
  return { problem: 'failed' };
745
1209
  }
746
- return { gitDir, workTree: ['--work-tree', cwd], ref, tree, env: { GIT_INDEX_FILE: index }, index, ...(limitation ? { limitation } : {}) };
1210
+ return { gitDir, workTree: ['--work-tree', cwd], ref, tree, env: { GIT_INDEX_FILE: index, ...quarantine.env }, index, quarantine: quarantine.dir, ...(limitation ? { limitation } : {}) };
747
1211
  }
748
1212
  async function prepareRestore(cwd, workflowId, seq) {
749
1213
  const { isRepo, gitDir } = await isGitRepo(cwd);
750
1214
  return isRepo && gitDir ? prepareGitRestore(cwd, gitDir, workflowId, seq) : prepareShadowRestore(cwd, workflowId, seq);
751
1215
  }
752
1216
  // The live tree a restore would replace, as a tree object (written into the
753
- // same object store; unreferenced, so ordinary gc reclaims it).
1217
+ // operation's quarantine and discarded with it).
754
1218
  async function liveTree(cwd, p) {
755
1219
  const out = await runGit(cwd, ['--git-dir', p.gitDir, 'write-tree'], p.env);
756
1220
  return out.code === 0 && out.stdout.trim() ? out.stdout.trim() : null;
@@ -759,7 +1223,7 @@ async function countRestoreChanges(cwd, p) {
759
1223
  const live = await liveTree(cwd, p);
760
1224
  if (!live)
761
1225
  return null;
762
- const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff-tree', '-r', '-z', '--no-renames', '--name-status', live, p.tree]);
1226
+ const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff-tree', '-r', '-z', '--no-renames', '--name-status', live, p.tree], p.env);
763
1227
  if (diff.code !== 0)
764
1228
  return null;
765
1229
  const parts = diff.stdout.split('\0');
@@ -805,7 +1269,7 @@ export async function previewCheckpointRevert(args) {
805
1269
  return changes ? { ok: true, changes, ...(p.limitation ? { limitation: p.limitation } : {}) } : { ok: false, error: PREVIEW_PROBLEMS.failed };
806
1270
  }
807
1271
  finally {
808
- await fs.rm(p.index, { force: true }).catch(() => { });
1272
+ await releasePrepared(p);
809
1273
  }
810
1274
  }
811
1275
  /**
@@ -823,11 +1287,11 @@ export async function diffCheckpointToNow(cwd, workflowId, seq) {
823
1287
  const live = await liveTree(cwd, p);
824
1288
  if (!live)
825
1289
  return { problem: 'failed' };
826
- const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff', '--no-ext-diff', '--no-textconv', '--no-color', p.tree, live]);
1290
+ const diff = await runGit(cwd, ['--git-dir', p.gitDir, 'diff', '--no-ext-diff', '--no-textconv', '--no-color', p.tree, live], p.env);
827
1291
  return diff.code === 0 ? { patch: diff.stdout } : { problem: 'failed' };
828
1292
  }
829
1293
  finally {
830
- await fs.rm(p.index, { force: true }).catch(() => { });
1294
+ await releasePrepared(p);
831
1295
  }
832
1296
  }
833
1297
  async function revertPrepared(cwd, p) {
@@ -847,7 +1311,7 @@ async function revertPrepared(cwd, p) {
847
1311
  return { fileCount, backend: 'git', restoredFrom: p.ref, ...(changes ? { changes } : {}), ...(p.limitation ? { limitation: p.limitation } : {}) };
848
1312
  }
849
1313
  finally {
850
- await fs.rm(p.index, { force: true }).catch(() => { });
1314
+ await releasePrepared(p);
851
1315
  }
852
1316
  }
853
1317
  // Legacy reader: pre-2026-08-19 non-git checkpoints are tar archives in the