@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 { createHash } from "node:crypto";
1
2
  import { createReadStream } from "node:fs";
2
3
  import { readFile, stat } from "node:fs/promises";
3
4
  import path from "node:path";
@@ -20,7 +21,7 @@ import {
20
21
  type FileReadMode,
21
22
  inspectFileCapabilities,
22
23
  } from "./file-capabilities";
23
- import { sha256, sha256File } from "./hash";
24
+ import { FILE_HASH_CHUNK_BYTES, sha256, sha256File } from "./hash";
24
25
  import { resolveWritablePath } from "./paths";
25
26
 
26
27
  const FILE_READ_DEFAULT_LINES = [0, 100] as const;
@@ -219,7 +220,12 @@ class LineRangeCollector {
219
220
 
220
221
  function bufferLineCount(content: Buffer) {
221
222
  let count = 0;
222
- for (const byte of content) if (byte === 10) count += 1;
223
+ for (
224
+ let newline = content.indexOf(10);
225
+ newline >= 0;
226
+ newline = content.indexOf(10, newline + 1)
227
+ )
228
+ count += 1;
223
229
  if (content.length > 0 && content.at(-1) !== 10) count += 1;
224
230
  return count;
225
231
  }
@@ -233,16 +239,31 @@ async function readLineRange(
233
239
  ) {
234
240
  signal.throwIfAborted();
235
241
  const collector = new LineRangeCollector(lines, maxBytes);
236
- const stream = createReadStream(filePath, { signal });
242
+ const hash = createHash("sha256");
243
+ const stream = createReadStream(filePath, {
244
+ highWaterMark: FILE_HASH_CHUNK_BYTES,
245
+ signal,
246
+ });
247
+ let collecting = true;
248
+ let rangeBytesRead = 0;
237
249
  try {
238
250
  for await (const raw of stream) {
251
+ signal.throwIfAborted();
239
252
  const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
240
- if (collector.consume(chunk)) break;
253
+ hash.update(chunk);
254
+ if (collecting) {
255
+ rangeBytesRead += chunk.length;
256
+ if (collector.consume(chunk)) collecting = false;
257
+ }
241
258
  }
259
+ signal.throwIfAborted();
260
+ return {
261
+ ...collector.result(fileSize, rangeBytesRead),
262
+ sha256: hash.digest("hex"),
263
+ };
242
264
  } finally {
243
265
  stream.destroy();
244
266
  }
245
- return collector.result(fileSize, stream.bytesRead);
246
267
  }
247
268
 
248
269
  export async function readWorkspaceRevisionBytes(
@@ -519,11 +540,11 @@ async function readFileWithSignal(
519
540
  await readDocumentAst(resolved, size, request.selectors, "");
520
541
  const resolvedMode = resolveReadMode(requestedMode, capabilities);
521
542
  assertReadMode(resolved, requestedMode, resolvedMode, capabilities);
522
- const digest = historicalBytes
523
- ? sha256(historicalBytes)
524
- : await sha256File(resolved, signal);
525
- signal.throwIfAborted();
526
543
  if (resolvedMode === "ast") {
544
+ const digest = historicalBytes
545
+ ? sha256(historicalBytes)
546
+ : await sha256File(resolved, signal);
547
+ signal.throwIfAborted();
527
548
  const ast = await readAst(
528
549
  request,
529
550
  resolved,
@@ -553,7 +574,10 @@ async function readFileWithSignal(
553
574
  ? (() => {
554
575
  const collector = new LineRangeCollector(lines, maxBytes);
555
576
  collector.consume(historicalBytes);
556
- return collector.result(size, size);
577
+ return {
578
+ ...collector.result(size, size),
579
+ sha256: sha256(historicalBytes),
580
+ };
557
581
  })()
558
582
  : await readLineRange(resolved, size, lines, maxBytes, signal);
559
583
  return {
@@ -562,7 +586,6 @@ async function readFileWithSignal(
562
586
  filePath: resolved,
563
587
  requestedMode,
564
588
  resolvedMode,
565
- sha256: digest,
566
589
  size,
567
590
  };
568
591
  }
@@ -12,11 +12,16 @@ import {
12
12
  recordMutationRollback,
13
13
  } from "../intelligence/mutation/index.ts";
14
14
  import { currentWorkspace } from "../intelligence/workspace/context.ts";
15
- import { readFileSnapshot } from "./file-snapshot";
16
15
  import { sha256File } from "./hash";
17
16
  import { withFileLocks } from "./locks";
17
+ import {
18
+ ensureParentDirectories,
19
+ removeCreatedDirectories,
20
+ revalidateWritePath,
21
+ } from "./parent-directories";
18
22
  import { pathsShareRoot, resolveWritablePath } from "./paths";
19
23
  import { requireExpectedHash, verifyExpectedHash } from "./policy";
24
+ import { stageFileSnapshot, FileSnapshotCollection } from "./snapshot-blob";
20
25
 
21
26
  export interface FileRenameRequest {
22
27
  destination: string;
@@ -43,6 +48,35 @@ function sourceHashFor(hashes: ReadonlyMap<string, string>, filePath: string) {
43
48
  return value;
44
49
  }
45
50
 
51
+ function renameFailure(error: unknown): Error {
52
+ const code = (error as NodeJS.ErrnoException)?.code;
53
+ const message =
54
+ code === "ENOENT"
55
+ ? "file_rename source or destination parent is missing"
56
+ : code === "EACCES" || code === "EPERM"
57
+ ? "file_rename filesystem permission denied"
58
+ : code === "EEXIST"
59
+ ? "file_rename destination already exists"
60
+ : code === "EXDEV" ||
61
+ code === "ENOTSUP" ||
62
+ code === "EOPNOTSUPP" ||
63
+ code === "ENOSYS"
64
+ ? "file_rename requires hard-link support between source and destination filesystems"
65
+ : "file_rename filesystem link operation failed";
66
+ return Object.assign(new Error(message, { cause: error }), {
67
+ code: typeof code === "string" ? code : "file_rename_link_failed",
68
+ retryable: code === "ENOENT",
69
+ });
70
+ }
71
+
72
+ async function revalidateEntry(entry: RenameEntry): Promise<void> {
73
+ if ((await resolveWritablePath(entry.filePath, "delete")) !== entry.filePath)
74
+ throw Object.assign(new Error("file_rename source path changed"), {
75
+ code: "mutation_path_changed",
76
+ });
77
+ await revalidateWritePath(entry.destinationPath);
78
+ }
79
+
46
80
  async function verifyLinkCapability(
47
81
  entries: RenameEntry[],
48
82
  fence: () => Promise<void>,
@@ -54,8 +88,10 @@ async function verifyLinkCapability(
54
88
  );
55
89
  let linkError: unknown;
56
90
  let created = false;
91
+ await fence();
92
+ await revalidateEntry(entry);
93
+ await revalidateWritePath(probe);
57
94
  try {
58
- await fence();
59
95
  await link(entry.filePath, probe);
60
96
  created = true;
61
97
  } catch (error) {
@@ -66,16 +102,20 @@ async function verifyLinkCapability(
66
102
  await fence();
67
103
  await unlink(probe);
68
104
  } catch (cleanupError) {
69
- throw new AggregateError(
70
- [cleanupError],
71
- `file_rename probe cleanup failed; residual probe: ${probe}`,
105
+ throw Object.assign(
106
+ new AggregateError(
107
+ [cleanupError],
108
+ `file_rename probe cleanup failed; residual probe: ${probe}`,
109
+ ),
110
+ {
111
+ details: {
112
+ affectedPaths: [entry.filePath, entry.destinationPath, probe],
113
+ },
114
+ },
72
115
  );
73
116
  }
74
117
  }
75
- if (linkError)
76
- throw new Error(
77
- `file_rename requires hard-link support between source and destination filesystems: ${String(linkError)}`,
78
- );
118
+ if (linkError) throw renameFailure(linkError);
79
119
  }
80
120
  }
81
121
 
@@ -85,6 +125,7 @@ async function rollbackMovedFiles(
85
125
  sourceHashes: ReadonlyMap<string, string>,
86
126
  ): Promise<void> {
87
127
  const rollbackErrors: unknown[] = [];
128
+ const affectedPaths: string[] = [];
88
129
  for (const entry of [...entries].reverse()) {
89
130
  try {
90
131
  await fence();
@@ -100,13 +141,19 @@ async function rollbackMovedFiles(
100
141
  );
101
142
  await unlink(entry.destinationPath);
102
143
  } catch (error) {
103
- rollbackErrors.push(error);
144
+ const paths = [entry.filePath, entry.destinationPath];
145
+ affectedPaths.push(...paths);
146
+ rollbackErrors.push(
147
+ Object.assign(new Error("Rename rollback failed", { cause: error }), {
148
+ details: { affectedPaths: paths },
149
+ }),
150
+ );
104
151
  }
105
152
  }
106
153
  if (rollbackErrors.length > 0)
107
- throw new AggregateError(
108
- rollbackErrors,
109
- "file_rename rollback was incomplete",
154
+ throw Object.assign(
155
+ new AggregateError(rollbackErrors, "file_rename rollback was incomplete"),
156
+ { details: { affectedPaths } },
110
157
  );
111
158
  }
112
159
 
@@ -124,11 +171,25 @@ async function moveFilesWithRollback(
124
171
  signal?.throwIfAborted();
125
172
  await fence();
126
173
  signal?.throwIfAborted();
127
- await link(entry.filePath, entry.destinationPath);
174
+ await revalidateEntry(entry);
175
+ verifyExpectedHash(
176
+ sourceHashFor(sourceHashes, entry.filePath),
177
+ await sha256File(entry.filePath),
178
+ );
179
+ try {
180
+ await link(entry.filePath, entry.destinationPath);
181
+ } catch (error) {
182
+ throw renameFailure(error);
183
+ }
128
184
  try {
129
185
  await linked(entry);
130
186
  await fence();
131
187
  signal?.throwIfAborted();
188
+ await revalidateEntry(entry);
189
+ verifyExpectedHash(
190
+ sourceHashFor(sourceHashes, entry.filePath),
191
+ await sha256File(entry.filePath),
192
+ );
132
193
  await unlink(entry.filePath);
133
194
  } catch (error) {
134
195
  await fence();
@@ -139,9 +200,16 @@ async function moveFilesWithRollback(
139
200
  );
140
201
  await unlink(entry.destinationPath);
141
202
  })().catch((cleanupError) => {
142
- throw new AggregateError(
143
- [error, cleanupError],
144
- "file_rename failed while cleaning up the current destination",
203
+ throw Object.assign(
204
+ new AggregateError(
205
+ [error, cleanupError],
206
+ "file_rename failed while cleaning up the current destination",
207
+ ),
208
+ {
209
+ details: {
210
+ affectedPaths: [entry.filePath, entry.destinationPath],
211
+ },
212
+ },
145
213
  );
146
214
  });
147
215
  throw error;
@@ -195,10 +263,17 @@ export async function renameFilesSafely(
195
263
  throw new Error(
196
264
  `file_rename source and destination must share a root: ${inputPath}`,
197
265
  );
198
- if (await lstat(destinationPath).catch(() => undefined))
199
- throw new Error(
200
- `file_rename destination already exists: ${request.destination}`,
266
+ try {
267
+ await lstat(destinationPath);
268
+ throw Object.assign(
269
+ new Error(
270
+ `file_rename destination already exists: ${request.destination}`,
271
+ ),
272
+ { code: "EEXIST" },
201
273
  );
274
+ } catch (error) {
275
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
276
+ }
202
277
  return { destinationPath, filePath, request } satisfies RenameEntry;
203
278
  }),
204
279
  );
@@ -224,16 +299,12 @@ export async function renameFilesSafely(
224
299
  const fence = async () => {
225
300
  for (const lease of leases) await lease.fence();
226
301
  };
227
- await verifyLinkCapability(entries, fence);
228
- const sourceSnapshots = new Map<
229
- string,
230
- Awaited<ReturnType<typeof readFileSnapshot>>
231
- >();
302
+ await using sourceSnapshots = new FileSnapshotCollection();
232
303
  for (const { filePath, request } of entries) {
233
- const snapshot = await readFileSnapshot(filePath, signal);
234
304
  await requireExpectedHash(request.expectedSha256, "file_rename");
235
- verifyExpectedHash(request.expectedSha256, snapshot.sha256);
305
+ const snapshot = await stageFileSnapshot(filePath, signal);
236
306
  sourceSnapshots.set(filePath, snapshot);
307
+ verifyExpectedHash(request.expectedSha256, snapshot.sha256);
237
308
  }
238
309
  const sourceHashes = new Map(
239
310
  [...sourceSnapshots].map(([filePath, snapshot]) => [
@@ -249,7 +320,8 @@ export async function renameFilesSafely(
249
320
  {
250
321
  candidateSha256: null,
251
322
  filePath,
252
- sourceContentBase64: snapshot?.content.toString("base64") ?? null,
323
+ sourceContentBase64: null,
324
+ sourceBlob: snapshot?.sourceBlob ?? null,
253
325
  sourceGid:
254
326
  process.platform === "win32" ? null : (snapshot?.gid ?? null),
255
327
  sourceMode: snapshot?.mode ?? null,
@@ -278,8 +350,12 @@ export async function renameFilesSafely(
278
350
  : randomUUID();
279
351
  let began = false;
280
352
  let moved = false;
353
+ let completed = false;
354
+ let primaryFailure: unknown;
355
+ const createdDirectories: string[] = [];
281
356
  try {
282
357
  signal?.throwIfAborted();
358
+ sourceSnapshots.disposable = false;
283
359
  await beginMutation({
284
360
  files: sourcePlan,
285
361
  operationId,
@@ -287,6 +363,18 @@ export async function renameFilesSafely(
287
363
  workspace,
288
364
  });
289
365
  began = true;
366
+ await sourceSnapshots.verify(signal);
367
+ for (const entry of entries) {
368
+ await ensureParentDirectories(
369
+ entry.destinationPath,
370
+ createdDirectories,
371
+ async () => {
372
+ signal?.throwIfAborted();
373
+ await fence();
374
+ },
375
+ );
376
+ }
377
+ await verifyLinkCapability(entries, fence);
290
378
  const files = await moveFilesWithRollback(
291
379
  entries,
292
380
  fence,
@@ -328,8 +416,11 @@ export async function renameFilesSafely(
328
416
  operationId,
329
417
  commits,
330
418
  );
419
+ completed = true;
420
+ sourceSnapshots.disposable = true;
331
421
  return intelligenceRefresh ? { files, intelligenceRefresh } : { files };
332
422
  } catch (error) {
423
+ primaryFailure = error;
333
424
  if (began) await ignoreFailure(failMutation(operationId, error));
334
425
  if (moved) {
335
426
  try {
@@ -354,9 +445,29 @@ export async function renameFilesSafely(
354
445
  ),
355
446
  ]),
356
447
  );
357
- if (began && restored.every(Boolean))
358
- await ignoreFailure(recordMutationRollback(operationId));
448
+ if (began && restored.every(Boolean)) {
449
+ try {
450
+ await recordMutationRollback(operationId);
451
+ sourceSnapshots.disposable = true;
452
+ } catch {}
453
+ }
359
454
  throw error;
455
+ } finally {
456
+ if (!completed) {
457
+ try {
458
+ await removeCreatedDirectories(createdDirectories);
459
+ } catch (cleanupError) {
460
+ throw Object.assign(
461
+ new AggregateError(
462
+ [primaryFailure, cleanupError],
463
+ "file_rename failed and parent cleanup was incomplete",
464
+ ),
465
+ {
466
+ details: { affectedPaths: createdDirectories },
467
+ },
468
+ );
469
+ }
470
+ }
360
471
  }
361
472
  },
362
473
  { signal },
@@ -1,9 +1,47 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { createReadStream } from "node:fs";
3
+ import type { FileHandle } from "node:fs/promises";
4
+
5
+ export const FILE_HASH_CHUNK_BYTES = 1024 * 1024;
3
6
  export function sha256(content: string | Uint8Array): string {
4
7
  return createHash("sha256").update(content).digest("hex");
5
8
  }
6
9
 
10
+ /**
11
+ * Hash an open regular file without closing it or changing its read position.
12
+ * The caller owns descriptor identity and metadata consistency checks.
13
+ * Cancellation and timeout are cooperative at completed I/O boundaries.
14
+ * Pending reads must settle before rejection; the caller can then reuse or close
15
+ * the handle safely. The timeout uses AbortSignal.timeout argument semantics.
16
+ */
17
+ export async function sha256Handle(
18
+ handle: FileHandle,
19
+ signal?: AbortSignal,
20
+ timeoutMs = 30_000,
21
+ ): Promise<string> {
22
+ const deadline = AbortSignal.timeout(timeoutMs);
23
+ const readSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
24
+ readSignal.throwIfAborted();
25
+ const metadata = await handle.stat();
26
+ readSignal.throwIfAborted();
27
+ if (!metadata.isFile())
28
+ throw Object.assign(new Error("Hashing requires a regular file"), {
29
+ code: "file_not_regular",
30
+ retryable: false,
31
+ });
32
+ const hash = createHash("sha256");
33
+ const buffer = Buffer.allocUnsafe(FILE_HASH_CHUNK_BYTES);
34
+ let position = 0;
35
+ while (true) {
36
+ readSignal.throwIfAborted();
37
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
38
+ readSignal.throwIfAborted();
39
+ if (bytesRead === 0) return hash.digest("hex");
40
+ hash.update(buffer.subarray(0, bytesRead));
41
+ position += bytesRead;
42
+ }
43
+ }
44
+
7
45
  export async function sha256File(
8
46
  filePath: string,
9
47
  signal?: AbortSignal,
@@ -12,7 +50,10 @@ export async function sha256File(
12
50
  const readSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
13
51
  readSignal.throwIfAborted();
14
52
  const hash = createHash("sha256");
15
- const stream = createReadStream(filePath, { signal: readSignal });
53
+ const stream = createReadStream(filePath, {
54
+ highWaterMark: FILE_HASH_CHUNK_BYTES,
55
+ signal: readSignal,
56
+ });
16
57
  try {
17
58
  for await (const chunk of stream) {
18
59
  readSignal.throwIfAborted();
@@ -0,0 +1,114 @@
1
+ import { lstat, mkdir, rmdir } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { resolveWritablePath } from "./paths";
5
+
6
+ type DirectoryIdentity = { dev: number; ino: number };
7
+ const ownership = new WeakMap<
8
+ readonly string[],
9
+ Map<string, DirectoryIdentity>
10
+ >();
11
+
12
+ export async function revalidateWritePath(filePath: string): Promise<void> {
13
+ if ((await resolveWritablePath(filePath)) !== filePath)
14
+ throw Object.assign(
15
+ new Error("Parent directory changed the resolved write path"),
16
+ {
17
+ code: "mutation_path_changed",
18
+ retryable: true,
19
+ },
20
+ );
21
+ }
22
+
23
+ /** The caller owns the ledger even when creation or later validation fails. */
24
+ export async function ensureParentDirectories(
25
+ filePath: string,
26
+ created: string[],
27
+ beforeSideEffect?: () => Promise<void>,
28
+ ): Promise<void> {
29
+ let identities = ownership.get(created);
30
+ if (!identities) {
31
+ identities = new Map();
32
+ ownership.set(created, identities);
33
+ }
34
+ const missing: string[] = [];
35
+ let directory = path.dirname(filePath);
36
+ for (;;) {
37
+ try {
38
+ const metadata = await lstat(directory);
39
+ if (!metadata.isDirectory())
40
+ throw Object.assign(
41
+ new Error("Destination parent is not a directory"),
42
+ {
43
+ code: "ENOTDIR",
44
+ },
45
+ );
46
+ break;
47
+ } catch (error) {
48
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
49
+ missing.push(directory);
50
+ const parent = path.dirname(directory);
51
+ if (parent === directory) throw error;
52
+ directory = parent;
53
+ }
54
+ }
55
+ for (const candidate of missing.reverse()) {
56
+ await beforeSideEffect?.();
57
+ await revalidateWritePath(filePath);
58
+ await revalidateWritePath(candidate);
59
+ try {
60
+ await mkdir(candidate);
61
+ } catch (error) {
62
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
63
+ const metadata = await lstat(candidate);
64
+ if (!metadata.isDirectory()) throw error;
65
+ await revalidateWritePath(filePath);
66
+ continue;
67
+ }
68
+ // Capture ownership before any policy, cancellation, or physical-path recheck.
69
+ created.push(candidate);
70
+ const metadata = await lstat(candidate);
71
+ identities.set(candidate, { dev: metadata.dev, ino: metadata.ino });
72
+ await revalidateWritePath(filePath);
73
+ await revalidateWritePath(candidate);
74
+ }
75
+ await revalidateWritePath(filePath);
76
+ }
77
+
78
+ export async function removeCreatedDirectories(
79
+ directories: readonly string[],
80
+ ): Promise<void> {
81
+ const identities = ownership.get(directories);
82
+ if (!identities) return;
83
+ const errors: unknown[] = [];
84
+ for (const directory of [...directories].reverse()) {
85
+ const identity = identities.get(directory);
86
+ if (!identity) continue;
87
+ try {
88
+ const metadata = await lstat(directory);
89
+ if (
90
+ !metadata.isDirectory() ||
91
+ metadata.dev !== identity.dev ||
92
+ metadata.ino !== identity.ino
93
+ )
94
+ continue;
95
+ await revalidateWritePath(directory);
96
+ await rmdir(directory);
97
+ identities.delete(directory);
98
+ } catch (error) {
99
+ const code = (error as NodeJS.ErrnoException).code;
100
+ if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST")
101
+ errors.push(error);
102
+ }
103
+ }
104
+ if (errors.length)
105
+ throw Object.assign(
106
+ new AggregateError(
107
+ errors,
108
+ "Created parent directory cleanup was incomplete",
109
+ ),
110
+ {
111
+ details: { affectedPaths: [...directories] },
112
+ },
113
+ );
114
+ }
@@ -0,0 +1,35 @@
1
+ import path from "node:path";
2
+
3
+ /** Resolve the same full-path, extensionless, and index aliases as delete preflight. */
4
+ export function createReferenceTargetIndex(
5
+ targets: Iterable<string>,
6
+ ): Map<string, string[]> {
7
+ const index = new Map<string, string[]>();
8
+ for (const target of targets) {
9
+ const extension = path.extname(target);
10
+ const aliases = new Set([target]);
11
+ if (extension && target.endsWith(extension))
12
+ aliases.add(target.slice(0, -extension.length));
13
+ for (const alias of aliases) {
14
+ const matches = index.get(alias);
15
+ if (matches) matches.push(target);
16
+ else index.set(alias, [target]);
17
+ }
18
+ }
19
+ return index;
20
+ }
21
+
22
+ /** Each importing file counts once per target, including repeated import spellings. */
23
+ export function referencedTargets(
24
+ index: ReadonlyMap<string, readonly string[]>,
25
+ bases: Iterable<string>,
26
+ ): Set<string> {
27
+ const matches = new Set<string>();
28
+ for (const base of bases) {
29
+ for (const target of index.get(base) ?? []) matches.add(target);
30
+ // Joining the query preserves native normalization without normalizing literal aliases.
31
+ for (const target of index.get(path.join(base, "index")) ?? [])
32
+ matches.add(target);
33
+ }
34
+ return matches;
35
+ }