@mwillbanks/ast-mcp 0.6.4 → 0.6.6

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,7 +12,6 @@ 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";
18
17
  import {
@@ -22,6 +21,7 @@ import {
22
21
  } from "./parent-directories";
23
22
  import { pathsShareRoot, resolveWritablePath } from "./paths";
24
23
  import { requireExpectedHash, verifyExpectedHash } from "./policy";
24
+ import { stageFileSnapshot, FileSnapshotCollection } from "./snapshot-blob";
25
25
 
26
26
  export interface FileRenameRequest {
27
27
  destination: string;
@@ -299,15 +299,12 @@ export async function renameFilesSafely(
299
299
  const fence = async () => {
300
300
  for (const lease of leases) await lease.fence();
301
301
  };
302
- const sourceSnapshots = new Map<
303
- string,
304
- Awaited<ReturnType<typeof readFileSnapshot>>
305
- >();
302
+ await using sourceSnapshots = new FileSnapshotCollection();
306
303
  for (const { filePath, request } of entries) {
307
- const snapshot = await readFileSnapshot(filePath, signal);
308
304
  await requireExpectedHash(request.expectedSha256, "file_rename");
309
- verifyExpectedHash(request.expectedSha256, snapshot.sha256);
305
+ const snapshot = await stageFileSnapshot(filePath, signal);
310
306
  sourceSnapshots.set(filePath, snapshot);
307
+ verifyExpectedHash(request.expectedSha256, snapshot.sha256);
311
308
  }
312
309
  const sourceHashes = new Map(
313
310
  [...sourceSnapshots].map(([filePath, snapshot]) => [
@@ -323,7 +320,8 @@ export async function renameFilesSafely(
323
320
  {
324
321
  candidateSha256: null,
325
322
  filePath,
326
- sourceContentBase64: snapshot?.content.toString("base64") ?? null,
323
+ sourceContentBase64: null,
324
+ sourceBlob: snapshot?.sourceBlob ?? null,
327
325
  sourceGid:
328
326
  process.platform === "win32" ? null : (snapshot?.gid ?? null),
329
327
  sourceMode: snapshot?.mode ?? null,
@@ -357,6 +355,7 @@ export async function renameFilesSafely(
357
355
  const createdDirectories: string[] = [];
358
356
  try {
359
357
  signal?.throwIfAborted();
358
+ sourceSnapshots.disposable = false;
360
359
  await beginMutation({
361
360
  files: sourcePlan,
362
361
  operationId,
@@ -364,6 +363,7 @@ export async function renameFilesSafely(
364
363
  workspace,
365
364
  });
366
365
  began = true;
366
+ await sourceSnapshots.verify(signal);
367
367
  for (const entry of entries) {
368
368
  await ensureParentDirectories(
369
369
  entry.destinationPath,
@@ -417,6 +417,7 @@ export async function renameFilesSafely(
417
417
  commits,
418
418
  );
419
419
  completed = true;
420
+ sourceSnapshots.disposable = true;
420
421
  return intelligenceRefresh ? { files, intelligenceRefresh } : { files };
421
422
  } catch (error) {
422
423
  primaryFailure = error;
@@ -444,8 +445,12 @@ export async function renameFilesSafely(
444
445
  ),
445
446
  ]),
446
447
  );
447
- if (began && restored.every(Boolean))
448
- await ignoreFailure(recordMutationRollback(operationId));
448
+ if (began && restored.every(Boolean)) {
449
+ try {
450
+ await recordMutationRollback(operationId);
451
+ sourceSnapshots.disposable = true;
452
+ } catch {}
453
+ }
449
454
  throw error;
450
455
  } finally {
451
456
  if (!completed) {
@@ -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,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
+ }