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.
- package/CONTRIBUTING.md +26 -24
- package/client/dist/assets/{PhosphorBackdrop-BbR3xmfD.js → PhosphorBackdrop-CHXVFLGT.js} +1 -1
- package/client/dist/assets/{ThemedBackgroundShaderImpl-UMjbs9ZN.js → ThemedBackgroundShaderImpl-Bhs4I9jA.js} +1 -1
- package/client/dist/assets/{XtermView-n135qz-f.js → XtermView-CdfurwFx.js} +1 -1
- package/client/dist/assets/{galleryEditor-CFSke4by.js → galleryEditor-DYjZZ4cf.js} +1 -1
- package/client/dist/assets/{index-DeoJbjI3.js → index-BjDmFvqG.js} +219 -219
- package/client/dist/index.html +1 -1
- package/client/dist/manifest-mobile.webmanifest +1 -0
- package/client/src/components/Connections/Connections.tsx +3 -3
- package/client/src/components/research/QuickResearchOverview.tsx +7 -3
- package/client/src/components/research/SavedQuickKeep.tsx +7 -3
- package/client/src/help/content/misc.tsx +2 -2
- package/client/src/help/content/rightPanel.tsx +3 -2
- package/client/src/help/manualSections/clusters.tsx +1 -1
- package/client/src/help/manualSections/powerFeatures.tsx +3 -2
- package/client/src/layout/layoutRange.ts +10 -0
- package/client/src/main.tsx +2 -0
- package/docs/CHECKPOINTS.md +67 -3
- package/docs/CLIENT.md +1 -1
- package/docs/HTTP_API.md +9 -7
- package/docs/PROVIDERS.md +1 -1
- package/docs/RESEARCH.md +2 -2
- package/node_modules/@arco/shared/package.json +1 -1
- package/package.json +2 -2
- package/server/dist/capabilities.d.ts +6 -0
- package/server/dist/capabilities.js +13 -4
- package/server/dist/explorerDocs.d.ts +1 -0
- package/server/dist/explorerDocs.js +4 -4
- package/server/dist/gitSnapshots.d.ts +1 -0
- package/server/dist/gitSnapshots.js +547 -83
- package/server/dist/http/clusterRoutes.js +9 -3
- package/server/dist/http/router.js +1 -0
- package/server/dist/providers/codexChatBoundary.js +6 -1
- package/server/dist/research/quickPromotion.d.ts +3 -0
- package/server/dist/research/quickPromotion.js +26 -9
- package/server/dist/research/savedQuickPromotion.js +2 -11
- package/server/dist/turnChanges.d.ts +1 -1
- package/server/dist/turnChanges.js +5 -4
- package/server/dist/ws/turnEngine.js +4 -1
- package/server/package.json +1 -1
- package/server/src/capabilities.ts +14 -4
- package/server/src/explorerDocs.ts +5 -5
- package/server/src/gitSnapshots.ts +538 -82
- package/server/src/http/clusterRoutes.ts +10 -3
- package/server/src/http/router.ts +1 -0
- package/server/src/providers/codexChatBoundary.ts +6 -1
- package/server/src/research/quickPromotion.ts +24 -6
- package/server/src/research/savedQuickPromotion.ts +2 -8
- package/server/src/turnChanges.ts +5 -4
- package/server/src/ws/turnEngine.ts +4 -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
|
|
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
|
|
275
|
+
const root = await gitCheckpointWorkTree(cwd, gitDir);
|
|
276
|
+
const protectedPaths = await providerHomePaths(root);
|
|
219
277
|
if (protectedPaths.includes('.')) return null;
|
|
220
|
-
const
|
|
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
|
-
|
|
225
|
-
|
|
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
|
-
//
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
233
|
-
|
|
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
|
-
|
|
237
|
-
|
|
238
|
-
|
|
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'],
|
|
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
|
-
...
|
|
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
|
|
272
|
-
if (
|
|
273
|
-
|
|
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
|
-
|
|
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
|
|
283
|
-
|
|
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).
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
620
|
-
//
|
|
621
|
-
await
|
|
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
|
|
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
|
-
|
|
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
|
|
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'],
|
|
790
|
-
if (headExists) {
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
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
|
|
804
|
-
//
|
|
805
|
-
//
|
|
806
|
-
//
|
|
807
|
-
//
|
|
808
|
-
const
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
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
|
-
|
|
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
|
-
|
|
889
|
-
|
|
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
|
-
//
|
|
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
|
|
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
|
|
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
|
|
1447
|
+
await releasePrepared(p);
|
|
992
1448
|
}
|
|
993
1449
|
}
|
|
994
1450
|
|