@mwillbanks/ast-mcp 0.6.4 → 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.
@@ -1,21 +1,28 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import {
3
- chmod,
4
- chown,
5
- lstat,
6
- rename,
7
- unlink,
8
- writeFile,
9
- } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open, type FileHandle, rename, unlink } from "node:fs/promises";
10
4
  import path from "node:path";
11
5
 
12
- import { sha256 } from "../../runtime/hash.ts";
6
+ import { sha256, sha256Handle } from "../../runtime/hash.ts";
13
7
  import { withFileLock, withFileLocks } from "../../runtime/locks.ts";
14
8
  import { canonicalizePath, pathWithin } from "../../runtime/path-utils.ts";
15
9
  import {
16
10
  ensurePrivateLockDirectory as ensureMutationLockDirectory,
17
11
  systemAccount,
18
12
  } from "../../runtime/private-lock-directory.ts";
13
+ import {
14
+ openSnapshotBlob,
15
+ inspectSnapshotBlob,
16
+ closeSnapshotHandles,
17
+ copySnapshotBlob,
18
+ publishSnapshotNoReplace,
19
+ releaseSnapshotCapture,
20
+ removeSnapshotBlob,
21
+ removeSnapshotTemporary,
22
+ snapshotNamespace,
23
+ sweepSnapshotBlobs,
24
+ syncDirectory,
25
+ } from "../../runtime/snapshot-blob.ts";
19
26
  import { createIdentity } from "../contracts/common.ts";
20
27
  import { ParserWorkerPool } from "../parser/pool.ts";
21
28
  import { LanceIntelligenceStore } from "../storage/store.ts";
@@ -32,6 +39,7 @@ import type {
32
39
  MutationBatchPlan,
33
40
  MutationFileCommit,
34
41
  MutationJournalRecord,
42
+ MutationJournalFile,
35
43
  MutationLifecycle,
36
44
  MutationRefreshResult,
37
45
  } from "./types.ts";
@@ -53,7 +61,14 @@ export function mutationOperationId(input: {
53
61
  workspaceId: string;
54
62
  }): string {
55
63
  return createIdentity("job", {
56
- operationId: createIdentity("mutation-operation", input),
64
+ operationId: createIdentity("mutation-operation", {
65
+ ...input,
66
+ files: input.files.map(({ candidateSha256, filePath, sourceSha256 }) => ({
67
+ candidateSha256,
68
+ filePath,
69
+ sourceSha256,
70
+ })),
71
+ }),
57
72
  storageDomainId: input.storageDomainId,
58
73
  workspaceId: input.workspaceId,
59
74
  });
@@ -62,9 +77,26 @@ export function mutationOperationId(input: {
62
77
  async function assertRecoveryPath(
63
78
  workspace: WorkspaceHandle,
64
79
  filePath: string,
80
+ retained?: FileHandle,
65
81
  ): Promise<void> {
66
82
  const canonicalRoot = await canonicalizePath(workspace.checkoutRoot);
67
- const canonicalTarget = await canonicalizePath(filePath);
83
+ let canonicalTarget: string;
84
+ if (retained) {
85
+ const held = await retained.stat();
86
+ const current = await lstat(filePath);
87
+ if (
88
+ !held.isFile() ||
89
+ current.isSymbolicLink() ||
90
+ held.dev !== current.dev ||
91
+ held.ino !== current.ino
92
+ )
93
+ throw new Error("mutation_recovery_hash_mismatch");
94
+ // macOS realpath requires read permission on mode-zero regular files.
95
+ canonicalTarget = path.join(
96
+ await canonicalizePath(path.dirname(filePath)),
97
+ path.basename(filePath),
98
+ );
99
+ } else canonicalTarget = await canonicalizePath(filePath);
68
100
  if (
69
101
  path.relative(canonicalRoot, canonicalTarget) === "" ||
70
102
  !pathWithin(canonicalRoot, canonicalTarget)
@@ -72,6 +104,258 @@ async function assertRecoveryPath(
72
104
  throw new Error("mutation_path_outside_workspace");
73
105
  }
74
106
 
107
+ function remainingRecoveryBudget(deadline?: Date | number): number | undefined {
108
+ if (deadline === undefined) return undefined;
109
+ const absolute = deadline instanceof Date ? deadline.getTime() : deadline;
110
+ if (!Number.isFinite(absolute))
111
+ throw new RangeError("Invalid recovery deadline");
112
+ const remaining = Math.ceil(absolute - Date.now());
113
+ if (remaining <= 0)
114
+ throw new DOMException(
115
+ "Mutation recovery deadline exceeded",
116
+ "TimeoutError",
117
+ );
118
+ return Math.min(remaining, 0xffffffff);
119
+ }
120
+
121
+ async function hashRecoveryFile(
122
+ filePath: string,
123
+ signal?: AbortSignal,
124
+ retained?: FileHandle,
125
+ hashTimeoutMs?: number,
126
+ ): Promise<string> {
127
+ const handle =
128
+ retained ??
129
+ (await open(
130
+ filePath,
131
+ constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
132
+ ));
133
+ try {
134
+ const before = await handle.stat();
135
+ if (!before.isFile()) throw new Error("mutation_recovery_hash_mismatch");
136
+ const digest = await sha256Handle(handle, signal, hashTimeoutMs);
137
+ const after = await handle.stat();
138
+ const current = await lstat(filePath);
139
+ if (
140
+ before.dev !== current.dev ||
141
+ before.ino !== current.ino ||
142
+ current.isSymbolicLink() ||
143
+ before.size !== after.size ||
144
+ before.mtimeMs !== after.mtimeMs ||
145
+ before.ctimeMs !== after.ctimeMs
146
+ )
147
+ throw new Error("mutation_recovery_hash_mismatch");
148
+ return digest;
149
+ } finally {
150
+ if (!retained) await handle.close();
151
+ }
152
+ }
153
+
154
+ interface NamespaceOnlyRename {
155
+ rollback: boolean;
156
+ signal?: AbortSignal;
157
+ deadline?: Date | number;
158
+ }
159
+
160
+ async function syncMutationFile(
161
+ filePath: string,
162
+ readonlySource?: { mode: number; sha256: string },
163
+ options?: NamespaceOnlyRename,
164
+ ): Promise<void> {
165
+ let handle: FileHandle;
166
+ let readonly = false;
167
+ try {
168
+ handle = await open(
169
+ filePath,
170
+ (process.platform === "win32" ? constants.O_RDWR : constants.O_RDONLY) |
171
+ constants.O_NONBLOCK |
172
+ constants.O_NOFOLLOW,
173
+ );
174
+ } catch (error) {
175
+ const code = (error as NodeJS.ErrnoException).code;
176
+ if (
177
+ process.platform !== "win32" ||
178
+ !readonlySource ||
179
+ (code !== "EACCES" && code !== "EPERM")
180
+ )
181
+ throw error;
182
+ const current = await lstat(filePath);
183
+ if (
184
+ current.isSymbolicLink() ||
185
+ (current.mode & 0o200) !== 0 ||
186
+ (current.mode & 0o7777) !== readonlySource.mode
187
+ )
188
+ throw error;
189
+ handle = await open(
190
+ filePath,
191
+ constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW,
192
+ );
193
+ readonly = true;
194
+ }
195
+ try {
196
+ const held = await handle.stat();
197
+ const current = await lstat(filePath);
198
+ if (
199
+ !held.isFile() ||
200
+ current.isSymbolicLink() ||
201
+ held.dev !== current.dev ||
202
+ held.ino !== current.ino
203
+ )
204
+ throw new Error("mutation_recovery_hash_mismatch");
205
+ if (readonly) {
206
+ if (
207
+ (held.mode & 0o200) !== 0 ||
208
+ (held.mode & 0o7777) !== readonlySource!.mode ||
209
+ (current.mode & 0o7777) !== readonlySource!.mode ||
210
+ (await hashRecoveryFile(
211
+ filePath,
212
+ options?.signal,
213
+ handle,
214
+ remainingRecoveryBudget(options?.deadline),
215
+ )) !== readonlySource!.sha256 ||
216
+ ((await handle.stat()).mode & 0o7777) !== readonlySource!.mode
217
+ )
218
+ throw new Error("mutation_recovery_hash_mismatch");
219
+ // Rename changed directory entries only; these readonly bytes and mode match the journal.
220
+ } else await handle.sync();
221
+ } finally {
222
+ await handle.close();
223
+ }
224
+ }
225
+ /** Include created directory entries, without syncing unchanged ancestors. */
226
+ async function mutationDirectories(
227
+ files: readonly { filePath: string }[],
228
+ fence: () => Promise<void>,
229
+ ): Promise<Set<string>> {
230
+ const directories = new Set<string>();
231
+ for (const { filePath } of files) {
232
+ let directory = await canonicalizePath(path.dirname(filePath));
233
+ for (;;) {
234
+ await fence();
235
+ directories.add(directory);
236
+ try {
237
+ await lstat(directory);
238
+ break;
239
+ } catch (error) {
240
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
241
+ const parent = path.dirname(directory);
242
+ if (parent === directory) throw error;
243
+ directory = parent;
244
+ }
245
+ }
246
+ }
247
+ return directories;
248
+ }
249
+
250
+ async function syncMutationPaths(
251
+ workspace: WorkspaceHandle,
252
+ files: MutationBatchPlan["files"],
253
+ fence: () => Promise<void>,
254
+ requireCheckout = true,
255
+ syncFiles = true,
256
+ capturedDirectories: ReadonlySet<string> = new Set(),
257
+ namespaceRename?: NamespaceOnlyRename,
258
+ ): Promise<void> {
259
+ const directories = await mutationDirectories(files, fence);
260
+ for (const directory of capturedDirectories) directories.add(directory);
261
+ const root = await canonicalizePath(workspace.checkoutRoot);
262
+ for (const [index, file] of files.entries()) {
263
+ const { filePath } = file;
264
+ await fence();
265
+ let readonlySource: { mode: number; sha256: string } | undefined;
266
+ if (namespaceRename) {
267
+ const source = namespaceRename.rollback ? file : files[index - 1];
268
+ const digest = namespaceRename.rollback
269
+ ? file.sourceSha256
270
+ : file.candidateSha256;
271
+ // The rename producer journals adjacent source/destination pairs.
272
+ if (
273
+ source &&
274
+ digest &&
275
+ source.sourceSha256 === digest &&
276
+ source.sourceMode != null &&
277
+ (namespaceRename.rollback ||
278
+ (source.filePath !== filePath &&
279
+ source.candidateSha256 === null &&
280
+ file.sourceSha256 === null))
281
+ )
282
+ readonlySource = { mode: source.sourceMode & 0o7777, sha256: digest };
283
+ }
284
+ if (syncFiles)
285
+ await syncMutationFile(filePath, readonlySource, namespaceRename).catch(
286
+ (error: NodeJS.ErrnoException) => {
287
+ if (error.code !== "ENOENT") throw error;
288
+ },
289
+ );
290
+ const directory = await canonicalizePath(path.dirname(filePath));
291
+ const withinCheckout = directory === root || pathWithin(root, directory);
292
+ if (requireCheckout && !withinCheckout)
293
+ throw new Error("mutation_path_outside_workspace");
294
+ }
295
+ for (const directory of [...directories].sort(
296
+ (a, b) => b.length - a.length,
297
+ )) {
298
+ await fence();
299
+ await syncDirectory(directory).catch((error: NodeJS.ErrnoException) => {
300
+ if (error.code !== "ENOENT") throw error;
301
+ });
302
+ }
303
+ }
304
+
305
+ class RecoveryMaterials extends Map<string, FileHandle> {
306
+ readonly targets = new Map<string, FileHandle>();
307
+ readonly extraTargets = new Set<FileHandle>();
308
+ readonly cleanReadonly = new Set<string>();
309
+ readonly inline = new Map<string, Buffer>();
310
+ constructor(readonly namespace: string) {
311
+ super();
312
+ }
313
+ async prepare(
314
+ file: MutationJournalFile,
315
+ signal?: AbortSignal,
316
+ hashTimeoutMs?: number,
317
+ ): Promise<void> {
318
+ signal?.throwIfAborted();
319
+ if (file.sourceBlob) {
320
+ if (file.sourceBlob.sha256 !== file.sourceSha256)
321
+ throw new Error("mutation_recovery_material_mismatch");
322
+ this.set(
323
+ file.filePath,
324
+ await openSnapshotBlob(
325
+ file.sourceBlob,
326
+ this.namespace,
327
+ signal,
328
+ hashTimeoutMs,
329
+ ),
330
+ );
331
+ } else if (file.sourceContentBase64 !== null) {
332
+ const source = Buffer.from(file.sourceContentBase64, "base64");
333
+ if (sha256(source) !== file.sourceSha256)
334
+ throw new Error("mutation_recovery_material_mismatch");
335
+ this.inline.set(file.filePath, source);
336
+ } else if (file.sourceSha256 !== null) {
337
+ throw new Error("mutation_recovery_material_missing");
338
+ }
339
+ }
340
+ async [Symbol.asyncDispose](): Promise<void> {
341
+ try {
342
+ await closeSnapshotHandles(
343
+ new Set([
344
+ ...this.values(),
345
+ ...this.targets.values(),
346
+ ...this.extraTargets,
347
+ ]),
348
+ );
349
+ } finally {
350
+ this.clear();
351
+ this.targets.clear();
352
+ this.extraTargets.clear();
353
+ this.cleanReadonly.clear();
354
+ this.inline.clear();
355
+ }
356
+ }
357
+ }
358
+
75
359
  async function restoreMutationRecord(
76
360
  workspace: WorkspaceHandle,
77
361
  record: MutationJournalRecord,
@@ -81,6 +365,16 @@ async function restoreMutationRecord(
81
365
  signal?: AbortSignal;
82
366
  } = {},
83
367
  ): Promise<void> {
368
+ const remaining = remainingRecoveryBudget(options.deadline);
369
+ if (remaining !== undefined) {
370
+ const deadlineSignal = AbortSignal.timeout(remaining);
371
+ options = {
372
+ ...options,
373
+ signal: options.signal
374
+ ? AbortSignal.any([options.signal, deadlineSignal])
375
+ : deadlineSignal,
376
+ };
377
+ }
84
378
  for (const file of record.files) {
85
379
  await assertRecoveryPath(workspace, file.filePath);
86
380
  if (
@@ -96,10 +390,38 @@ async function restoreMutationRecord(
96
390
  await options.fence?.();
97
391
  for (const lease of leases) await lease.fence();
98
392
  };
99
- const fencePath = async (filePath: string) => {
393
+ const fencePath = async (filePath: string, retained?: FileHandle) => {
100
394
  await fence();
101
- await assertRecoveryPath(workspace, filePath);
395
+ await assertRecoveryPath(workspace, filePath, retained);
102
396
  };
397
+ const hashTimeout = () => remainingRecoveryBudget(options.deadline);
398
+ const recoveryHash = (
399
+ filePath: string,
400
+ signal?: AbortSignal,
401
+ retained?: FileHandle,
402
+ ) => hashRecoveryFile(filePath, signal, retained, hashTimeout());
403
+ await using materials = new RecoveryMaterials(
404
+ snapshotNamespace(workspace),
405
+ );
406
+ const directories = await mutationDirectories(record.files, fence);
407
+ // Validate every source and current target before the first recovery write.
408
+ for (const file of record.files) {
409
+ await materials.prepare(file, options.signal, hashTimeout());
410
+ await assertRecoveryPath(workspace, file.filePath);
411
+ const actual = await recoveryHash(file.filePath, options.signal).catch(
412
+ (error: NodeJS.ErrnoException) => {
413
+ if (error.code === "ENOENT") return null;
414
+ throw error;
415
+ },
416
+ );
417
+ if (
418
+ actual !== null &&
419
+ actual !== file.sourceSha256 &&
420
+ actual !== file.candidateSha256 &&
421
+ actual !== file.committedSha256
422
+ )
423
+ throw new Error("mutation_recovery_hash_mismatch");
424
+ }
103
425
  for (const file of record.files) {
104
426
  await assertRecoveryPath(workspace, file.filePath);
105
427
  const exists = await lstat(file.filePath).then(
@@ -110,9 +432,9 @@ async function restoreMutationRecord(
110
432
  throw error;
111
433
  },
112
434
  );
113
- if (file.sourceContentBase64 === null) {
435
+ if (file.sourceSha256 === null) {
114
436
  if (!exists) continue;
115
- const actual = sha256(await Bun.file(file.filePath).bytes());
437
+ const actual = await recoveryHash(file.filePath, options.signal);
116
438
  if (
117
439
  actual !== file.candidateSha256 &&
118
440
  actual !== file.committedSha256
@@ -122,20 +444,79 @@ async function restoreMutationRecord(
122
444
  await unlink(file.filePath);
123
445
  continue;
124
446
  }
125
- const source = Buffer.from(file.sourceContentBase64, "base64");
126
- if (sha256(source) !== file.sourceSha256)
127
- throw new Error("mutation_recovery_material_mismatch");
447
+ const source = materials.inline.get(file.filePath);
448
+ let expectedCurrent: string | null = null;
128
449
  if (exists) {
129
- const actual = sha256(await Bun.file(file.filePath).bytes());
450
+ const actual = await recoveryHash(file.filePath, options.signal);
451
+ expectedCurrent = actual;
130
452
  if (actual === file.sourceSha256) {
453
+ const readonlyWindows =
454
+ process.platform === "win32" &&
455
+ ((await lstat(file.filePath)).mode & 0o200) === 0;
456
+ let handle = await open(
457
+ file.filePath,
458
+ (process.platform === "win32" && !readonlyWindows
459
+ ? constants.O_RDWR
460
+ : constants.O_RDONLY) |
461
+ constants.O_NONBLOCK |
462
+ constants.O_NOFOLLOW,
463
+ );
464
+ materials.targets.set(file.filePath, handle);
465
+ if (
466
+ (await recoveryHash(file.filePath, options.signal, handle)) !==
467
+ file.sourceSha256
468
+ )
469
+ throw new Error("mutation_recovery_hash_mismatch");
470
+ if (readonlyWindows) {
471
+ const metadata = await handle.stat();
472
+ const stillReadonly = (metadata.mode & 0o200) === 0;
473
+ if (
474
+ stillReadonly &&
475
+ (file.sourceMode === null ||
476
+ (metadata.mode & 0o7777) === (file.sourceMode & 0o7777)) &&
477
+ (file.sourceUid === null || metadata.uid === file.sourceUid) &&
478
+ (file.sourceGid === null || metadata.gid === file.sourceGid)
479
+ ) {
480
+ // No recovery change needs flushing; retain identity through final verification.
481
+ materials.cleanReadonly.add(file.filePath);
482
+ continue;
483
+ }
484
+ await fencePath(file.filePath, handle);
485
+ if (stillReadonly) {
486
+ if (file.sourceMode === null || (file.sourceMode & 0o200) === 0)
487
+ throw new Error("mutation_recovery_metadata_unflushable");
488
+ await handle.chmod(file.sourceMode);
489
+ }
490
+ const writable = await open(
491
+ file.filePath,
492
+ constants.O_RDWR | constants.O_NONBLOCK | constants.O_NOFOLLOW,
493
+ );
494
+ materials.extraTargets.add(writable);
495
+ await fencePath(file.filePath, handle);
496
+ const opened = await writable.stat();
497
+ if (
498
+ opened.dev !== metadata.dev ||
499
+ opened.ino !== metadata.ino ||
500
+ (await recoveryHash(
501
+ file.filePath,
502
+ options.signal,
503
+ writable,
504
+ )) !== file.sourceSha256
505
+ )
506
+ throw new Error("mutation_recovery_hash_mismatch");
507
+ materials.extraTargets.add(handle);
508
+ materials.targets.set(file.filePath, writable);
509
+ handle = writable;
510
+ }
131
511
  if (file.sourceUid !== null && file.sourceGid !== null) {
132
512
  await fencePath(file.filePath);
133
- await chown(file.filePath, file.sourceUid, file.sourceGid);
513
+ await handle.chown(file.sourceUid, file.sourceGid);
134
514
  }
135
515
  if (file.sourceMode !== null) {
136
516
  await fencePath(file.filePath);
137
- await chmod(file.filePath, file.sourceMode);
517
+ await handle.chmod(file.sourceMode);
138
518
  }
519
+ await handle.sync();
139
520
  continue;
140
521
  }
141
522
  if (
@@ -149,31 +530,122 @@ async function restoreMutationRecord(
149
530
  `.${path.basename(file.filePath)}.recovery-${randomUUID()}`,
150
531
  );
151
532
  await fencePath(temporary);
152
- await writeFile(temporary, source, {
153
- flag: "wx",
154
- mode:
155
- process.platform === "win32"
156
- ? undefined
157
- : (file.sourceMode ?? undefined),
158
- });
533
+ let temporaryCreated = false;
534
+ let temporaryIdentity: { dev: number; ino: number } | undefined;
535
+ const restorationErrors: unknown[] = [];
159
536
  try {
537
+ let output: FileHandle;
538
+ if (file.sourceBlob) {
539
+ const identity = await copySnapshotBlob(
540
+ materials.get(file.filePath)!,
541
+ temporary,
542
+ file.sourceBlob,
543
+ options.signal,
544
+ );
545
+ temporaryCreated = true;
546
+ temporaryIdentity = identity;
547
+ output = await open(
548
+ temporary,
549
+ (process.platform === "win32"
550
+ ? constants.O_RDWR
551
+ : constants.O_RDONLY) | constants.O_NOFOLLOW,
552
+ );
553
+ materials.targets.set(file.filePath, output);
554
+ const actual = await output.stat();
555
+ if (actual.dev !== identity.dev || actual.ino !== identity.ino)
556
+ throw new Error("mutation_recovery_hash_mismatch");
557
+ } else {
558
+ output = await open(temporary, "wx+", 0o600);
559
+ temporaryCreated = true;
560
+ materials.targets.set(file.filePath, output);
561
+ temporaryIdentity = await output.stat();
562
+ await output.writeFile(source!);
563
+ await output.sync();
564
+ }
160
565
  if (file.sourceUid !== null && file.sourceGid !== null) {
161
566
  await fencePath(temporary);
162
- await chown(temporary, file.sourceUid, file.sourceGid);
567
+ await output.chown(file.sourceUid, file.sourceGid);
163
568
  }
164
569
  if (file.sourceMode !== null) {
165
570
  await fencePath(temporary);
166
- await chmod(temporary, file.sourceMode);
571
+ await output.chmod(file.sourceMode);
167
572
  }
573
+ await fencePath(temporary, output);
574
+ await output.sync();
168
575
  await fencePath(file.filePath);
169
- await assertRecoveryPath(workspace, temporary);
170
- await rename(temporary, file.filePath);
576
+ await assertRecoveryPath(workspace, temporary, output);
577
+ const actualBeforeReplace = await recoveryHash(
578
+ file.filePath,
579
+ options.signal,
580
+ ).catch((error: NodeJS.ErrnoException) => {
581
+ if (error.code === "ENOENT") return null;
582
+ throw error;
583
+ });
584
+ if (actualBeforeReplace !== expectedCurrent)
585
+ throw new Error("mutation_recovery_hash_mismatch");
586
+ await fencePath(file.filePath);
587
+ const held = await output.stat();
588
+ const published = await lstat(temporary);
589
+ if (
590
+ published.isSymbolicLink() ||
591
+ held.dev !== published.dev ||
592
+ held.ino !== published.ino
593
+ )
594
+ throw new Error("mutation_recovery_hash_mismatch");
595
+ if (expectedCurrent === null) {
596
+ const target = await publishSnapshotNoReplace(
597
+ temporary,
598
+ file.filePath,
599
+ output,
600
+ { sha256: file.sourceSha256, size: held.size },
601
+ async (retained) => {
602
+ await fencePath(file.filePath, retained);
603
+ await assertRecoveryPath(workspace, temporary, output);
604
+ },
605
+ {
606
+ signal: options.signal,
607
+ hashTimeoutMs: remainingRecoveryBudget(options.deadline),
608
+ },
609
+ );
610
+ if (target !== output) {
611
+ materials.extraTargets.add(output);
612
+ materials.targets.set(file.filePath, target);
613
+ }
614
+ } else {
615
+ await rename(temporary, file.filePath);
616
+ }
617
+ } catch (error) {
618
+ restorationErrors.push(error);
619
+ throw error;
171
620
  } finally {
172
- await unlink(temporary).catch(() => undefined);
621
+ const failures = [...restorationErrors];
622
+ if (temporaryCreated && temporaryIdentity) {
623
+ try {
624
+ await removeSnapshotTemporary(temporary, temporaryIdentity);
625
+ } catch (error) {
626
+ failures.push(error);
627
+ }
628
+ if (restorationErrors.length) {
629
+ try {
630
+ await syncDirectory(path.dirname(temporary));
631
+ } catch (error) {
632
+ failures.push(error);
633
+ }
634
+ }
635
+ }
636
+ if (failures.length > restorationErrors.length)
637
+ throw new AggregateError(
638
+ failures,
639
+ "Mutation recovery temporary cleanup failed",
640
+ );
173
641
  }
174
642
  }
175
643
  for (const file of record.files) {
176
- await assertRecoveryPath(workspace, file.filePath);
644
+ await assertRecoveryPath(
645
+ workspace,
646
+ file.filePath,
647
+ materials.targets.get(file.filePath),
648
+ );
177
649
  const exists = await lstat(file.filePath).then(
178
650
  () => true,
179
651
  () => false,
@@ -183,9 +655,11 @@ async function restoreMutationRecord(
183
655
  } else {
184
656
  if (!exists) throw new Error("mutation_recovery_verification_failed");
185
657
  const [actual, metadata] = await Promise.all([
186
- Bun.file(file.filePath)
187
- .bytes()
188
- .then((content) => sha256(content)),
658
+ recoveryHash(
659
+ file.filePath,
660
+ options.signal,
661
+ materials.targets.get(file.filePath),
662
+ ),
189
663
  lstat(file.filePath),
190
664
  ]);
191
665
  if (
@@ -196,8 +670,18 @@ async function restoreMutationRecord(
196
670
  (file.sourceGid !== null && metadata.gid !== file.sourceGid)
197
671
  )
198
672
  throw new Error("mutation_recovery_verification_failed");
673
+ if (!materials.cleanReadonly.has(file.filePath))
674
+ await materials.targets.get(file.filePath)!.sync();
199
675
  }
200
676
  }
677
+ await syncMutationPaths(
678
+ workspace,
679
+ record.files,
680
+ fence,
681
+ true,
682
+ false,
683
+ directories,
684
+ );
201
685
  },
202
686
  {
203
687
  deadline: options.deadline ?? Date.now() + 10_000,
@@ -209,6 +693,7 @@ async function restoreMutationRecord(
209
693
  export class LanceMutationLifecycle implements MutationLifecycle {
210
694
  readonly journal: LanceMutationJournal;
211
695
  readonly #plans = new Map<string, MutationBatchPlan>();
696
+ readonly #directories = new Map<string, ReadonlySet<string>>();
212
697
 
213
698
  constructor(
214
699
  private readonly store: LanceIntelligenceStore,
@@ -227,16 +712,37 @@ export class LanceMutationLifecycle implements MutationLifecycle {
227
712
  async recover(): Promise<void> {
228
713
  await this.options.fence?.();
229
714
  const checkoutRoot = await canonicalizePath(this.workspace.checkoutRoot);
230
- await this.journal.recover(
715
+ const recovered = await this.journal.recover(
231
716
  this.workspace.workspaceId,
232
717
  (record) => restoreMutationRecord(this.workspace, record, this.options),
233
718
  checkoutRoot,
234
719
  );
235
- if (
236
- (await this.journal.unfinished(this.workspace.workspaceId, checkoutRoot))
237
- .length > 0
238
- )
239
- throw new Error("mutation_recovery_required");
720
+ for (const operationId of recovered) {
721
+ this.#plans.delete(operationId);
722
+ this.#directories.delete(operationId);
723
+ const record = await this.journal.get(operationId);
724
+ for (const file of record?.files ?? [])
725
+ if (file.sourceBlob)
726
+ await removeSnapshotBlob(
727
+ file.sourceBlob,
728
+ snapshotNamespace(this.workspace),
729
+ ).catch(() => undefined);
730
+ }
731
+ const unfinished = await this.journal.unfinished(
732
+ this.workspace.workspaceId,
733
+ checkoutRoot,
734
+ );
735
+ await sweepSnapshotBlobs(
736
+ snapshotNamespace(this.workspace),
737
+ new Set(
738
+ unfinished.flatMap((record) =>
739
+ record.files.flatMap((file) =>
740
+ file.sourceBlob ? [file.sourceBlob.id] : [],
741
+ ),
742
+ ),
743
+ ),
744
+ );
745
+ if (unfinished.length > 0) throw new Error("mutation_recovery_required");
240
746
  }
241
747
 
242
748
  async begin(plan: MutationBatchPlan): Promise<void> {
@@ -252,8 +758,28 @@ export class LanceMutationLifecycle implements MutationLifecycle {
252
758
  throw new Error("mutation_workspace_mismatch");
253
759
  if (!this.workspace.writeEligibility.eligible)
254
760
  throw new Error("workspace_read_only");
255
- this.#plans.set(plan.operationId, plan);
761
+ // Begin only journals. Producers fully verify all captured bytes after begin,
762
+ // before changing any target, so a durable rollback owner exists on failure.
763
+ for (const file of plan.files)
764
+ if (file.sourceBlob)
765
+ await inspectSnapshotBlob(
766
+ file.sourceBlob,
767
+ snapshotNamespace(this.workspace),
768
+ this.options.signal,
769
+ );
770
+ const directories = await mutationDirectories(plan.files, async () => {
771
+ this.options.signal?.throwIfAborted();
772
+ await this.options.fence?.();
773
+ });
256
774
  await this.journal.begin(plan);
775
+ this.#directories.set(plan.operationId, directories);
776
+ for (const file of plan.files)
777
+ if (file.sourceBlob)
778
+ releaseSnapshotCapture(
779
+ file.sourceBlob,
780
+ snapshotNamespace(this.workspace),
781
+ );
782
+ this.#plans.set(plan.operationId, plan);
257
783
  }
258
784
 
259
785
  async committed(
@@ -300,8 +826,27 @@ export class LanceMutationLifecycle implements MutationLifecycle {
300
826
  });
301
827
  signal.throwIfAborted();
302
828
  await this.options.fence?.();
829
+ await syncMutationPaths(
830
+ this.workspace,
831
+ plan.files,
832
+ async () => {
833
+ await this.options.fence?.();
834
+ },
835
+ false,
836
+ // Attribute and text producers sync retained descriptors before closing.
837
+ !["file_chattr", "file_patch", "file_write"].includes(plan.tool),
838
+ this.#directories.get(operationId),
839
+ plan.tool === "file_rename"
840
+ ? {
841
+ rollback: false,
842
+ signal: this.options.signal,
843
+ deadline: this.options.deadline,
844
+ }
845
+ : undefined,
846
+ );
303
847
  await this.journal.transition(operationId, "succeeded");
304
848
  this.#plans.delete(operationId);
849
+ this.#directories.delete(operationId);
305
850
  return result;
306
851
  } catch (error) {
307
852
  const failure =
@@ -322,13 +867,36 @@ export class LanceMutationLifecycle implements MutationLifecycle {
322
867
 
323
868
  async failed(operationId: string, error: unknown): Promise<void> {
324
869
  if (!this.#plans.has(operationId)) return;
325
- await this.journal.transition(operationId, "failed", errorCode(error));
870
+ await this.journal.transition(
871
+ operationId,
872
+ "recovery-required",
873
+ errorCode(error),
874
+ );
326
875
  }
327
876
 
328
877
  async rolledBack(operationId: string): Promise<void> {
329
- if (!this.#plans.has(operationId)) return;
878
+ const plan = this.#plans.get(operationId);
879
+ if (!plan) return;
880
+ await syncMutationPaths(
881
+ this.workspace,
882
+ plan.files,
883
+ async () => {
884
+ await this.options.fence?.();
885
+ },
886
+ false,
887
+ !["file_chattr", "file_patch", "file_write"].includes(plan.tool),
888
+ this.#directories.get(operationId),
889
+ plan.tool === "file_rename"
890
+ ? {
891
+ rollback: true,
892
+ signal: this.options.signal,
893
+ deadline: this.options.deadline,
894
+ }
895
+ : undefined,
896
+ );
330
897
  await this.journal.transition(operationId, "rolled-back");
331
898
  this.#plans.delete(operationId);
899
+ this.#directories.delete(operationId);
332
900
  }
333
901
  }
334
902