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