@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.
@@ -1,3 +1,4 @@
1
+ import type { SnapshotBlob } from "../../runtime/snapshot-blob.ts";
1
2
  import type { WorkspaceHandle } from "../workspace/context.ts";
2
3
 
3
4
  export type MutationTool =
@@ -11,6 +12,7 @@ export interface MutationFilePlan {
11
12
  candidateSha256: string | null;
12
13
  filePath: string;
13
14
  sourceContentBase64?: string | null;
15
+ sourceBlob?: SnapshotBlob | null;
14
16
  sourceGid?: number | null;
15
17
  sourceMode?: number | null;
16
18
  sourceSha256: string | null;
@@ -3,10 +3,9 @@ import { randomUUID } from "node:crypto";
3
3
  import {
4
4
  chmod,
5
5
  lstat,
6
- mkdir,
7
- realpath,
6
+ open,
7
+ type FileHandle,
8
8
  rename,
9
- rmdir,
10
9
  unlink,
11
10
  writeFile,
12
11
  } from "node:fs/promises";
@@ -44,8 +43,17 @@ import {
44
43
  withFencedFileLock,
45
44
  withFencedFileLocks,
46
45
  } from "../runtime/locks";
46
+ import {
47
+ ensureParentDirectories,
48
+ removeCreatedDirectories,
49
+ revalidateWritePath,
50
+ } from "../runtime/parent-directories";
47
51
  import { resolveWritablePath } from "../runtime/paths";
48
52
  import { requireExpectedHash, verifyExpectedHash } from "../runtime/policy";
53
+ import {
54
+ FileSnapshotCollection,
55
+ stageFileSnapshot,
56
+ } from "../runtime/snapshot-blob";
49
57
  import {
50
58
  type AiderBlock,
51
59
  type AstRule,
@@ -110,38 +118,9 @@ function temporary(filePath: string): string {
110
118
  async function removeTemporary(filePath: string) {
111
119
  try {
112
120
  await unlink(filePath);
113
- } catch {}
114
- }
115
-
116
- async function ensureParent(filePath: string): Promise<string[]> {
117
- const parent = path.dirname(filePath);
118
- const first = await mkdir(parent, { recursive: true });
119
- const revalidated = await resolveWritablePath(filePath);
120
- if (revalidated !== filePath)
121
- throw new Error("Parent creation changed the resolved write path");
122
- if (!first) return [];
123
- // Recursive mkdir can return a different physical alias on Windows.
124
- const [canonicalFirst, canonicalParent] = await Promise.all([
125
- realpath(first),
126
- realpath(parent),
127
- ]);
128
- const relative = path.relative(canonicalFirst, canonicalParent);
129
- if (
130
- relative === ".." ||
131
- relative.startsWith(`..${path.sep}`) ||
132
- path.isAbsolute(relative)
133
- )
134
- throw new Error(
135
- "Created parent directory escaped its first created ancestor",
136
- );
137
- const created = [canonicalFirst];
138
- let current = canonicalFirst;
139
- for (const segment of relative.split(path.sep)) {
140
- if (!segment) continue;
141
- current = path.join(current, segment);
142
- created.push(current);
121
+ } catch (error) {
122
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
143
123
  }
144
- return created;
145
124
  }
146
125
 
147
126
  async function ignoreFailure(operation: Promise<unknown>): Promise<void> {
@@ -150,11 +129,6 @@ async function ignoreFailure(operation: Promise<unknown>): Promise<void> {
150
129
  } catch {}
151
130
  }
152
131
 
153
- async function removeCreatedDirectories(directories: string[]): Promise<void> {
154
- for (const directory of [...directories].reverse())
155
- await ignoreFailure(rmdir(directory));
156
- }
157
-
158
132
  async function commit(
159
133
  filePath: string,
160
134
  content: string,
@@ -169,24 +143,29 @@ async function commit(
169
143
  sha256: string;
170
144
  }> {
171
145
  const next = temporary(filePath);
172
- let createdDirectories: string[] = [];
146
+ const createdDirectories: string[] = [];
173
147
  let committed = false;
148
+ let output: FileHandle | undefined;
149
+ let temporaryCreated = false;
150
+ const primaryFailures: unknown[] = [];
174
151
  try {
175
- const parentExists = await lstat(path.dirname(filePath)).then(
176
- () => true,
177
- () => false,
178
- );
179
- createdDirectories = parentExists ? [] : await ensureParent(filePath);
152
+ await ensureParentDirectories(filePath, createdDirectories, beforeReplace);
180
153
  const formatted = alreadyFormatted
181
154
  ? content
182
155
  : await formatContent(filePath, content);
183
156
  await beforeReplace?.();
184
- await writeFile(next, formatted, { encoding: "utf8", flag: "wx", mode });
157
+ await revalidateWritePath(filePath);
158
+ output = await open(next, "wx", mode);
159
+ temporaryCreated = true;
160
+ await output.writeFile(formatted, { encoding: "utf8" });
185
161
  if (mode !== undefined) {
186
162
  await beforeReplace?.();
187
163
  await chmod(next, mode);
188
164
  }
189
165
  await applyFileChattr(next, chattr, beforeReplace);
166
+ await output.sync();
167
+ await output.close();
168
+ output = undefined;
190
169
  const committedChattr = await resultingFileChattr(next);
191
170
  const committedSha256 = sha256(formatted);
192
171
  if (expectedSha256) {
@@ -195,6 +174,7 @@ async function commit(
195
174
  verifyExpectedHash(expectedSha256, actual);
196
175
  }
197
176
  await beforeReplace?.();
177
+ await revalidateWritePath(filePath);
198
178
  await rename(next, filePath);
199
179
  committed = true;
200
180
  return {
@@ -202,9 +182,41 @@ async function commit(
202
182
  createdDirectories,
203
183
  sha256: committedSha256,
204
184
  };
185
+ } catch (error) {
186
+ primaryFailures.push(error);
187
+ throw error;
205
188
  } finally {
206
- await removeTemporary(next);
207
- if (!committed) await removeCreatedDirectories(createdDirectories);
189
+ const failures = [...primaryFailures];
190
+ const affectedPaths = new Set<string>();
191
+ try {
192
+ await output?.close();
193
+ } catch (error) {
194
+ failures.push(error);
195
+ affectedPaths.add(next);
196
+ }
197
+ try {
198
+ if (temporaryCreated) await removeTemporary(next);
199
+ } catch (error) {
200
+ failures.push(error);
201
+ affectedPaths.add(next);
202
+ }
203
+ if (!committed) {
204
+ try {
205
+ await removeCreatedDirectories(createdDirectories);
206
+ } catch (error) {
207
+ failures.push(error);
208
+ for (const directory of createdDirectories)
209
+ affectedPaths.add(directory);
210
+ }
211
+ }
212
+ if (failures.length > primaryFailures.length)
213
+ throw Object.assign(
214
+ new AggregateError(
215
+ failures,
216
+ "File write failed and cleanup was incomplete",
217
+ ),
218
+ { details: { affectedPaths: [...affectedPaths] } },
219
+ );
208
220
  }
209
221
  }
210
222
  function previewDiff(filePath: string, before: string, after: string): string {
@@ -295,6 +307,60 @@ const MAX_PREVIEW_SESSION_BYTES = 16 * 1024 * 1024;
295
307
  const MAX_PREVIEW_SESSION_RECEIPTS = 32;
296
308
  const previewReceipts = new Map<string, PreviewReceipt>();
297
309
  const expiredPreviewReceipts = new Set<string>();
310
+ const reservedPreviewReceipts = new Map<string, symbol>();
311
+ const previewReservation = new AsyncLocalStorage<symbol>();
312
+
313
+ interface ReceiptBatchState {
314
+ completed: boolean;
315
+ safeToRelease: boolean;
316
+ }
317
+
318
+ async function withReservedPreviewReceipts<T>(
319
+ requests: unknown[],
320
+ state: ReceiptBatchState,
321
+ operation: () => Promise<T>,
322
+ ): Promise<T> {
323
+ const owner = Symbol("patch receipt batch");
324
+ const tokens = requests.flatMap((request) => {
325
+ const token = (request as PatchBatchRequest).previewReceipt;
326
+ return typeof token === "string" ? [token] : [];
327
+ });
328
+ if (
329
+ new Set(tokens).size !== tokens.length ||
330
+ tokens.some((token) => reservedPreviewReceipts.has(token))
331
+ )
332
+ throw receiptError(
333
+ "preview_receipt_reserved",
334
+ "Preview receipt is already reserved by an active batch",
335
+ );
336
+ const receipts = tokens.map(
337
+ (token) => [token, previewReceipts.get(token)] as const,
338
+ );
339
+ for (const token of tokens) reservedPreviewReceipts.set(token, owner);
340
+ try {
341
+ return await previewReservation.run(owner, operation);
342
+ } finally {
343
+ for (const [token, receipt] of receipts) {
344
+ let reusable = state.safeToRelease && !state.completed;
345
+ if (receipt && reusable) {
346
+ try {
347
+ reusable = await patchSignals.run(
348
+ undefined,
349
+ async () =>
350
+ sha256(await readText(receipt.filePath)) === receipt.sourceSha256,
351
+ );
352
+ } catch {
353
+ reusable = false;
354
+ }
355
+ }
356
+ if (!reusable && receipt) {
357
+ clearTimeout(receipt.expiryTimer);
358
+ previewReceipts.delete(token);
359
+ }
360
+ reservedPreviewReceipts.delete(token);
361
+ }
362
+ }
363
+ }
298
364
 
299
365
  function expirePreviewReceipt(token: string): void {
300
366
  previewReceipts.delete(token);
@@ -343,6 +409,14 @@ function previewPayloadBytes(
343
409
  }
344
410
 
345
411
  async function validatePreviewReceipt(filePath: string, token: string) {
412
+ if (
413
+ reservedPreviewReceipts.has(token) &&
414
+ reservedPreviewReceipts.get(token) !== previewReservation.getStore()
415
+ )
416
+ throw receiptError(
417
+ "preview_receipt_reserved",
418
+ "Preview receipt is already reserved by an active batch",
419
+ );
346
420
  const receipt = previewReceipts.get(token);
347
421
  if (!receipt)
348
422
  throw receiptError(
@@ -649,11 +723,8 @@ async function applyPreparedPatch(
649
723
  prepared.candidate,
650
724
  await inspectFileCapabilities(filePath),
651
725
  );
652
- if (prepared.receiptToken) {
653
- const receipt = previewReceipts.get(prepared.receiptToken);
654
- if (receipt) clearTimeout(receipt.expiryTimer);
655
- previewReceipts.delete(prepared.receiptToken);
656
- }
726
+ if (prepared.receiptToken)
727
+ await validatePreviewReceipt(filePath, prepared.receiptToken);
657
728
  await commit(
658
729
  filePath,
659
730
  candidate,
@@ -699,20 +770,35 @@ async function preflightFileWrite(
699
770
  );
700
771
  mode = (await lstat(filePath)).mode;
701
772
  }
702
- const parentExists = await lstat(path.dirname(filePath)).then(
703
- () => true,
704
- () => false,
705
- );
706
- const createdDirectories = parentExists ? [] : await ensureParent(filePath);
773
+ const createdDirectories: string[] = [];
774
+ let primaryFailure: unknown;
707
775
  try {
776
+ await ensureParentDirectories(filePath, createdDirectories, async () =>
777
+ patchSignals.getStore()?.throwIfAborted(),
778
+ );
708
779
  return {
709
780
  actual,
710
781
  content: await formatContent(filePath, request.content),
711
782
  existing: existing !== undefined,
712
783
  mode,
713
784
  };
785
+ } catch (error) {
786
+ primaryFailure = error;
787
+ throw error;
714
788
  } finally {
715
- await removeCreatedDirectories(createdDirectories);
789
+ try {
790
+ await removeCreatedDirectories(createdDirectories);
791
+ } catch (cleanupError) {
792
+ throw Object.assign(
793
+ new AggregateError(
794
+ [primaryFailure, cleanupError],
795
+ "File write preflight failed and parent cleanup was incomplete",
796
+ ),
797
+ {
798
+ details: { affectedPaths: createdDirectories },
799
+ },
800
+ );
801
+ }
716
802
  }
717
803
  }
718
804
 
@@ -795,6 +881,7 @@ async function rollbackFileBatch(
795
881
  fence: () => Promise<void>,
796
882
  ): Promise<void> {
797
883
  const failures: unknown[] = [];
884
+ const affectedPaths: string[] = [];
798
885
  for (const { resolvedPath, result } of committed.reverse()) {
799
886
  const snapshot = snapshots.get(resolvedPath);
800
887
  try {
@@ -821,20 +908,26 @@ async function rollbackFileBatch(
821
908
  await unlink(resolvedPath);
822
909
  const createdDirectories = result.createdDirectories;
823
910
  if (Array.isArray(createdDirectories))
824
- await removeCreatedDirectories(
825
- createdDirectories.filter(
826
- (value): value is string => typeof value === "string",
827
- ),
828
- );
911
+ await removeCreatedDirectories(createdDirectories);
829
912
  } catch (error) {
830
- failures.push(error);
913
+ affectedPaths.push(resolvedPath);
914
+ failures.push(
915
+ Object.assign(new Error("File rollback failed", { cause: error }), {
916
+ details: { affectedPaths: [resolvedPath] },
917
+ }),
918
+ );
831
919
  }
832
920
  }
833
921
  if (failures.length > 0)
834
- throw new AggregateError(failures, "Mutation rollback requires recovery");
922
+ throw Object.assign(
923
+ new AggregateError(failures, "Mutation rollback requires recovery"),
924
+ {
925
+ details: { affectedPaths },
926
+ },
927
+ );
835
928
  }
836
929
 
837
- async function executePreparedFileBatch<T, Prepared>(
930
+ async function executeReservedFileBatch<T, Prepared>(
838
931
  tool: "file_patch" | "file_write",
839
932
  entries: ResolvedBatchEntry<T>[],
840
933
  handler: (
@@ -846,24 +939,32 @@ async function executePreparedFileBatch<T, Prepared>(
846
939
  preflight: (filePath: string, request: T) => Promise<Prepared>,
847
940
  mutates: (request: T) => boolean,
848
941
  fence: () => Promise<void>,
849
- signal?: AbortSignal,
942
+ signal: AbortSignal | undefined,
943
+ receiptState: ReceiptBatchState,
850
944
  ): Promise<Record<string, unknown>> {
851
945
  signal?.throwIfAborted();
946
+ await using durableSnapshots = new FileSnapshotCollection();
852
947
  const snapshots = await captureBatchSnapshots(entries);
853
948
  const prepared = await prepareFileBatch(entries, preflight);
854
949
  const files: Record<string, unknown> = {};
855
950
  const committed: CommittedBatchEntry[] = [];
856
951
  const workspace = currentWorkspace() ?? null;
857
952
  const plannedEntries = entries.filter((entry) => mutates(entry.request));
953
+ for (const entry of plannedEntries) {
954
+ const snapshot = snapshots.get(entry.resolvedPath);
955
+ if (!snapshot) continue;
956
+ const durable = await stageFileSnapshot(entry.resolvedPath, signal);
957
+ durableSnapshots.set(entry.resolvedPath, durable);
958
+ verifyExpectedHash(sha256(snapshot.content), durable.sha256);
959
+ }
858
960
  const sourcePlan = plannedEntries.map((entry) => {
859
961
  const entryIndex = entries.indexOf(entry);
860
962
  const snapshot = snapshots.get(entry.resolvedPath);
861
963
  return {
862
964
  candidateSha256: preparedCandidateSha256(prepared[entryIndex]),
863
965
  filePath: entry.resolvedPath,
864
- sourceContentBase64: snapshot
865
- ? Buffer.from(snapshot.content).toString("base64")
866
- : null,
966
+ sourceContentBase64: null,
967
+ sourceBlob: durableSnapshots.get(entry.resolvedPath)?.sourceBlob ?? null,
867
968
  sourceGid:
868
969
  process.platform === "win32"
869
970
  ? null
@@ -888,6 +989,8 @@ async function executePreparedFileBatch<T, Prepared>(
888
989
  try {
889
990
  signal?.throwIfAborted();
890
991
  if (plannedEntries.length > 0) {
992
+ receiptState.safeToRelease = false;
993
+ durableSnapshots.disposable = false;
891
994
  await beginMutation({
892
995
  files: sourcePlan,
893
996
  operationId,
@@ -895,6 +998,7 @@ async function executePreparedFileBatch<T, Prepared>(
895
998
  workspace,
896
999
  });
897
1000
  began = true;
1001
+ await durableSnapshots.verify(signal);
898
1002
  }
899
1003
  for (const [
900
1004
  index,
@@ -931,6 +1035,8 @@ async function executePreparedFileBatch<T, Prepared>(
931
1035
  began && commits.length > 0
932
1036
  ? await completeMutation(operationId, commits)
933
1037
  : null;
1038
+ durableSnapshots.disposable = true;
1039
+ receiptState.completed = true;
934
1040
  return intelligenceRefresh ? { files, intelligenceRefresh } : { files };
935
1041
  } catch (error) {
936
1042
  discardPreparedPreviews(prepared);
@@ -939,11 +1045,23 @@ async function executePreparedFileBatch<T, Prepared>(
939
1045
  await patchSignals.run(undefined, () =>
940
1046
  rollbackFileBatch(committed, snapshots, fence),
941
1047
  );
942
- if (began) await ignoreFailure(recordMutationRollback(operationId));
1048
+ if (began) {
1049
+ await recordMutationRollback(operationId);
1050
+ durableSnapshots.disposable = true;
1051
+ }
1052
+ // A failed begin can leave an uncertain journal even without file commits.
1053
+ receiptState.safeToRelease = began || receiptState.safeToRelease;
943
1054
  } catch (rollbackError) {
944
- throw new AggregateError(
945
- [error, rollbackError],
946
- "Mutation failed and rollback requires recovery",
1055
+ throw Object.assign(
1056
+ new AggregateError(
1057
+ [error, rollbackError],
1058
+ "Mutation failed and rollback requires recovery",
1059
+ ),
1060
+ {
1061
+ details: {
1062
+ affectedPaths: committed.map(({ resolvedPath }) => resolvedPath),
1063
+ },
1064
+ },
947
1065
  );
948
1066
  }
949
1067
  throw error;
@@ -976,19 +1094,29 @@ async function processFileBatch<T, Prepared>(
976
1094
  resolvedPath: await resolveWritablePath(inputPath),
977
1095
  })),
978
1096
  );
1097
+ const receiptState: ReceiptBatchState = {
1098
+ completed: false,
1099
+ safeToRelease: true,
1100
+ };
979
1101
  return withFencedFileLocks(
980
1102
  resolvedEntries.map(({ resolvedPath }) => resolvedPath),
981
1103
  (leases: readonly FileLockLease[]) =>
982
- executePreparedFileBatch(
983
- tool,
984
- resolvedEntries,
985
- handler,
986
- preflight,
987
- mutates,
988
- async () => {
989
- for (const lease of leases) await lease.fence();
990
- },
991
- options.signal,
1104
+ withReservedPreviewReceipts(
1105
+ resolvedEntries.map(({ request }) => request),
1106
+ receiptState,
1107
+ () =>
1108
+ executeReservedFileBatch(
1109
+ tool,
1110
+ resolvedEntries,
1111
+ handler,
1112
+ preflight,
1113
+ mutates,
1114
+ async () => {
1115
+ for (const lease of leases) await lease.fence();
1116
+ },
1117
+ options.signal,
1118
+ receiptState,
1119
+ ),
992
1120
  ),
993
1121
  { ...options, deadline: options.deadline ?? Date.now() + 10_000 },
994
1122
  );