@mwillbanks/ast-mcp 0.6.3 → 0.6.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,733 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants, type Stats } from "node:fs";
3
+ import {
4
+ type FileHandle,
5
+ lstat,
6
+ link,
7
+ mkdir,
8
+ open,
9
+ readdir,
10
+ rmdir,
11
+ unlink,
12
+ } from "node:fs/promises";
13
+ import path from "node:path";
14
+
15
+ import {
16
+ currentWorkspace,
17
+ type WorkspaceHandle,
18
+ } from "../intelligence/workspace/context.ts";
19
+ import { sha256, sha256Handle } from "./hash.ts";
20
+ import {
21
+ ensurePrivateLockDirectory,
22
+ systemAccount,
23
+ } from "./private-lock-directory.ts";
24
+
25
+ export interface SnapshotBlob {
26
+ id: string;
27
+ sha256: string;
28
+ size: number;
29
+ }
30
+
31
+ export interface StagedFileSnapshot {
32
+ sourceBlob: SnapshotBlob;
33
+ namespace: string;
34
+ dev: number;
35
+ ino: number;
36
+ gid: number;
37
+ mode: number;
38
+ sha256: string;
39
+ uid: number;
40
+ }
41
+
42
+ const BLOB_ID = /^[1-9][0-9]*-[a-f0-9-]{36}$/;
43
+ const DIGEST = /^[a-f0-9]{64}$/;
44
+ const CHUNK_SIZE = 1024 * 1024;
45
+ const activeCaptures = new Set<string>();
46
+
47
+ function failure(code: string): Error {
48
+ return Object.assign(new Error(code), { code, retryable: false });
49
+ }
50
+
51
+ /** Close every descriptor even when another close fails. */
52
+ export async function closeSnapshotHandles(
53
+ handles: Iterable<FileHandle>,
54
+ ): Promise<void> {
55
+ const results = await Promise.allSettled(
56
+ [...handles].map((handle) => handle.close()),
57
+ );
58
+ const errors = results.flatMap((result) =>
59
+ result.status === "rejected" ? [result.reason] : [],
60
+ );
61
+ if (errors.length)
62
+ throw new AggregateError(errors, "Snapshot descriptor cleanup failed");
63
+ }
64
+
65
+ async function cleanupSnapshot(
66
+ primary: unknown[],
67
+ actions: Array<() => Promise<unknown>>,
68
+ ): Promise<void> {
69
+ const errors = [...primary];
70
+ for (const action of actions) {
71
+ try {
72
+ await action();
73
+ } catch (error) {
74
+ errors.push(error);
75
+ }
76
+ }
77
+ if (errors.length === primary.length) return;
78
+ if (errors.length === 1) throw errors[0];
79
+ throw new AggregateError(errors, "Snapshot operation and cleanup failed");
80
+ }
81
+
82
+ export function snapshotNamespace(
83
+ workspace: WorkspaceHandle | null = currentWorkspace() ?? null,
84
+ ): string {
85
+ return sha256(
86
+ workspace
87
+ ? JSON.stringify([
88
+ workspace.storageDomain.domainId,
89
+ workspace.checkoutRoot,
90
+ ])
91
+ : "unbound-file-operations",
92
+ );
93
+ }
94
+
95
+ async function privateDirectory(directory: string): Promise<boolean> {
96
+ const account = await systemAccount();
97
+ let created = false;
98
+ try {
99
+ await mkdir(directory, { mode: 0o700 });
100
+ created = true;
101
+ } catch (error) {
102
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
103
+ }
104
+ const metadata = await lstat(directory);
105
+ if (
106
+ !metadata.isDirectory() ||
107
+ metadata.isSymbolicLink() ||
108
+ (process.platform !== "win32" &&
109
+ (metadata.uid !== account.uid || (metadata.mode & 0o777) !== 0o700))
110
+ )
111
+ throw failure("mutation_snapshot_directory_unsafe");
112
+ if (created) {
113
+ await syncDirectory(directory);
114
+ await syncDirectory(path.dirname(directory));
115
+ }
116
+ return created;
117
+ }
118
+
119
+ async function snapshotRoot(namespace: string): Promise<string> {
120
+ if (!DIGEST.test(namespace))
121
+ throw failure("mutation_snapshot_namespace_invalid");
122
+ const account = await systemAccount();
123
+ const lockDirectory = await ensurePrivateLockDirectory(account);
124
+ const base = path.join(lockDirectory, "snapshots");
125
+ if (await privateDirectory(base))
126
+ await syncDirectory(path.dirname(lockDirectory));
127
+ const directory = path.join(base, namespace);
128
+ await privateDirectory(directory);
129
+ return directory;
130
+ }
131
+
132
+ async function blobDirectory(
133
+ blob: SnapshotBlob,
134
+ namespace: string,
135
+ ): Promise<string> {
136
+ if (
137
+ !BLOB_ID.test(blob.id) ||
138
+ !DIGEST.test(blob.sha256) ||
139
+ !Number.isSafeInteger(blob.size) ||
140
+ blob.size < 0
141
+ )
142
+ throw failure("mutation_snapshot_reference_invalid");
143
+ const directory = path.join(await snapshotRoot(namespace), blob.id);
144
+ const metadata = await lstat(directory);
145
+ const account = await systemAccount();
146
+ if (
147
+ !metadata.isDirectory() ||
148
+ metadata.isSymbolicLink() ||
149
+ (process.platform !== "win32" &&
150
+ (metadata.uid !== account.uid || (metadata.mode & 0o777) !== 0o700))
151
+ )
152
+ throw failure("mutation_snapshot_directory_unsafe");
153
+ return directory;
154
+ }
155
+
156
+ export async function syncDirectory(directory: string): Promise<void> {
157
+ // Windows has no portable directory fsync here; directory-entry power-loss durability is not guaranteed.
158
+ if (process.platform === "win32") return;
159
+ const handle = await open(
160
+ directory,
161
+ constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW,
162
+ );
163
+ try {
164
+ await handle.sync();
165
+ } finally {
166
+ await handle.close();
167
+ }
168
+ }
169
+
170
+ function unchanged(before: Stats, after: Stats): boolean {
171
+ return (
172
+ before.dev === after.dev &&
173
+ before.ino === after.ino &&
174
+ before.size === after.size &&
175
+ before.mtimeMs === after.mtimeMs &&
176
+ before.ctimeMs === after.ctimeMs
177
+ );
178
+ }
179
+
180
+ async function writeAll(
181
+ handle: FileHandle,
182
+ bytes: Buffer,
183
+ position: number,
184
+ ): Promise<void> {
185
+ let written = 0;
186
+ while (written < bytes.length) {
187
+ const result = await handle.write(
188
+ bytes,
189
+ written,
190
+ bytes.length - written,
191
+ position + written,
192
+ );
193
+ if (!result.bytesWritten) throw failure("mutation_snapshot_write_failed");
194
+ written += result.bytesWritten;
195
+ }
196
+ }
197
+
198
+ /** Capture one immutable rollback copy with bounded memory and a fresh digest. */
199
+ export async function stageFileSnapshot(
200
+ filePath: string,
201
+ signal?: AbortSignal,
202
+ ): Promise<StagedFileSnapshot> {
203
+ const readSignal = signal
204
+ ? AbortSignal.any([signal, AbortSignal.timeout(30_000)])
205
+ : AbortSignal.timeout(30_000);
206
+ readSignal.throwIfAborted();
207
+ const namespace = snapshotNamespace();
208
+ const root = await snapshotRoot(namespace);
209
+ if (!currentWorkspace()) await sweepSnapshotBlobs(namespace, new Set());
210
+ const id = `${process.pid}-${randomUUID()}`;
211
+ const directory = path.join(root, id);
212
+ await mkdir(directory, { mode: 0o700 });
213
+ activeCaptures.add(`${namespace}:${id}`);
214
+ const pending = path.join(directory, "pending");
215
+ let source: FileHandle | undefined;
216
+ let destination: FileHandle | undefined;
217
+ let succeeded = false;
218
+ const errors: unknown[] = [];
219
+ try {
220
+ source = await open(
221
+ filePath,
222
+ constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
223
+ );
224
+ const metadata = await source.stat();
225
+ if (!metadata.isFile()) throw failure("file_not_regular");
226
+ destination = await open(pending, "wx", 0o600);
227
+ const hash = createHash("sha256");
228
+ const buffer = Buffer.allocUnsafe(CHUNK_SIZE);
229
+ let position = 0;
230
+ for (;;) {
231
+ readSignal.throwIfAborted();
232
+ const { bytesRead } = await source.read(
233
+ buffer,
234
+ 0,
235
+ buffer.length,
236
+ position,
237
+ );
238
+ if (!bytesRead) break;
239
+ const bytes = buffer.subarray(0, bytesRead);
240
+ hash.update(bytes);
241
+ await writeAll(destination, bytes, position);
242
+ position += bytesRead;
243
+ }
244
+ readSignal.throwIfAborted();
245
+ const after = await source.stat();
246
+ const current = await lstat(filePath);
247
+ if (
248
+ !unchanged(metadata, after) ||
249
+ !unchanged(metadata, current) ||
250
+ position !== metadata.size ||
251
+ current.isSymbolicLink()
252
+ )
253
+ throw failure("stale_or_missing_hash");
254
+ const digest = hash.digest("hex");
255
+ await destination.sync();
256
+ await destination.close();
257
+ destination = undefined;
258
+ // Publication is a no-replace link, never a replace of existing recovery material.
259
+ await link(pending, path.join(directory, `${digest}.blob`));
260
+ await unlink(pending);
261
+ await syncDirectory(directory);
262
+ await syncDirectory(root);
263
+ await source.close();
264
+ source = undefined;
265
+ succeeded = true;
266
+ return {
267
+ sourceBlob: { id, sha256: digest, size: position },
268
+ namespace,
269
+ dev: metadata.dev,
270
+ ino: metadata.ino,
271
+ gid: metadata.gid,
272
+ mode: metadata.mode,
273
+ sha256: digest,
274
+ uid: metadata.uid,
275
+ };
276
+ } catch (error) {
277
+ errors.push(error);
278
+ throw error;
279
+ } finally {
280
+ await cleanupSnapshot(errors, [
281
+ async () => destination?.close(),
282
+ async () => source?.close(),
283
+ async () => {
284
+ if (succeeded) return;
285
+ activeCaptures.delete(`${namespace}:${id}`);
286
+ const entries = await readdir(directory);
287
+ await cleanupSnapshot(
288
+ [],
289
+ [
290
+ ...entries.map(
291
+ (entry) => () => unlink(path.join(directory, entry)),
292
+ ),
293
+ () => rmdir(directory),
294
+ ],
295
+ );
296
+ },
297
+ ]);
298
+ }
299
+ }
300
+
301
+ async function openSnapshotMaterial(
302
+ blob: SnapshotBlob,
303
+ namespace: string,
304
+ signal?: AbortSignal,
305
+ ): Promise<FileHandle> {
306
+ signal?.throwIfAborted();
307
+ const directory = await blobDirectory(blob, namespace);
308
+ const target = path.join(directory, `${blob.sha256}.blob`);
309
+ const handle = await open(
310
+ target,
311
+ constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
312
+ );
313
+ try {
314
+ const metadata = await handle.stat();
315
+ const current = await lstat(target);
316
+ const account = await systemAccount();
317
+ if (
318
+ current.isSymbolicLink() ||
319
+ !current.isFile() ||
320
+ !unchanged(metadata, current) ||
321
+ !metadata.isFile() ||
322
+ metadata.nlink !== 1 ||
323
+ metadata.size !== blob.size ||
324
+ (process.platform !== "win32" &&
325
+ (metadata.uid !== account.uid || (metadata.mode & 0o777) !== 0o600))
326
+ )
327
+ throw failure("mutation_snapshot_material_unsafe");
328
+ return handle;
329
+ } catch (error) {
330
+ await handle.close();
331
+ throw error;
332
+ }
333
+ }
334
+
335
+ /** Validate private identity and bounds for journaling, without reading payload bytes. */
336
+ export async function inspectSnapshotBlob(
337
+ blob: SnapshotBlob,
338
+ namespace: string,
339
+ signal?: AbortSignal,
340
+ ): Promise<void> {
341
+ const handle = await openSnapshotMaterial(blob, namespace, signal);
342
+ await handle.close();
343
+ }
344
+
345
+ /** Full material verification belongs after durable begin and before any target mutation. */
346
+ export async function openSnapshotBlob(
347
+ blob: SnapshotBlob,
348
+ namespace: string,
349
+ signal?: AbortSignal,
350
+ hashTimeoutMs?: number,
351
+ ): Promise<FileHandle> {
352
+ const handle = await openSnapshotMaterial(blob, namespace, signal);
353
+ try {
354
+ if ((await sha256Handle(handle, signal, hashTimeoutMs)) !== blob.sha256)
355
+ throw failure("mutation_recovery_material_mismatch");
356
+ return handle;
357
+ } catch (error) {
358
+ await handle.close();
359
+ throw error;
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Check current pathname identity before unlinking.
365
+ * A concurrent directory writer can still replace it between lstat and unlink.
366
+ */
367
+ export async function removeSnapshotTemporary(
368
+ filePath: string,
369
+ identity: { dev: number; ino: number },
370
+ ): Promise<void> {
371
+ const current = await lstat(filePath).catch(
372
+ (error: NodeJS.ErrnoException) => {
373
+ if (error.code === "ENOENT") return null;
374
+ throw error;
375
+ },
376
+ );
377
+ if (!current) return;
378
+ if (
379
+ current.isSymbolicLink() ||
380
+ current.dev !== identity.dev ||
381
+ current.ino !== identity.ino
382
+ )
383
+ throw failure("mutation_snapshot_temporary_replaced");
384
+ await unlink(filePath);
385
+ }
386
+
387
+ async function copyVerifiedBytes(
388
+ handle: FileHandle,
389
+ output: FileHandle,
390
+ blob: Pick<SnapshotBlob, "sha256" | "size">,
391
+ signal?: AbortSignal,
392
+ ): Promise<void> {
393
+ const hash = createHash("sha256");
394
+ const buffer = Buffer.allocUnsafe(CHUNK_SIZE);
395
+ let position = 0;
396
+ for (;;) {
397
+ signal?.throwIfAborted();
398
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
399
+ if (!bytesRead) break;
400
+ const bytes = buffer.subarray(0, bytesRead);
401
+ hash.update(bytes);
402
+ await writeAll(output, bytes, position);
403
+ position += bytesRead;
404
+ }
405
+ signal?.throwIfAborted();
406
+ if (position !== blob.size || hash.digest("hex") !== blob.sha256)
407
+ throw failure("mutation_recovery_material_mismatch");
408
+ }
409
+
410
+ /** Copy from the already verified descriptor, preserving its identity. */
411
+ export async function copySnapshotBlob(
412
+ handle: FileHandle,
413
+ destination: string,
414
+ blob: SnapshotBlob,
415
+ signal?: AbortSignal,
416
+ ): Promise<{ dev: number; ino: number }> {
417
+ const output = await open(destination, "wx", 0o600);
418
+ let identity: { dev: number; ino: number } | undefined;
419
+ let succeeded = false;
420
+ let closed = false;
421
+ const errors: unknown[] = [];
422
+ try {
423
+ identity = await output.stat();
424
+ await copyVerifiedBytes(handle, output, blob, signal);
425
+ await output.sync();
426
+ await output.close();
427
+ closed = true;
428
+ succeeded = true;
429
+ return { dev: identity.dev, ino: identity.ino };
430
+ } catch (error) {
431
+ errors.push(error);
432
+ throw error;
433
+ } finally {
434
+ await cleanupSnapshot(errors, [
435
+ async () => {
436
+ // Retry once while the owned descriptor remains open; unknown paths stay intact.
437
+ if (!succeeded && !identity) identity = await output.stat();
438
+ },
439
+ async () => {
440
+ if (!closed) await output.close();
441
+ },
442
+ async () => {
443
+ if (!succeeded && identity)
444
+ await removeSnapshotTemporary(destination, identity);
445
+ },
446
+ async () => {
447
+ if (!succeeded && identity)
448
+ await syncDirectory(path.dirname(destination));
449
+ },
450
+ ]);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * Link atomically when supported; otherwise copy to an exclusively created mode-0600 path.
456
+ * The fallback exposes a partial pathname while copying, but never replaces another entry.
457
+ * Returns the borrowed source on link, or a caller-owned writable descriptor on copy.
458
+ */
459
+ export async function publishSnapshotNoReplace(
460
+ temporary: string,
461
+ destination: string,
462
+ source: FileHandle,
463
+ expected: Pick<SnapshotBlob, "sha256" | "size">,
464
+ fence: (target?: FileHandle) => Promise<void>,
465
+ options: { signal?: AbortSignal; hashTimeoutMs?: number } = {},
466
+ ): Promise<FileHandle> {
467
+ let linkError: unknown;
468
+ try {
469
+ await link(temporary, destination);
470
+ return source;
471
+ } catch (error) {
472
+ const code = (error as NodeJS.ErrnoException).code;
473
+ if (
474
+ !["EXDEV", "ENOSYS", "ENOTSUP", "EOPNOTSUPP", "EPERM"].includes(
475
+ code ?? "",
476
+ )
477
+ )
478
+ throw error;
479
+ linkError = error;
480
+ }
481
+ let output: FileHandle | undefined;
482
+ let identity: { dev: number; ino: number } | undefined;
483
+ let succeeded = false;
484
+ const errors: unknown[] = [linkError];
485
+ try {
486
+ await fence();
487
+ options.signal?.throwIfAborted();
488
+ const metadata = await source.stat();
489
+ const staged = await lstat(temporary);
490
+ if (
491
+ !metadata.isFile() ||
492
+ staged.isSymbolicLink() ||
493
+ !unchanged(metadata, staged)
494
+ )
495
+ throw failure("mutation_recovery_material_mismatch");
496
+ output = await open(destination, "wx+", 0o600);
497
+ identity = await output.stat();
498
+ await copyVerifiedBytes(source, output, expected, options.signal);
499
+ // Persist complete bytes before broadening permissions or making the file readonly.
500
+ await output.sync();
501
+ await fence(output);
502
+ if (process.platform !== "win32")
503
+ await output.chown(metadata.uid, metadata.gid);
504
+ await output.chmod(metadata.mode);
505
+ const verified = await output.stat();
506
+ if (
507
+ (await sha256Handle(output, options.signal, options.hashTimeoutMs)) !==
508
+ expected.sha256
509
+ )
510
+ throw failure("mutation_recovery_material_mismatch");
511
+ await output.sync();
512
+ await fence(output);
513
+ options.signal?.throwIfAborted();
514
+ const held = await output.stat();
515
+ const current = await lstat(destination);
516
+ const sourceNow = await source.stat();
517
+ const stagedNow = await lstat(temporary);
518
+ if (
519
+ current.isSymbolicLink() ||
520
+ held.dev !== identity.dev ||
521
+ held.ino !== identity.ino ||
522
+ !unchanged(verified, held) ||
523
+ !unchanged(held, current) ||
524
+ (held.mode & 0o7777) !== (metadata.mode & 0o7777) ||
525
+ (process.platform !== "win32" &&
526
+ (held.uid !== metadata.uid || held.gid !== metadata.gid)) ||
527
+ !unchanged(metadata, sourceNow) ||
528
+ stagedNow.isSymbolicLink() ||
529
+ !unchanged(sourceNow, stagedNow)
530
+ )
531
+ throw failure("mutation_recovery_material_mismatch");
532
+ succeeded = true;
533
+ return output;
534
+ } catch (error) {
535
+ errors.push(error);
536
+ throw new AggregateError(errors, "Snapshot exclusive publication failed");
537
+ } finally {
538
+ if (!succeeded)
539
+ await cleanupSnapshot(errors, [
540
+ async () => {
541
+ if (output && !identity) identity = await output.stat();
542
+ },
543
+ async () => {
544
+ await output?.close();
545
+ },
546
+ async () => {
547
+ if (identity) await removeSnapshotTemporary(destination, identity);
548
+ },
549
+ async () => {
550
+ if (identity) await syncDirectory(path.dirname(destination));
551
+ },
552
+ ]);
553
+ }
554
+ }
555
+
556
+ /** Publish a restored file only after its complete bytes are durable and verified. */
557
+ export async function restoreSnapshotBlob(
558
+ snapshot: StagedFileSnapshot,
559
+ destination: string,
560
+ fence: () => Promise<void>,
561
+ ): Promise<void> {
562
+ const temporary = path.join(
563
+ path.dirname(destination),
564
+ `.${path.basename(destination)}.rollback-${randomUUID()}`,
565
+ );
566
+ const source = await openSnapshotBlob(
567
+ snapshot.sourceBlob,
568
+ snapshot.namespace,
569
+ );
570
+ let created = false;
571
+ let identity: { dev: number; ino: number } | undefined;
572
+ const errors: unknown[] = [];
573
+ try {
574
+ await fence();
575
+ identity = await copySnapshotBlob(source, temporary, snapshot.sourceBlob);
576
+ created = true;
577
+ const output = await open(
578
+ temporary,
579
+ (process.platform === "win32" ? constants.O_RDWR : constants.O_RDONLY) |
580
+ constants.O_NOFOLLOW,
581
+ );
582
+ const metadataErrors: unknown[] = [];
583
+ let published: FileHandle | undefined;
584
+ try {
585
+ const held = await output.stat();
586
+ const current = await lstat(temporary);
587
+ if (
588
+ current.isSymbolicLink() ||
589
+ !held.isFile() ||
590
+ held.dev !== identity.dev ||
591
+ held.ino !== identity.ino ||
592
+ !unchanged(held, current)
593
+ )
594
+ throw failure("mutation_recovery_material_mismatch");
595
+ await fence();
596
+ if (process.platform !== "win32")
597
+ await output.chown(snapshot.uid, snapshot.gid);
598
+ await output.chmod(snapshot.mode);
599
+ await output.sync();
600
+ await fence();
601
+ published = await publishSnapshotNoReplace(
602
+ temporary,
603
+ destination,
604
+ output,
605
+ snapshot.sourceBlob,
606
+ fence,
607
+ );
608
+ await syncDirectory(path.dirname(destination));
609
+ } catch (error) {
610
+ metadataErrors.push(error);
611
+ throw error;
612
+ } finally {
613
+ await cleanupSnapshot(metadataErrors, [
614
+ () => output.close(),
615
+ async () => {
616
+ if (published && published !== output) await published.close();
617
+ },
618
+ ]);
619
+ }
620
+ } catch (error) {
621
+ errors.push(error);
622
+ throw error;
623
+ } finally {
624
+ await cleanupSnapshot(errors, [
625
+ () => source.close(),
626
+ async () => {
627
+ if (created && identity)
628
+ await removeSnapshotTemporary(temporary, identity);
629
+ },
630
+ async () => {
631
+ if (created && errors.length)
632
+ await syncDirectory(path.dirname(destination));
633
+ },
634
+ ]);
635
+ }
636
+ }
637
+
638
+ export function releaseSnapshotCapture(
639
+ blob: SnapshotBlob,
640
+ namespace: string,
641
+ ): void {
642
+ activeCaptures.delete(`${namespace}:${blob.id}`);
643
+ }
644
+
645
+ export async function removeSnapshotBlob(
646
+ blob: SnapshotBlob,
647
+ namespace: string,
648
+ ): Promise<void> {
649
+ activeCaptures.delete(`${namespace}:${blob.id}`);
650
+ const directory = await blobDirectory(blob, namespace).catch(
651
+ (error: NodeJS.ErrnoException) => {
652
+ if (error.code === "ENOENT") return null;
653
+ throw error;
654
+ },
655
+ );
656
+ if (!directory) return;
657
+ await unlink(path.join(directory, `${blob.sha256}.blob`)).catch(
658
+ (error: NodeJS.ErrnoException) => {
659
+ if (error.code !== "ENOENT") throw error;
660
+ },
661
+ );
662
+ await rmdir(directory);
663
+ }
664
+
665
+ export class FileSnapshotCollection<
666
+ T extends StagedFileSnapshot = StagedFileSnapshot,
667
+ > extends Map<string, T> {
668
+ disposable = true;
669
+ async verify(signal?: AbortSignal): Promise<void> {
670
+ for (const snapshot of this.values()) {
671
+ const handle = await openSnapshotBlob(
672
+ snapshot.sourceBlob,
673
+ snapshot.namespace,
674
+ signal,
675
+ );
676
+ await handle.close();
677
+ }
678
+ }
679
+ async [Symbol.asyncDispose](): Promise<void> {
680
+ for (const snapshot of this.values()) {
681
+ activeCaptures.delete(`${snapshot.namespace}:${snapshot.sourceBlob.id}`);
682
+ if (this.disposable)
683
+ await removeSnapshotBlob(snapshot.sourceBlob, snapshot.namespace).catch(
684
+ () => undefined,
685
+ );
686
+ }
687
+ }
688
+ }
689
+
690
+ /** Only dead-process, old, unreferenced captures are garbage; live captures stay fenced. */
691
+ export async function sweepSnapshotBlobs(
692
+ namespace: string,
693
+ retained: ReadonlySet<string>,
694
+ now = Date.now(),
695
+ ): Promise<number> {
696
+ const root = await snapshotRoot(namespace);
697
+ let removed = 0;
698
+ for (const entry of await readdir(root, { withFileTypes: true })) {
699
+ if (
700
+ !BLOB_ID.test(entry.name) ||
701
+ retained.has(entry.name) ||
702
+ activeCaptures.has(`${namespace}:${entry.name}`)
703
+ )
704
+ continue;
705
+ if (!entry.isDirectory() || entry.isSymbolicLink())
706
+ throw failure("mutation_snapshot_directory_unsafe");
707
+ const directory = path.join(root, entry.name);
708
+ const metadata = await lstat(directory);
709
+ const owner = Number(entry.name.slice(0, entry.name.indexOf("-")));
710
+ if (owner !== process.pid) {
711
+ if (now - metadata.mtimeMs < 24 * 60 * 60 * 1000) continue;
712
+ try {
713
+ process.kill(owner, 0);
714
+ continue;
715
+ } catch (error) {
716
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") continue;
717
+ }
718
+ }
719
+ await privateDirectory(directory);
720
+ for (const child of await readdir(directory, { withFileTypes: true })) {
721
+ if (
722
+ !child.isFile() ||
723
+ child.isSymbolicLink() ||
724
+ (child.name !== "pending" && !/^[a-f0-9]{64}\.blob$/.test(child.name))
725
+ )
726
+ throw failure("mutation_snapshot_material_unsafe");
727
+ await unlink(path.join(directory, child.name));
728
+ }
729
+ await rmdir(directory);
730
+ removed++;
731
+ }
732
+ return removed;
733
+ }