@mwillbanks/ast-mcp 0.6.3 → 0.6.4

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,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { createReadStream } from "node:fs";
2
+ import { createReadStream, type Dirent } from "node:fs";
3
3
  import {
4
4
  chmod,
5
5
  chown,
@@ -49,6 +49,9 @@ interface ReferenceVerification {
49
49
  targets: Set<string>;
50
50
  candidates: number;
51
51
  sourceBytes: number;
52
+ directories: Map<string, Dirent[]>;
53
+ imports: Map<string, string[]>;
54
+ roots: Map<string, Map<string, string[]>>;
52
55
  }
53
56
 
54
57
  function referenceFailure(message: string, cause?: unknown): Error {
@@ -68,12 +71,23 @@ async function* referenceCandidates(
68
71
  const pending = [root];
69
72
  while (pending.length) {
70
73
  signal.throwIfAborted();
71
- for await (const entry of await opendir(pending.pop()!)) {
74
+ const directory = pending.pop()!;
75
+ // Cache inventories, including overlapping roots, within this batch only.
76
+ let entries = verification.directories.get(directory);
77
+ if (!entries) {
78
+ entries = [];
79
+ for await (const entry of await opendir(directory)) {
80
+ signal.throwIfAborted();
81
+ if (++verification.candidates > 100_000)
82
+ throw referenceFailure(
83
+ "Reference verification exceeds the inventory limit",
84
+ );
85
+ entries.push(entry);
86
+ }
87
+ verification.directories.set(directory, entries);
88
+ }
89
+ for (const entry of entries) {
72
90
  signal.throwIfAborted();
73
- if (++verification.candidates > 100_000)
74
- throw referenceFailure(
75
- "Reference verification exceeds the inventory limit",
76
- );
77
91
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
78
92
  const candidate = path.join(entry.parentPath, entry.name);
79
93
  if (entry.isDirectory()) pending.push(candidate);
@@ -87,11 +101,12 @@ async function importersFor(
87
101
  root: string,
88
102
  verification: ReferenceVerification,
89
103
  ): Promise<string[]> {
90
- const importers: string[] = [];
91
- const target = path.resolve(filePath);
104
+ const cached = verification.roots.get(root);
105
+ if (cached) return cached.get(filePath) ?? [];
106
+ const importers = new Map<string, string[]>();
92
107
  try {
93
108
  for await (const candidate of referenceCandidates(root, verification)) {
94
- if (candidate === target || verification.targets.has(candidate)) continue;
109
+ if (verification.targets.has(candidate)) continue;
95
110
  const language = detectAstLanguage(candidate);
96
111
  if (
97
112
  !language ||
@@ -100,60 +115,74 @@ async function importersFor(
100
115
  )
101
116
  )
102
117
  continue;
103
- const file = Bun.file(candidate);
104
- if (file.size > 2 * 1024 * 1024)
105
- throw referenceFailure(
106
- "Reference verification source exceeds the byte limit",
107
- );
108
- verification.signal.throwIfAborted();
109
- const stream = createReadStream(candidate, {
110
- end: 2 * 1024 * 1024,
111
- signal: verification.signal,
112
- });
113
- const chunks: Buffer[] = [];
114
- let bytes: Buffer;
115
- try {
116
- for await (const chunk of stream) {
118
+ let bases = verification.imports.get(candidate);
119
+ if (!bases) {
120
+ const file = Bun.file(candidate);
121
+ if (file.size > 2 * 1024 * 1024)
122
+ throw referenceFailure(
123
+ "Reference verification source exceeds the byte limit",
124
+ );
125
+ verification.signal.throwIfAborted();
126
+ const stream = createReadStream(candidate, {
127
+ end: 2 * 1024 * 1024,
128
+ signal: verification.signal,
129
+ });
130
+ const chunks: Buffer[] = [];
131
+ let bytes: Buffer;
132
+ try {
133
+ for await (const chunk of stream) {
134
+ verification.signal.throwIfAborted();
135
+ chunks.push(Buffer.from(chunk));
136
+ }
117
137
  verification.signal.throwIfAborted();
118
- chunks.push(Buffer.from(chunk));
138
+ bytes = Buffer.concat(chunks);
139
+ } finally {
140
+ stream.destroy();
119
141
  }
142
+ verification.sourceBytes += bytes.byteLength;
143
+ if (
144
+ bytes.byteLength > 2 * 1024 * 1024 ||
145
+ verification.sourceBytes > 16 * 1024 * 1024
146
+ )
147
+ throw referenceFailure(
148
+ "Reference verification exceeds the source byte limit",
149
+ );
150
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
151
+ const facts = await verification.pool.parse(
152
+ {
153
+ languageId: language,
154
+ source,
155
+ },
156
+ { signal: verification.signal, timeoutMs: 1_000 },
157
+ );
158
+ if (
159
+ facts.diagnostics.some(
160
+ (diagnostic) => diagnostic.severity === "error",
161
+ )
162
+ )
163
+ throw referenceFailure(
164
+ "Reference verification encountered invalid source",
165
+ );
166
+ bases = facts.imports
167
+ .filter((entry) => entry.source.startsWith("."))
168
+ .map((entry) => path.resolve(path.dirname(candidate), entry.source));
169
+ verification.imports.set(candidate, bases);
170
+ }
171
+ for (const target of verification.targets) {
120
172
  verification.signal.throwIfAborted();
121
- bytes = Buffer.concat(chunks);
122
- } finally {
123
- stream.destroy();
173
+ if (
174
+ bases.some(
175
+ (base) =>
176
+ base === target ||
177
+ `${base}${path.extname(target)}` === target ||
178
+ path.join(base, `index${path.extname(target)}`) === target,
179
+ )
180
+ ) {
181
+ const matches = importers.get(target) ?? [];
182
+ matches.push(path.relative(root, candidate));
183
+ importers.set(target, matches);
184
+ }
124
185
  }
125
- verification.sourceBytes += bytes.byteLength;
126
- if (
127
- bytes.byteLength > 2 * 1024 * 1024 ||
128
- verification.sourceBytes > 16 * 1024 * 1024
129
- )
130
- throw referenceFailure(
131
- "Reference verification exceeds the source byte limit",
132
- );
133
- const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
134
- const facts = await verification.pool.parse(
135
- {
136
- languageId: language,
137
- source,
138
- },
139
- { signal: verification.signal, timeoutMs: 1_000 },
140
- );
141
- if (
142
- facts.diagnostics.some((diagnostic) => diagnostic.severity === "error")
143
- )
144
- throw referenceFailure(
145
- "Reference verification encountered invalid source",
146
- );
147
- const referenced = facts.imports.some((entry) => {
148
- if (!entry.source.startsWith(".")) return false;
149
- const base = path.resolve(path.dirname(candidate), entry.source);
150
- return (
151
- base === target ||
152
- `${base}${path.extname(target)}` === target ||
153
- path.join(base, `index${path.extname(target)}`) === target
154
- );
155
- });
156
- if (referenced) importers.push(path.relative(root, candidate));
157
186
  }
158
187
  } catch (error) {
159
188
  throw referenceFailure(
@@ -161,7 +190,9 @@ async function importersFor(
161
190
  error,
162
191
  );
163
192
  }
164
- return importers.sort();
193
+ for (const matches of importers.values()) matches.sort();
194
+ verification.roots.set(root, importers);
195
+ return importers.get(filePath) ?? [];
165
196
  }
166
197
 
167
198
  function ancestorPaths(filePath: string, root: string): string[] {
@@ -320,7 +351,10 @@ export async function deleteFilesSafely(
320
351
  signal?: AbortSignal,
321
352
  ) {
322
353
  const pool = new ParserWorkerPool({ minWorkers: 0, maxWorkers: 1 });
323
- const verification = {
354
+ const verification: ReferenceVerification = {
355
+ directories: new Map(),
356
+ imports: new Map(),
357
+ roots: new Map(),
324
358
  pool,
325
359
  targets: new Set<string>(),
326
360
  candidates: 0,
@@ -456,6 +490,7 @@ export async function deleteFilesSafely(
456
490
  } catch (error) {
457
491
  if (began) await ignoreFailure(failMutation(operationId, error));
458
492
  const rollbackErrors: unknown[] = [];
493
+ const affectedPaths: string[] = [];
459
494
  for (const commit of [...commits].reverse()) {
460
495
  const snapshot = snapshots.get(commit.filePath);
461
496
  if (!snapshot) continue;
@@ -481,15 +516,26 @@ export async function deleteFilesSafely(
481
516
  )
482
517
  throw new Error("file_delete_rollback_verification_failed");
483
518
  } catch (rollbackError) {
484
- rollbackErrors.push(rollbackError);
519
+ affectedPaths.push(commit.filePath);
520
+ rollbackErrors.push(
521
+ Object.assign(
522
+ new Error("Delete rollback failed", { cause: rollbackError }),
523
+ {
524
+ details: { affectedPaths: [commit.filePath] },
525
+ },
526
+ ),
527
+ );
485
528
  }
486
529
  }
487
530
  if (began && rollbackErrors.length === 0)
488
531
  await ignoreFailure(recordMutationRollback(operationId));
489
532
  if (rollbackErrors.length > 0)
490
- throw new AggregateError(
491
- [error, ...rollbackErrors],
492
- "file_delete failed and rollback requires recovery",
533
+ throw Object.assign(
534
+ new AggregateError(
535
+ [error, ...rollbackErrors],
536
+ "file_delete failed and rollback requires recovery",
537
+ ),
538
+ { details: { affectedPaths } },
493
539
  );
494
540
  throw error;
495
541
  }
@@ -15,6 +15,11 @@ import { currentWorkspace } from "../intelligence/workspace/context.ts";
15
15
  import { readFileSnapshot } from "./file-snapshot";
16
16
  import { sha256File } from "./hash";
17
17
  import { withFileLocks } from "./locks";
18
+ import {
19
+ ensureParentDirectories,
20
+ removeCreatedDirectories,
21
+ revalidateWritePath,
22
+ } from "./parent-directories";
18
23
  import { pathsShareRoot, resolveWritablePath } from "./paths";
19
24
  import { requireExpectedHash, verifyExpectedHash } from "./policy";
20
25
 
@@ -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,7 +299,6 @@ 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
302
  const sourceSnapshots = new Map<
229
303
  string,
230
304
  Awaited<ReturnType<typeof readFileSnapshot>>
@@ -278,6 +352,9 @@ export async function renameFilesSafely(
278
352
  : randomUUID();
279
353
  let began = false;
280
354
  let moved = false;
355
+ let completed = false;
356
+ let primaryFailure: unknown;
357
+ const createdDirectories: string[] = [];
281
358
  try {
282
359
  signal?.throwIfAborted();
283
360
  await beginMutation({
@@ -287,6 +364,17 @@ export async function renameFilesSafely(
287
364
  workspace,
288
365
  });
289
366
  began = true;
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,10 @@ export async function renameFilesSafely(
328
416
  operationId,
329
417
  commits,
330
418
  );
419
+ completed = true;
331
420
  return intelligenceRefresh ? { files, intelligenceRefresh } : { files };
332
421
  } catch (error) {
422
+ primaryFailure = error;
333
423
  if (began) await ignoreFailure(failMutation(operationId, error));
334
424
  if (moved) {
335
425
  try {
@@ -357,6 +447,22 @@ export async function renameFilesSafely(
357
447
  if (began && restored.every(Boolean))
358
448
  await ignoreFailure(recordMutationRollback(operationId));
359
449
  throw error;
450
+ } finally {
451
+ if (!completed) {
452
+ try {
453
+ await removeCreatedDirectories(createdDirectories);
454
+ } catch (cleanupError) {
455
+ throw Object.assign(
456
+ new AggregateError(
457
+ [primaryFailure, cleanupError],
458
+ "file_rename failed and parent cleanup was incomplete",
459
+ ),
460
+ {
461
+ details: { affectedPaths: createdDirectories },
462
+ },
463
+ );
464
+ }
465
+ }
360
466
  }
361
467
  },
362
468
  { signal },
@@ -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
+ }
@@ -415,16 +415,14 @@ export async function computeNative(
415
415
  );
416
416
  const schema = `ast-mcp.${name}.v1`;
417
417
  if (name === "map" || name === "digest") {
418
+ const memberLimit = input.max_members ?? (name === "digest" ? 50 : 200);
418
419
  const mapped = flatMapFilesWithAbort(files, signal, (file) => [
419
420
  {
420
421
  diagnostics: file.facts.diagnostics,
421
422
  language: file.facts.languageId,
422
423
  partial: file.facts.partial,
423
424
  path: relative(root, file.path),
424
- symbols: symbolView(file, root).slice(
425
- 0,
426
- input.max_members ?? (name === "digest" ? 50 : 200),
427
- ),
425
+ symbols: symbolView(file, root).slice(0, memberLimit),
428
426
  },
429
427
  ]);
430
428
  const result = bounded(mapped, input);
@@ -432,7 +430,9 @@ export async function computeNative(
432
430
  files: result.items,
433
431
  schema,
434
432
  total: result.total,
435
- truncated: result.truncated,
433
+ truncated:
434
+ result.truncated ||
435
+ files.some((file) => file.facts.symbols.length > memberLimit),
436
436
  };
437
437
  }
438
438
  if (name === "show") {
@@ -566,7 +566,15 @@ export async function computeNative(
566
566
  if (name === "cycles") {
567
567
  const limit = input.limit ?? input.top_k ?? 200;
568
568
  const result = graphCycles(visibleEdges, limit, signal);
569
- return { ...result, schema };
569
+ const page = bounded(result.cycles, {
570
+ ...input,
571
+ budget: input.budget ?? 1_000_000,
572
+ });
573
+ return {
574
+ cycles: page.items,
575
+ schema,
576
+ truncated: result.truncated || page.truncated,
577
+ };
570
578
  }
571
579
  if (name === "deps" || name === "reverse_deps") {
572
580
  const selectedPath = input.file ?? input.path;
@@ -10,7 +10,12 @@ import {
10
10
  import type { ToolInput, ToolName } from "./code-intelligence.ts";
11
11
  export type CpuJob =
12
12
  | { kind: "compiler-config"; source: string }
13
- | { kind: "parse"; languageId: ParserLanguageId; source: string }
13
+ | {
14
+ kind: "parse";
15
+ languageId: ParserLanguageId;
16
+ source: string;
17
+ maxReplyBytes?: number;
18
+ }
14
19
  | {
15
20
  kind: "compute";
16
21
  name: ToolName;
@@ -45,7 +50,11 @@ scope.onmessage = async ({ data }) => {
45
50
  data.aliases,
46
51
  );
47
52
  const bytes = Buffer.byteLength(JSON.stringify(value));
48
- if (bytes > 16 * 1024 * 1024)
53
+ const maxBytes =
54
+ data.kind === "parse"
55
+ ? (data.maxReplyBytes ?? 16 * 1024 * 1024)
56
+ : 16 * 1024 * 1024;
57
+ if (bytes > maxBytes)
49
58
  throw Object.assign(
50
59
  new Error(
51
60
  "Parsed data exceeds the request byte limit; narrow paths, glob, or scan_limit",