@mwillbanks/ast-mcp 0.2.1 → 0.3.0

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.
Files changed (59) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -14
  3. package/dist/ast-mcp.js +183 -137
  4. package/dist/ast-mcp.js.map +58 -42
  5. package/package.json +17 -11
  6. package/src/ast-bro/capability.ts +20 -10
  7. package/src/ast-bro/tools.json +22 -2
  8. package/src/cli.ts +10 -7
  9. package/src/config-cli.ts +166 -19
  10. package/src/config-migrate.ts +223 -0
  11. package/src/config-registry.ts +321 -0
  12. package/src/config-schema-common.ts +81 -0
  13. package/src/config-v2-schema.ts +97 -0
  14. package/src/config.ts +375 -149
  15. package/src/helpers/ast-bro.ts +1 -7
  16. package/src/helpers/config.ts +12 -3
  17. package/src/helpers/installer.ts +8 -0
  18. package/src/helpers/mcp-schema.ts +105 -4
  19. package/src/host-smoke.ts +182 -0
  20. package/src/http.ts +8 -3
  21. package/src/installer-transport.ts +6 -4
  22. package/src/installer.ts +192 -51
  23. package/src/patch/engine.ts +555 -279
  24. package/src/patch/languages.ts +9 -0
  25. package/src/patch/strategy/aiderBlock.ts +110 -0
  26. package/src/patch/strategy/ast.ts +170 -0
  27. package/src/patch/strategy.ts +61 -0
  28. package/src/runtime/approval.ts +438 -0
  29. package/src/runtime/dependencies.ts +1 -1
  30. package/src/runtime/document-inspection.ts +78 -0
  31. package/src/runtime/file-capabilities.ts +250 -0
  32. package/src/runtime/file-delete.ts +122 -20
  33. package/src/runtime/file-read.ts +142 -14
  34. package/src/runtime/file-rename.ts +7 -6
  35. package/src/runtime/format.ts +65 -27
  36. package/src/runtime/path-policy.ts +557 -0
  37. package/src/runtime/path-utils.ts +40 -0
  38. package/src/runtime/paths.ts +204 -43
  39. package/src/server.ts +2 -1
  40. package/src/tools/ast-bro.ts +197 -76
  41. package/src/tools/configuration.ts +450 -0
  42. package/src/tools/configured.ts +49 -21
  43. package/src/tools/files.ts +177 -73
  44. package/src/tools/index.ts +2 -0
  45. package/src/tools/lifecycle.ts +89 -45
  46. package/templates/AGENTS.md +15 -17
  47. package/templates/skills/ast-mcp/SKILL.md +50 -34
  48. package/templates/skills/ast-mcp/evals/batch.evals.json +9 -9
  49. package/templates/skills/ast-mcp/evals/evals.json +221 -9
  50. package/templates/skills/ast-mcp/evals/measure.ts +27 -4
  51. package/templates/skills/ast-mcp/evals/score.test.ts +46 -3
  52. package/templates/skills/ast-mcp/evals/score.ts +87 -0
  53. package/templates/skills/ast-mcp/evals/semantic.test.ts +209 -28
  54. package/templates/skills/ast-mcp/evals/semantic.ts +151 -37
  55. package/templates/skills/ast-mcp/references/installation.md +12 -12
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +16 -10
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +8 -17
  59. package/src/ast-bro/rewrite-capability.ts +0 -9
@@ -1,4 +1,5 @@
1
- import { lstat, readFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, readFile, unlink, writeFile } from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { currentConfig, type ResolvedConfig } from "../config";
4
5
  import { replaceFileAtomically } from "./atomic";
@@ -24,44 +25,83 @@ function matchesFormatter(
24
25
  }
25
26
  function formatterArgs(
26
27
  config: ResolvedConfig,
27
- filePath: string,
28
+ sourceFile: string,
29
+ formatterFile: string,
28
30
  args: string[],
29
31
  ) {
30
32
  return args.map((argument) =>
31
33
  argument
32
- .replaceAll("{file}", filePath)
34
+ .replaceAll("{file}", formatterFile)
35
+ .replaceAll("{source_file}", sourceFile)
33
36
  .replaceAll("{project_root}", config.projectRoot),
34
37
  );
35
38
  }
36
39
 
40
+ async function removeFormatterStage(staged: string): Promise<void> {
41
+ try {
42
+ await unlink(staged);
43
+ } catch (error) {
44
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT")
45
+ throw new Error(`Failed to remove formatter stage ${staged}`, {
46
+ cause: error,
47
+ });
48
+ }
49
+ }
50
+
37
51
  export async function formatContent(
38
52
  filePath: string,
39
53
  content: string,
40
54
  ): Promise<string> {
41
55
  const config = await currentConfig();
42
- if (!config.formatting.enabled) return content;
43
- const formatter = config.formatting.formatters.find((candidate) =>
44
- matchesFormatter(config, filePath, candidate),
56
+ const formatter = config.formatting.formatters.find(
57
+ (candidate) =>
58
+ (candidate.enabled ?? config.formatting.enabled) &&
59
+ matchesFormatter(config, filePath, candidate),
45
60
  );
46
- const result = formatter
47
- ? await runCommandInput(
61
+ if (formatter) {
62
+ if (formatter.mode === "stdout") {
63
+ const result = await runCommandInput(
48
64
  formatter.command,
49
- formatterArgs(config, filePath, formatter.args),
65
+ formatterArgs(config, filePath, filePath, formatter.args),
50
66
  content,
51
67
  { cwd: config.projectRoot, timeoutMs: formatter.timeoutMs },
52
- )
53
- : await runCommandInput(
54
- await dprint(),
55
- [
56
- "fmt",
57
- "--config",
58
- config.formatting.dprintConfig,
59
- "--stdin",
60
- formatterPath(config, filePath),
61
- ],
62
- content,
63
- { cwd: config.projectRoot },
64
68
  );
69
+ return result.stdout;
70
+ }
71
+ const extension = path.extname(filePath);
72
+ const staged = path.join(
73
+ path.dirname(filePath),
74
+ `.ast-mcp-format-${randomUUID()}${extension}`,
75
+ );
76
+ try {
77
+ await writeFile(staged, content, { flag: "wx" });
78
+ await runCommandInput(
79
+ formatter.command,
80
+ formatterArgs(config, filePath, staged, formatter.args),
81
+ "",
82
+ { cwd: config.projectRoot, timeoutMs: formatter.timeoutMs },
83
+ );
84
+ return await readFile(staged, "utf8");
85
+ } finally {
86
+ await removeFormatterStage(staged);
87
+ }
88
+ }
89
+ if (!config.formatting.enabled || config.formatting.fallback === "preserve")
90
+ return content;
91
+ if (config.formatting.fallback === "reject")
92
+ throw new Error(`No enabled formatter matches ${filePath}`);
93
+ const result = await runCommandInput(
94
+ await dprint(),
95
+ [
96
+ "fmt",
97
+ "--config",
98
+ config.formatting.dprintConfig,
99
+ "--stdin",
100
+ formatterPath(config, filePath),
101
+ ],
102
+ content,
103
+ { cwd: config.projectRoot },
104
+ );
65
105
  return result.stdout;
66
106
  }
67
107
 
@@ -70,11 +110,9 @@ export async function assertFormattable(filePath: string): Promise<void> {
70
110
  }
71
111
 
72
112
  export async function formatFileAtomically(filePath: string): Promise<void> {
73
- if (!(await currentConfig()).formatting.enabled) return;
74
113
  const metadata = await lstat(filePath);
75
- const formatted = await formatContent(
76
- filePath,
77
- await readFile(filePath, "utf8"),
78
- );
79
- await replaceFileAtomically(filePath, formatted, metadata.mode);
114
+ const source = await readFile(filePath, "utf8");
115
+ const formatted = await formatContent(filePath, source);
116
+ if (formatted !== source)
117
+ await replaceFileAtomically(filePath, formatted, metadata.mode);
80
118
  }
@@ -0,0 +1,557 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { lstat, realpath } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import type { ResolvedConfig } from "../config";
6
+ import type { PathPolicy } from "../config-v2-schema";
7
+ import { authorizeRequestedDecision } from "./approval";
8
+ import {
9
+ canonicalizePath,
10
+ effectiveWorkspaceRoot,
11
+ pathWithin,
12
+ } from "./path-utils";
13
+
14
+ export type PathOperation = "read" | "write" | "delete";
15
+
16
+ export interface PolicyDecision {
17
+ canonicalPath: string;
18
+ operation: PathOperation;
19
+ policy: PathPolicy;
20
+ reason: string;
21
+ ruleId?: string;
22
+ source: "baseline" | "configuration" | "global" | "project";
23
+ specificity: number;
24
+ symlinks: boolean;
25
+ }
26
+
27
+ const precedence: Record<PathPolicy, number> = {
28
+ allow: 0,
29
+ deny: 2,
30
+ request: 1,
31
+ };
32
+ const temporaryRoot = (() => {
33
+ try {
34
+ return realpathSync.native(os.tmpdir());
35
+ } catch {
36
+ return path.resolve(os.tmpdir());
37
+ }
38
+ })();
39
+
40
+ async function canonicalPolicyPath(targetPath: string): Promise<string> {
41
+ const absolute = path.resolve(targetPath);
42
+ return path.join(
43
+ await canonicalizePath(path.dirname(absolute)),
44
+ path.basename(absolute),
45
+ );
46
+ }
47
+
48
+ function within(root: string, target: string): boolean {
49
+ return pathWithin(root, target);
50
+ }
51
+
52
+ function literalPrefix(glob: string): number {
53
+ const wildcard = glob.search(/[?*[{]/);
54
+ return (wildcard < 0 ? glob : glob.slice(0, wildcard)).length;
55
+ }
56
+
57
+ function matchingIncludes(relative: string, includes: string[]): string[] {
58
+ if (relative === "") return [];
59
+ const unix = relative.split(path.sep).join("/");
60
+ return includes.filter((glob) => new Bun.Glob(glob).match(unix));
61
+ }
62
+
63
+ function matches(
64
+ relative: string,
65
+ includes: string[],
66
+ excludes: string[],
67
+ ): boolean {
68
+ const unix = relative.split(path.sep).join("/") || ".";
69
+ const selectorMatches = (glob: string) => {
70
+ if (new Bun.Glob(glob).match(unix)) return true;
71
+ const recursiveRoot = recursiveSelectorPath(glob);
72
+ return (
73
+ recursiveRoot !== undefined &&
74
+ (recursiveRoot === "" || new Bun.Glob(recursiveRoot).match(unix))
75
+ );
76
+ };
77
+ if (excludes.some(selectorMatches)) return false;
78
+ return relative === "" || includes.some(selectorMatches);
79
+ }
80
+
81
+ function protectedConfiguration(
82
+ config: ResolvedConfig,
83
+ target: string,
84
+ platform: NodeJS.Platform,
85
+ ): boolean {
86
+ const normalizedTarget = platform === "win32" ? target.toLowerCase() : target;
87
+ return [config.sources.global, config.sources.project]
88
+ .filter((item): item is string => Boolean(item))
89
+ .some((item) => {
90
+ const candidate = path.resolve(item);
91
+ return (
92
+ (platform === "win32" ? candidate.toLowerCase() : candidate) ===
93
+ normalizedTarget
94
+ );
95
+ });
96
+ }
97
+
98
+ export function evaluatePolicy(
99
+ config: ResolvedConfig,
100
+ targetPath: string,
101
+ operation: PathOperation,
102
+ platform: NodeJS.Platform = process.platform,
103
+ ): PolicyDecision {
104
+ const canonicalPath = path.resolve(targetPath);
105
+ if (
106
+ operation !== "read" &&
107
+ protectedConfiguration(config, canonicalPath, platform)
108
+ )
109
+ return {
110
+ canonicalPath,
111
+ operation,
112
+ policy: "request",
113
+ reason: "Active configuration files are protected targets",
114
+ source: "configuration",
115
+ specificity: Number.MAX_SAFE_INTEGER,
116
+ symlinks: false,
117
+ };
118
+
119
+ const candidates = (config.paths ?? []).flatMap((rule) => {
120
+ const anchor = path.resolve(rule.path);
121
+ if (!within(anchor, canonicalPath)) return [];
122
+ const relative = path.relative(anchor, canonicalPath);
123
+ if (relative !== "" && !matches(relative, rule.includes, rule.excludes))
124
+ return [];
125
+ const exact = canonicalPath === anchor ? 1_000_000 : 0;
126
+ const depth = anchor.split(path.sep).length * 10_000;
127
+ const includeSpecificity = Math.max(
128
+ ...matchingIncludes(relative, rule.includes).map(literalPrefix),
129
+ 0,
130
+ );
131
+ return [
132
+ {
133
+ canonicalPath,
134
+ operation,
135
+ policy: rule.policies[operation],
136
+ reason: `Matched paths rule ${rule.id}`,
137
+ ruleId: rule.id,
138
+ source: rule.source,
139
+ specificity: exact + depth + includeSpecificity,
140
+ symlinks: rule.followSymlinks,
141
+ } satisfies PolicyDecision,
142
+ ];
143
+ });
144
+
145
+ candidates.sort(
146
+ (left, right) =>
147
+ right.specificity - left.specificity ||
148
+ precedence[right.policy] - precedence[left.policy],
149
+ );
150
+ const winner = candidates[0];
151
+ if (winner) {
152
+ const withinBaseline = config.trustedRoots.some((root) =>
153
+ within(root, canonicalPath),
154
+ );
155
+ if (
156
+ winner.policy === "allow" &&
157
+ !withinBaseline &&
158
+ winner.source === "project"
159
+ )
160
+ return {
161
+ ...winner,
162
+ policy: "request",
163
+ reason: `${winner.reason}; project access beyond the host baseline requires approval`,
164
+ };
165
+ return winner;
166
+ }
167
+
168
+ if (
169
+ config.version === 1 &&
170
+ config.safety.allowTempDirectory &&
171
+ within(temporaryRoot, canonicalPath)
172
+ )
173
+ return {
174
+ canonicalPath,
175
+ operation,
176
+ policy: "allow",
177
+ reason: "Legacy safety.allow_temp_directory",
178
+ source: "baseline",
179
+ specificity: 0,
180
+ symlinks: config.safety.followSymlinks,
181
+ };
182
+ if (config.version === 1 && config.safety.allowAnyPath)
183
+ return {
184
+ canonicalPath,
185
+ operation,
186
+ policy: "allow",
187
+ reason: "Legacy safety.allow_any_path",
188
+ source: "baseline",
189
+ specificity: 0,
190
+ symlinks: config.safety.followSymlinks,
191
+ };
192
+ const inBaseline = config.trustedRoots.some((root) =>
193
+ within(root, canonicalPath),
194
+ );
195
+ return {
196
+ canonicalPath,
197
+ operation,
198
+ policy: inBaseline ? "allow" : "deny",
199
+ reason: inBaseline
200
+ ? "Path is within the host baseline"
201
+ : "No explicit rule matches outside the host baseline",
202
+ source: "baseline",
203
+ specificity: 0,
204
+ symlinks: config.version === 1 && config.safety.followSymlinks,
205
+ };
206
+ }
207
+
208
+ function symlinkDenied(
209
+ decision: PolicyDecision,
210
+ target: string,
211
+ ): PolicyDecision {
212
+ return {
213
+ ...decision,
214
+ canonicalPath: target,
215
+ policy: "deny",
216
+ reason: `${decision.reason}; the winning rule does not permit symbolic links`,
217
+ };
218
+ }
219
+
220
+ export async function evaluatePolicyForCheck(
221
+ config: ResolvedConfig,
222
+ targetPath: string,
223
+ operation: PathOperation,
224
+ ): Promise<PolicyDecision> {
225
+ const workspaceRoots = await Promise.all(
226
+ config.workspace.roots.map(canonicalizePath),
227
+ );
228
+ const base = effectiveWorkspaceRoot(
229
+ await canonicalizePath(config.projectRoot),
230
+ workspaceRoots,
231
+ );
232
+ const inputPath = path.isAbsolute(targetPath)
233
+ ? targetPath
234
+ : path.resolve(base, targetPath);
235
+ const linkPath = await canonicalPolicyPath(inputPath);
236
+ const linkDecision = evaluatePolicy(config, linkPath, operation);
237
+ const metadata = await lstat(linkPath).catch(() => undefined);
238
+ if (!metadata?.isSymbolicLink()) return linkDecision;
239
+ if (linkDecision.policy !== "allow") return linkDecision;
240
+ if (!linkDecision.symlinks) return symlinkDenied(linkDecision, linkPath);
241
+ const target = await realpath(linkPath);
242
+ const targetDecision = evaluatePolicy(config, target, operation);
243
+ if (targetDecision.policy !== "allow") return targetDecision;
244
+ return targetDecision.symlinks
245
+ ? targetDecision
246
+ : symlinkDenied(targetDecision, target);
247
+ }
248
+
249
+ function allowRuleCoversTree(
250
+ rule: ResolvedConfig["paths"][number],
251
+ root: string,
252
+ ): boolean {
253
+ const anchor = path.resolve(rule.path);
254
+ if (!within(anchor, root)) return false;
255
+ const relative = path.relative(anchor, root).split(path.sep).join("/");
256
+ const included = rule.includes.some((value) => {
257
+ const glob = value.replace(/^\.\//, "").replace(/\/$/, "");
258
+ const prefix =
259
+ glob === "**" || glob === "**/*"
260
+ ? ""
261
+ : glob.endsWith("/**/*")
262
+ ? glob.slice(0, -5)
263
+ : glob.endsWith("/**")
264
+ ? glob.slice(0, -3)
265
+ : undefined;
266
+ return (
267
+ prefix !== undefined &&
268
+ (prefix === "" ||
269
+ relative === prefix ||
270
+ relative.startsWith(`${prefix}/`))
271
+ );
272
+ });
273
+ if (!included) return false;
274
+ return !rule.excludes.some((value) => {
275
+ const glob = value.replace(/^\.\//, "").replace(/\/$/, "");
276
+ const wildcard = glob.search(/[?*[{]/);
277
+ const prefix = (wildcard < 0 ? glob : glob.slice(0, wildcard)).replace(
278
+ /\/$/,
279
+ "",
280
+ );
281
+ return (
282
+ !relative ||
283
+ !prefix ||
284
+ prefix === relative ||
285
+ prefix.startsWith(`${relative}/`) ||
286
+ relative.startsWith(`${prefix}/`)
287
+ );
288
+ });
289
+ }
290
+
291
+ function normalizedSelector(selector: string): string {
292
+ return selector.replace(/^\.\//, "").replace(/\/$/, "");
293
+ }
294
+
295
+ const selectorExpansionLimit = 256;
296
+
297
+ function selectorSegments(selector: string): string[] {
298
+ return normalizedSelector(selector).split("/").filter(Boolean);
299
+ }
300
+
301
+ function expandBraceAlternatives(selector: string): string[] | undefined {
302
+ const match = /\{([^{}]*,[^{}]*)\}/.exec(selector);
303
+ if (!match || match.index === undefined) return [selector];
304
+ const prefix = selector.slice(0, match.index);
305
+ const suffix = selector.slice(match.index + match[0].length);
306
+ const expanded: string[] = [];
307
+ for (const alternative of match[1].split(",")) {
308
+ const nested = expandBraceAlternatives(`${prefix}${alternative}${suffix}`);
309
+ if (!nested) return undefined;
310
+ expanded.push(...nested);
311
+ if (expanded.length > selectorExpansionLimit) return undefined;
312
+ }
313
+ return expanded;
314
+ }
315
+
316
+ function expandCharacterRange(
317
+ start: string,
318
+ end: string,
319
+ ): string[] | undefined {
320
+ const startCode = start.codePointAt(0) ?? 0;
321
+ const endCode = end.codePointAt(0) ?? 0;
322
+ const distance = endCode - startCode;
323
+ if (distance < 0 || distance > 64) return undefined;
324
+ return Array.from({ length: distance + 1 }, (_, offset) =>
325
+ String.fromCodePoint(startCode + offset),
326
+ );
327
+ }
328
+
329
+ function expandClassCharacters(value: string): string[] | undefined {
330
+ if (!value || value.startsWith("!") || value.startsWith("^"))
331
+ return undefined;
332
+ const characters: string[] = [];
333
+ for (let index = 0; index < value.length; index += 1) {
334
+ const start = value[index] as string;
335
+ if (value[index + 1] !== "-" || index + 2 >= value.length) {
336
+ characters.push(start);
337
+ continue;
338
+ }
339
+ const range = expandCharacterRange(start, value[index + 2] as string);
340
+ if (!range) return undefined;
341
+ characters.push(...range);
342
+ index += 2;
343
+ }
344
+ return [...new Set(characters)];
345
+ }
346
+
347
+ function expandClassAlternatives(selector: string): string[] | undefined {
348
+ const match = /\[([^\]]+)\]/.exec(selector);
349
+ if (!match || match.index === undefined) return [selector];
350
+ const characters = expandClassCharacters(match[1] as string);
351
+ if (!characters) return [selector];
352
+ const prefix = selector.slice(0, match.index);
353
+ const suffix = selector.slice(match.index + match[0].length);
354
+ const expanded: string[] = [];
355
+ for (const character of characters) {
356
+ const nested = expandClassAlternatives(`${prefix}${character}${suffix}`);
357
+ if (!nested) return undefined;
358
+ expanded.push(...nested);
359
+ if (expanded.length > selectorExpansionLimit) return undefined;
360
+ }
361
+ return expanded;
362
+ }
363
+
364
+ function expandSelectorAlternatives(selector: string): string[] | undefined {
365
+ const braces = expandBraceAlternatives(selector);
366
+ if (!braces) return undefined;
367
+ const expanded: string[] = [];
368
+ for (const alternative of braces) {
369
+ const classes = expandClassAlternatives(alternative);
370
+ if (!classes) return undefined;
371
+ expanded.push(...classes);
372
+ if (expanded.length > selectorExpansionLimit) return undefined;
373
+ }
374
+ return [...new Set(expanded)];
375
+ }
376
+
377
+ function recursiveSelectorPath(selector: string): string | undefined {
378
+ const normalized = normalizedSelector(selector);
379
+ if (normalized === "**" || normalized === "**/*") return "";
380
+ if (normalized.endsWith("/**/*")) return normalized.slice(0, -5);
381
+ if (normalized.endsWith("/**")) return normalized.slice(0, -3);
382
+ return undefined;
383
+ }
384
+
385
+ function selectorCoveredByExclusion(
386
+ selector: string,
387
+ exclusion: string,
388
+ ): boolean {
389
+ if (normalizedSelector(exclusion) === normalizedSelector(selector))
390
+ return true;
391
+ const excludedPath = recursiveSelectorPath(exclusion);
392
+ if (excludedPath === undefined) return false;
393
+ if (excludedPath === "") return true;
394
+ const excludedSegments = selectorSegments(excludedPath);
395
+ if (excludedSegments.some((segment) => /[?*[{]/.test(segment))) return false;
396
+ const includeSegments = selectorSegments(selector);
397
+ return (
398
+ excludedSegments.length <= includeSegments.length &&
399
+ excludedSegments.every(
400
+ (segment, index) => includeSegments[index] === segment,
401
+ )
402
+ );
403
+ }
404
+
405
+ function expandedSelectorExclusions(excludes: string[]): string[] {
406
+ return excludes.flatMap(
407
+ (exclude) => expandSelectorAlternatives(exclude) ?? [],
408
+ );
409
+ }
410
+
411
+ function selectorAlternativeIntersectsTree(
412
+ selector: string,
413
+ relativeRoot: string,
414
+ ): boolean {
415
+ const selectors = selectorSegments(selector);
416
+ const roots = relativeRoot.split("/").filter(Boolean);
417
+ const visited = new Set<string>();
418
+ const intersects = (selectorIndex: number, rootIndex: number): boolean => {
419
+ if (rootIndex === roots.length) return true;
420
+ if (selectorIndex === selectors.length) return false;
421
+ const key = `${selectorIndex}:${rootIndex}`;
422
+ if (visited.has(key)) return false;
423
+ visited.add(key);
424
+ const segment = selectors[selectorIndex] as string;
425
+ if (segment === "**")
426
+ return (
427
+ intersects(selectorIndex + 1, rootIndex) ||
428
+ intersects(selectorIndex, rootIndex + 1)
429
+ );
430
+ return (
431
+ new Bun.Glob(segment).match(roots[rootIndex] as string) &&
432
+ intersects(selectorIndex + 1, rootIndex + 1)
433
+ );
434
+ };
435
+ return intersects(0, 0);
436
+ }
437
+
438
+ function exclusionCoversRequestedTree(
439
+ exclusion: string,
440
+ relativeRoot: string,
441
+ ): boolean {
442
+ return (
443
+ recursiveSelectorPath(exclusion) !== undefined &&
444
+ matches(relativeRoot, [exclusion], [])
445
+ );
446
+ }
447
+
448
+ function selectorIntersectsRuleTree(
449
+ selector: string,
450
+ excludes: string[],
451
+ relativeRoot: string,
452
+ ): boolean {
453
+ if (
454
+ excludes.some(
455
+ (exclude) => normalizedSelector(exclude) === normalizedSelector(selector),
456
+ )
457
+ )
458
+ return false;
459
+ const alternatives = expandSelectorAlternatives(selector);
460
+ if (!alternatives) return true;
461
+ const expandedExcludes = expandedSelectorExclusions(excludes);
462
+ return alternatives.some(
463
+ (alternative) =>
464
+ selectorAlternativeIntersectsTree(alternative, relativeRoot) &&
465
+ !expandedExcludes.some(
466
+ (exclude) =>
467
+ selectorCoveredByExclusion(alternative, exclude) ||
468
+ exclusionCoversRequestedTree(exclude, relativeRoot),
469
+ ),
470
+ );
471
+ }
472
+
473
+ function ruleIntersectsTree(
474
+ rule: ResolvedConfig["paths"][number],
475
+ root: string,
476
+ ): boolean {
477
+ const anchor = path.resolve(rule.path);
478
+ if (within(root, anchor)) return true;
479
+ if (!within(anchor, root)) return false;
480
+ const relativeRoot = path.relative(anchor, root).split(path.sep).join("/");
481
+ return rule.includes.some((selector) =>
482
+ selectorIntersectsRuleTree(selector, rule.excludes, relativeRoot),
483
+ );
484
+ }
485
+
486
+ export function assertReadableTree(
487
+ config: ResolvedConfig,
488
+ targetPath: string,
489
+ ): void {
490
+ const root = path.resolve(targetPath);
491
+ assertPolicy(evaluatePolicy(config, root, "read"), config.generation);
492
+ let fullTreeAllowed =
493
+ config.trustedRoots.some((trustedRoot) => within(trustedRoot, root)) ||
494
+ (config.version === 1 &&
495
+ (config.safety.allowAnyPath ||
496
+ (config.safety.allowTempDirectory && within(temporaryRoot, root))));
497
+ for (const rule of config.paths ?? []) {
498
+ if (!ruleIntersectsTree(rule, root)) continue;
499
+ if (rule.policies.read === "allow") {
500
+ fullTreeAllowed ||= allowRuleCoversTree(rule, root);
501
+ continue;
502
+ }
503
+ assertPolicy(
504
+ {
505
+ canonicalPath: root,
506
+ operation: "read",
507
+ policy: rule.policies.read,
508
+ reason: `Recursive read intersects paths rule ${rule.id}`,
509
+ ruleId: rule.id,
510
+ source: rule.source,
511
+ specificity: 0,
512
+ symlinks: rule.followSymlinks,
513
+ },
514
+ config.generation,
515
+ );
516
+ }
517
+ if (!fullTreeAllowed)
518
+ assertPolicy(
519
+ {
520
+ canonicalPath: root,
521
+ operation: "read",
522
+ policy: "deny",
523
+ reason: "Recursive read is not fully covered by an allow rule",
524
+ source: "baseline",
525
+ specificity: 0,
526
+ symlinks: false,
527
+ },
528
+ config.generation,
529
+ );
530
+ }
531
+
532
+ export class PathPolicyError extends Error {
533
+ readonly code: "path_denied" | "approval_required";
534
+ readonly decision: PolicyDecision;
535
+
536
+ constructor(decision: PolicyDecision) {
537
+ super(
538
+ decision.policy === "deny"
539
+ ? `${decision.operation} denied for ${decision.canonicalPath}: ${decision.reason}`
540
+ : `${decision.operation} requires approval for ${decision.canonicalPath}: ${decision.reason}`,
541
+ );
542
+ this.name = "PathPolicyError";
543
+ this.code =
544
+ decision.policy === "deny" ? "path_denied" : "approval_required";
545
+ this.decision = decision;
546
+ }
547
+ }
548
+
549
+ export function assertPolicy(decision: PolicyDecision, generation = 0): void {
550
+ if (decision.policy === "allow") return;
551
+ if (
552
+ decision.policy === "request" &&
553
+ authorizeRequestedDecision(decision, generation)
554
+ )
555
+ return;
556
+ throw new PathPolicyError(decision);
557
+ }