@mwillbanks/ast-mcp 0.2.2 → 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 (55) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -16
  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 +346 -148
  15. package/src/helpers/ast-bro.ts +1 -7
  16. package/src/helpers/config.ts +7 -0
  17. package/src/helpers/installer.ts +8 -0
  18. package/src/helpers/mcp-schema.ts +98 -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 +110 -37
  33. package/src/runtime/file-read.ts +142 -14
  34. package/src/runtime/file-rename.ts +5 -2
  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 +142 -44
  39. package/src/server.ts +2 -1
  40. package/src/tools/ast-bro.ts +196 -75
  41. package/src/tools/configuration.ts +450 -0
  42. package/src/tools/configured.ts +49 -21
  43. package/src/tools/files.ts +168 -61
  44. package/src/tools/index.ts +2 -0
  45. package/src/tools/lifecycle.ts +82 -38
  46. package/templates/AGENTS.md +13 -15
  47. package/templates/skills/ast-mcp/SKILL.md +28 -20
  48. package/templates/skills/ast-mcp/evals/evals.json +221 -9
  49. package/templates/skills/ast-mcp/evals/score.ts +80 -0
  50. package/templates/skills/ast-mcp/evals/semantic.ts +3 -1
  51. package/templates/skills/ast-mcp/references/installation.md +12 -12
  52. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  53. package/templates/skills/ast-mcp/references/tool-catalog.md +13 -7
  54. package/templates/skills/ast-mcp/scripts/check-install.ts +8 -17
  55. package/src/ast-bro/rewrite-capability.ts +0 -9
package/src/config.ts CHANGED
@@ -4,64 +4,28 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { z } from "zod";
7
+ import {
8
+ createFormatterSchema,
9
+ createHookSchema,
10
+ dependenciesSchema,
11
+ httpSchema,
12
+ workspaceSchema,
13
+ } from "./config-schema-common";
14
+ import {
15
+ fileV2Schema,
16
+ type PathPolicy,
17
+ type PathRuleV2,
18
+ } from "./config-v2-schema";
7
19
  import { collectRequestPaths, normalizeConfigLayer } from "./helpers/config";
20
+ import { canonicalizePath } from "./runtime/path-utils";
8
21
 
9
- const positiveInteger = z.number().int().positive();
10
- const toolNameSchema = z
11
- .string()
12
- .min(1)
13
- .max(200)
14
- .regex(
15
- /^[a-zA-Z0-9_.:-]+$/,
16
- "tool names may contain letters, digits, _, ., :, and - only",
17
- );
18
- const hookSchema = z
19
- .object({
20
- allow_tools: z.array(toolNameSchema).max(64).optional(),
21
- block_tools: z.array(toolNameSchema).max(64).optional(),
22
- enabled: z.boolean().optional(),
23
- })
24
- .strict()
25
- .superRefine((value, context) => {
26
- const allowed = new Set(
27
- (value.allow_tools ?? []).map((tool) => tool.toLowerCase()),
28
- );
29
- for (const tool of value.block_tools ?? [])
30
- if (allowed.has(tool.toLowerCase()))
31
- context.addIssue({
32
- code: "custom",
33
- message: `hook tool "${tool}" cannot be both allowed and blocked`,
34
- path: ["block_tools"],
35
- });
36
- });
37
- const formatterSchema = z
38
- .object({
39
- args: z.array(z.string().max(4096)).max(64).optional(),
40
- command: z.string().min(1).max(4096),
41
- extensions: z
42
- .array(
43
- z.string().regex(/^\.[^./\\]+$/, "extensions must begin with a dot"),
44
- )
45
- .max(64)
46
- .optional(),
47
- globs: z.array(z.string().min(1).max(4096)).max(64).optional(),
48
- timeout_ms: positiveInteger.max(120_000).optional(),
49
- })
50
- .strict()
51
- .refine(
52
- (value) =>
53
- Boolean(value.extensions?.length) || Boolean(value.globs?.length),
54
- "formatter requires at least one extension or glob",
55
- );
56
- const fileSchema = z
22
+ const schemaVersion = 1 as const;
23
+ const hookSchema = createHookSchema(64);
24
+
25
+ const formatterSchema = createFormatterSchema({});
26
+ const fileV1Schema = z
57
27
  .object({
58
- dependencies: z
59
- .object({
60
- ast_bro_binary: z.string().min(1).optional(),
61
- dprint_binary: z.string().min(1).optional(),
62
- })
63
- .strict()
64
- .optional(),
28
+ dependencies: dependenciesSchema.optional(),
65
29
  formatting: z
66
30
  .object({
67
31
  dprint_config: z.string().min(1).optional(),
@@ -70,15 +34,7 @@ const fileSchema = z
70
34
  })
71
35
  .strict()
72
36
  .optional(),
73
- http: z
74
- .object({
75
- host: z.string().min(1).optional(),
76
- port: z.number().int().min(1).max(65_535).optional(),
77
- session_sweep_interval_ms: positiveInteger.optional(),
78
- session_timeout_ms: positiveInteger.optional(),
79
- })
80
- .strict()
81
- .optional(),
37
+ http: httpSchema.optional(),
82
38
  safety: z
83
39
  .object({
84
40
  allow_any_path: z.boolean().optional(),
@@ -90,35 +46,57 @@ const fileSchema = z
90
46
  })
91
47
  .strict()
92
48
  .optional(),
93
- version: z.literal(1).optional(),
94
- workspace: z
95
- .object({ roots: z.array(z.string().min(1)).min(1).optional() })
96
- .strict()
97
- .optional(),
49
+ version: z.literal(schemaVersion).optional(),
50
+ workspace: workspaceSchema.optional(),
98
51
  })
99
52
  .strict();
100
53
 
101
- type AstMcpFileConfig = z.infer<typeof fileSchema>;
54
+ type AstMcpFileConfig =
55
+ | z.infer<typeof fileV1Schema>
56
+ | z.infer<typeof fileV2Schema>;
102
57
 
103
58
  export interface ResolvedConfig {
104
59
  dependencies: { astBroBinary?: string; dprintBinary?: string };
60
+ files: {
61
+ patch: {
62
+ aiderMatchers: Array<
63
+ "exact" | "whitespace" | "relative-indentation" | "diff-match-patch"
64
+ >;
65
+ strategies: Array<"ast" | "aider_block">;
66
+ };
67
+ read: { modes: Array<"ast" | "text"> };
68
+ };
105
69
  formatting: {
106
70
  dprintConfig: string;
107
71
  enabled: boolean;
72
+ fallback: "preserve" | "dprint" | "reject";
108
73
  formatters: Array<{
109
74
  args: string[];
110
75
  command: string;
76
+ enabled?: boolean;
111
77
  extensions: string[];
112
78
  globs: string[];
79
+ id: string;
80
+ mode: "stdout" | "in_place";
113
81
  timeoutMs: number;
114
82
  }>;
115
83
  };
84
+ generation: number;
116
85
  http: {
117
86
  host: string;
118
87
  port: number;
119
88
  sessionTimeoutMs: number;
120
89
  sessionSweepIntervalMs: number;
121
90
  };
91
+ paths: Array<{
92
+ excludes: string[];
93
+ followSymlinks: boolean;
94
+ id: string;
95
+ includes: string[];
96
+ path: string;
97
+ policies: { delete: PathPolicy; read: PathPolicy; write: PathPolicy };
98
+ source: "global" | "project";
99
+ }>;
122
100
  projectRoot: string;
123
101
  provenance: Record<string, "default" | "global" | "project" | "environment">;
124
102
  safety: {
@@ -129,13 +107,9 @@ export interface ResolvedConfig {
129
107
  hook: { allowTools: string[]; blockTools: string[]; enabled: boolean };
130
108
  requireHash: boolean;
131
109
  };
132
- sources: {
133
- project?: string;
134
- global?: string;
135
- environment: string[];
136
- };
110
+ sources: { project?: string; global?: string; environment: string[] };
137
111
  trustedRoots: string[];
138
- version: 1;
112
+ version: 1 | 2;
139
113
  workspace: { roots: string[] };
140
114
  }
141
115
 
@@ -156,14 +130,27 @@ interface LoadedLayer {
156
130
 
157
131
  interface InternalConfig {
158
132
  dependencies?: { ast_bro_binary?: string; dprint_binary?: string };
133
+ files?: {
134
+ patch?: {
135
+ aider_matchers?: Array<
136
+ "exact" | "whitespace" | "relative-indentation" | "diff-match-patch"
137
+ >;
138
+ strategies?: Array<"ast" | "aider_block">;
139
+ };
140
+ read?: { modes?: Array<"ast" | "text"> };
141
+ };
159
142
  formatting?: {
160
143
  dprint_config?: string;
161
144
  enabled?: boolean;
145
+ fallback?: "preserve" | "dprint" | "reject";
162
146
  formatters?: Array<{
163
147
  args?: string[];
164
148
  command: string;
149
+ enabled?: boolean;
165
150
  extensions?: string[];
166
151
  globs?: string[];
152
+ id?: string;
153
+ mode?: "stdout" | "in_place";
167
154
  timeout_ms?: number;
168
155
  }>;
169
156
  };
@@ -173,6 +160,14 @@ interface InternalConfig {
173
160
  session_timeout_ms?: number;
174
161
  session_sweep_interval_ms?: number;
175
162
  };
163
+ paths?: Array<{
164
+ excludes?: string[];
165
+ follow_symlinks?: boolean;
166
+ id: string;
167
+ includes?: string[];
168
+ path: string;
169
+ policies: { delete?: PathPolicy; read: PathPolicy; write: PathPolicy };
170
+ }>;
176
171
  safety?: {
177
172
  allow_any_path?: boolean;
178
173
  allow_external_roots?: boolean;
@@ -185,7 +180,7 @@ interface InternalConfig {
185
180
  };
186
181
  require_hash?: boolean;
187
182
  };
188
- version?: 1;
183
+ version?: 1 | 2;
189
184
  workspace?: { roots?: string[] };
190
185
  }
191
186
 
@@ -326,11 +321,51 @@ function _pathValue(value: string, base: string) {
326
321
  return path.resolve(base, value);
327
322
  }
328
323
 
329
- function normalizeLayer(
324
+ async function canonicalConfigurationPath(value: string): Promise<string> {
325
+ return canonicalizePath(value);
326
+ }
327
+
328
+ async function normalizeLayer(
330
329
  value: AstMcpFileConfig,
331
330
  filePath: string,
332
- ): AstMcpFileConfig {
333
- return normalizeConfigLayer(value, filePath);
331
+ ): Promise<AstMcpFileConfig> {
332
+ const normalized = normalizeConfigLayer(value, filePath);
333
+ if (normalized.version !== 2 || !normalized.paths) return normalized;
334
+ return {
335
+ ...normalized,
336
+ paths: await Promise.all(
337
+ normalized.paths.map(async (rule) => ({
338
+ ...rule,
339
+ path: await canonicalConfigurationPath(rule.path),
340
+ })),
341
+ ),
342
+ };
343
+ }
344
+
345
+ async function parseLayerValue(filePath: string): Promise<AstMcpFileConfig> {
346
+ let parsed: unknown;
347
+ try {
348
+ parsed = Bun.TOML.parse(await Bun.file(filePath).text());
349
+ } catch (error) {
350
+ throw new ConfigurationError(
351
+ `${filePath}: invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
352
+ );
353
+ }
354
+ const version =
355
+ parsed &&
356
+ typeof parsed === "object" &&
357
+ "version" in parsed &&
358
+ parsed.version === 2
359
+ ? 2
360
+ : 1;
361
+ const result = (version === 2 ? fileV2Schema : fileV1Schema).safeParse(
362
+ parsed,
363
+ );
364
+ if (!result.success)
365
+ throw new ConfigurationError(
366
+ `${filePath}: invalid configuration: ${diagnostic(result.error)}`,
367
+ );
368
+ return { ...result.data, version } as AstMcpFileConfig;
334
369
  }
335
370
 
336
371
  async function loadLayer(filePath: string): Promise<LoadedLayer> {
@@ -346,23 +381,10 @@ async function loadLayer(filePath: string): Promise<LoadedLayer> {
346
381
 
347
382
  const promise = (async () => {
348
383
  if (!metadata) return { fingerprint, path: filePath };
349
- let parsed: unknown;
350
- try {
351
- parsed = Bun.TOML.parse(await Bun.file(filePath).text());
352
- } catch (error) {
353
- throw new ConfigurationError(
354
- `${filePath}: invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
355
- );
356
- }
357
- const result = fileSchema.safeParse(parsed);
358
- if (!result.success)
359
- throw new ConfigurationError(
360
- `${filePath}: invalid configuration: ${diagnostic(result.error)}`,
361
- );
362
384
  return {
363
385
  fingerprint,
364
- path: filePath,
365
- value: normalizeLayer(result.data, filePath),
386
+ path: await canonicalConfigurationPath(filePath),
387
+ value: await normalizeLayer(await parseLayerValue(filePath), filePath),
366
388
  };
367
389
  })();
368
390
  layerCache.set(filePath, { fingerprint, promise });
@@ -513,6 +535,7 @@ function environmentLayer(
513
535
  const leaves = [
514
536
  "version",
515
537
  "workspace.roots",
538
+ "paths",
516
539
  "safety.allow_any_path",
517
540
  "safety.allow_external_roots",
518
541
  "safety.allow_temp_directory",
@@ -521,8 +544,12 @@ const leaves = [
521
544
  "safety.hook.block_tools",
522
545
  "safety.hook.enabled",
523
546
  "safety.require_hash",
547
+ "files.read.modes",
548
+ "files.patch.strategies",
549
+ "files.patch.aider_matchers",
524
550
  "formatting.dprint_config",
525
551
  "formatting.enabled",
552
+ "formatting.fallback",
526
553
  "formatting.formatters",
527
554
  "dependencies.ast_bro_binary",
528
555
  "dependencies.dprint_binary",
@@ -544,43 +571,78 @@ function leaf(value: InternalConfig, dotted: (typeof leaves)[number]) {
544
571
  );
545
572
  }
546
573
 
574
+ const mergeSections = [
575
+ "workspace",
576
+ "safety",
577
+ "files",
578
+ "formatting",
579
+ "dependencies",
580
+ "http",
581
+ ] as const;
582
+
583
+ type MergeSection = (typeof mergeSections)[number];
584
+
585
+ function definedProperties(value: object): object {
586
+ return Object.fromEntries(
587
+ Object.entries(value).filter(([, entry]) => entry !== undefined),
588
+ );
589
+ }
590
+
591
+ function mergeSafetyHook(
592
+ result: InternalConfig,
593
+ incoming: InternalConfig["safety"],
594
+ previousHook: NonNullable<InternalConfig["safety"]>["hook"],
595
+ ): void {
596
+ if (!incoming?.hook) return;
597
+ result.safety = {
598
+ ...result.safety,
599
+ hook: {
600
+ ...previousHook,
601
+ ...definedProperties(incoming.hook),
602
+ },
603
+ };
604
+ }
605
+
606
+ function mergeFileMethods(
607
+ result: InternalConfig,
608
+ incoming: InternalConfig["files"],
609
+ previous: InternalConfig["files"],
610
+ ): void {
611
+ if (!incoming) return;
612
+ result.files = {
613
+ patch: { ...previous?.patch, ...incoming.patch },
614
+ read: { ...previous?.read, ...incoming.read },
615
+ };
616
+ }
617
+
618
+ function mergeSection(
619
+ result: InternalConfig,
620
+ layer: InternalConfig,
621
+ section: MergeSection,
622
+ ): void {
623
+ const incoming = layer[section];
624
+ if (!incoming) return;
625
+ const previousHook = result.safety?.hook;
626
+ const previousFiles = result.files;
627
+ result[section] = {
628
+ ...(result[section] as object | undefined),
629
+ ...definedProperties(incoming),
630
+ } as never;
631
+ if (section === "safety")
632
+ mergeSafetyHook(result, incoming as InternalConfig["safety"], previousHook);
633
+ if (section === "files")
634
+ mergeFileMethods(
635
+ result,
636
+ incoming as InternalConfig["files"],
637
+ previousFiles,
638
+ );
639
+ }
640
+
547
641
  function merge(...layers: InternalConfig[]): InternalConfig {
548
642
  const result: InternalConfig = {};
549
643
  for (const layer of layers) {
550
644
  if (layer.version !== undefined) result.version = layer.version;
551
- for (const section of [
552
- "workspace",
553
- "safety",
554
- "formatting",
555
- "dependencies",
556
- "http",
557
- ] as const) {
558
- const incoming = layer[section];
559
- if (!incoming) continue;
560
- const previousHook = result.safety?.hook;
561
- const defined = Object.fromEntries(
562
- Object.entries(incoming).filter(([, value]) => value !== undefined),
563
- );
564
- result[section] = {
565
- ...(result[section] as object | undefined),
566
- ...defined,
567
- } as never;
568
- if (section === "safety") {
569
- const safetyIncoming = incoming as InternalConfig["safety"];
570
- if (safetyIncoming?.hook)
571
- result.safety = {
572
- ...result.safety,
573
- hook: {
574
- ...previousHook,
575
- ...Object.fromEntries(
576
- Object.entries(safetyIncoming.hook).filter(
577
- ([, value]) => value !== undefined,
578
- ),
579
- ),
580
- },
581
- };
582
- }
583
- }
645
+ for (const section of mergeSections) mergeSection(result, layer, section);
584
646
  }
585
647
  return result;
586
648
  }
@@ -588,27 +650,44 @@ function merge(...layers: InternalConfig[]): InternalConfig {
588
650
  async function projectRoots(options: ResolveConfigOptions) {
589
651
  const env = options.env ?? process.env;
590
652
  const cwd = path.resolve(options.cwd ?? process.cwd());
653
+ const withCanonical = async (roots: string[]) => [
654
+ ...new Set([
655
+ ...roots,
656
+ ...(await Promise.all(roots.map(canonicalConfigurationPath))),
657
+ ]),
658
+ ];
591
659
  const clientRoots = await Promise.all(
592
660
  (options.clientRoots ?? []).map((item) =>
593
661
  existingDirectory(resolveFileUri(item)),
594
662
  ),
595
663
  );
596
664
  if (clientRoots.length)
597
- return { candidates: clientRoots, trustedRoots: clientRoots };
665
+ return {
666
+ candidates: clientRoots,
667
+ trustedRoots: await withCanonical(clientRoots),
668
+ };
598
669
 
599
670
  if (env.AST_MCP_PROJECT_ROOT) {
600
671
  const selected = path.resolve(cwd, env.AST_MCP_PROJECT_ROOT);
601
- return { candidates: [selected], trustedRoots: [selected] };
672
+ return {
673
+ candidates: [selected],
674
+ trustedRoots: await withCanonical([selected]),
675
+ };
602
676
  }
603
677
 
604
678
  const legacy = env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean);
605
- if (legacy?.length)
679
+ if (legacy?.length) {
680
+ const candidates = legacy.map((item) => path.resolve(cwd, item));
606
681
  return {
607
- candidates: legacy.map((item) => path.resolve(cwd, item)),
608
- trustedRoots: [cwd],
682
+ candidates,
683
+ trustedRoots: await withCanonical([cwd]),
609
684
  };
685
+ }
610
686
 
611
- return { candidates: [cwd], trustedRoots: [cwd] };
687
+ return {
688
+ candidates: [cwd],
689
+ trustedRoots: await withCanonical([cwd]),
690
+ };
612
691
  }
613
692
 
614
693
  function matchedProjectRoots(
@@ -639,10 +718,6 @@ function defaultInternalConfig(candidates: string[]): InternalConfig {
639
718
  session_timeout_ms: 30 * 60 * 1000,
640
719
  },
641
720
  safety: {
642
- allow_any_path: false,
643
- allow_external_roots: false,
644
- allow_temp_directory: true,
645
- follow_symlinks: false,
646
721
  hook: { allow_tools: [], block_tools: [], enabled: true },
647
722
  require_hash: true,
648
723
  },
@@ -669,16 +744,39 @@ function resolvedFormatting(
669
744
  value: InternalConfig,
670
745
  dprintConfig: string,
671
746
  ): ResolvedConfig["formatting"] {
747
+ const version = value.version ?? 1;
672
748
  return {
673
749
  dprintConfig,
674
750
  enabled: value.formatting?.enabled ?? true,
675
- formatters: (value.formatting?.formatters ?? []).map((formatter) => ({
676
- args: formatter.args ?? [],
677
- command: formatter.command,
678
- extensions: formatter.extensions ?? [],
679
- globs: formatter.globs ?? [],
680
- timeoutMs: formatter.timeout_ms ?? 30_000,
681
- })),
751
+ fallback:
752
+ value.formatting?.fallback ?? (version === 2 ? "preserve" : "dprint"),
753
+ formatters: (value.formatting?.formatters ?? []).map(
754
+ (formatter, index) => ({
755
+ args: formatter.args ?? [],
756
+ command: formatter.command,
757
+ enabled: formatter.enabled,
758
+ extensions: formatter.extensions ?? [],
759
+ globs: formatter.globs ?? [],
760
+ id: formatter.id ?? `legacy-${index + 1}`,
761
+ mode: formatter.mode ?? "stdout",
762
+ timeoutMs: formatter.timeout_ms ?? 30_000,
763
+ }),
764
+ ),
765
+ };
766
+ }
767
+
768
+ function resolvedFiles(value: InternalConfig): ResolvedConfig["files"] {
769
+ return {
770
+ patch: {
771
+ aiderMatchers: value.files?.patch?.aider_matchers ?? [
772
+ "exact",
773
+ "whitespace",
774
+ "relative-indentation",
775
+ "diff-match-patch",
776
+ ],
777
+ strategies: value.files?.patch?.strategies ?? ["ast", "aider_block"],
778
+ },
779
+ read: { modes: value.files?.read?.modes ?? ["ast", "text"] },
682
780
  };
683
781
  }
684
782
 
@@ -703,17 +801,31 @@ function resolvedHook(value: InternalConfig["safety"]) {
703
801
  };
704
802
  }
705
803
 
804
+ type ConfiguredPathRule = PathRuleV2;
805
+
706
806
  function resolvedSafety(value: InternalConfig): ResolvedConfig["safety"] {
807
+ const version = value.version ?? 1;
707
808
  return {
708
809
  allowAnyPath: withDefault(value.safety?.allow_any_path, false),
709
810
  allowExternalRoots: withDefault(value.safety?.allow_external_roots, false),
710
- allowTempDirectory: withDefault(value.safety?.allow_temp_directory, true),
811
+ allowTempDirectory: withDefault(
812
+ value.safety?.allow_temp_directory,
813
+ version === 1,
814
+ ),
711
815
  followSymlinks: withDefault(value.safety?.follow_symlinks, false),
712
816
  hook: resolvedHook(value.safety),
713
817
  requireHash: withDefault(value.safety?.require_hash, true),
714
818
  };
715
819
  }
716
820
 
821
+ function layerPathRules(
822
+ layer: LoadedLayer,
823
+ source: "global" | "project",
824
+ ): Array<{ rule: ConfiguredPathRule; source: "global" | "project" }> {
825
+ if (layer.value?.version !== 2) return [];
826
+ return (layer.value.paths ?? []).map((rule) => ({ rule, source }));
827
+ }
828
+
717
829
  function resolvedConfiguration(args: {
718
830
  candidates: string[];
719
831
  dprintConfig: string;
@@ -736,13 +848,32 @@ function resolvedConfiguration(args: {
736
848
  trustedRoots,
737
849
  value,
738
850
  } = args;
851
+ const pathRules = [
852
+ ...layerPathRules(global, "global"),
853
+ ...layerPathRules(project, "project"),
854
+ ];
739
855
  return {
740
856
  dependencies: {
741
857
  astBroBinary: value.dependencies?.ast_bro_binary,
742
858
  dprintBinary: value.dependencies?.dprint_binary,
743
859
  },
860
+ files: resolvedFiles(value),
744
861
  formatting: resolvedFormatting(value, dprintConfig),
862
+ generation: 0,
745
863
  http: resolvedHttp(value),
864
+ paths: pathRules.map(({ rule, source }) => ({
865
+ excludes: rule.excludes ?? [],
866
+ followSymlinks: rule.follow_symlinks ?? false,
867
+ id: rule.id,
868
+ includes: rule.includes ?? ["**/*"],
869
+ path: rule.path,
870
+ policies: {
871
+ delete: rule.policies.delete ?? rule.policies.write,
872
+ read: rule.policies.read,
873
+ write: rule.policies.write,
874
+ },
875
+ source,
876
+ })),
746
877
  projectRoot,
747
878
  provenance,
748
879
  safety: resolvedSafety(value),
@@ -752,7 +883,7 @@ function resolvedConfiguration(args: {
752
883
  project: project.value ? project.path : undefined,
753
884
  },
754
885
  trustedRoots,
755
- version: 1,
886
+ version: value.version ?? 1,
756
887
  workspace: { roots: value.workspace?.roots ?? candidates },
757
888
  };
758
889
  }
@@ -834,6 +965,10 @@ async function resolveForProject(
834
965
  { name: "environment", value: environment.value },
835
966
  ];
836
967
  const value = merge(...layers.map((item) => item.value));
968
+ const sourceVersions = [global.value?.version, project.value?.version].filter(
969
+ (version): version is 1 | 2 => version !== undefined,
970
+ );
971
+ if (sourceVersions.includes(1)) value.version = 1;
837
972
  const dprint = await resolvedDprint(value);
838
973
  const key = resolutionCacheKey({
839
974
  candidates,
@@ -863,14 +998,70 @@ async function resolveForProject(
863
998
  return resolved;
864
999
  }
865
1000
 
1001
+ function projectRelativePolicyPath(
1002
+ config: ResolvedConfig,
1003
+ rule: ResolvedConfig["paths"][number],
1004
+ ): string | undefined {
1005
+ if (rule.source !== "project" || !config.sources.project) return undefined;
1006
+ const relative = path.relative(
1007
+ path.dirname(config.sources.project),
1008
+ rule.path,
1009
+ );
1010
+ const outside =
1011
+ relative === ".." ||
1012
+ relative.startsWith(`..${path.sep}`) ||
1013
+ path.isAbsolute(relative);
1014
+ return outside ? undefined : relative || ".";
1015
+ }
1016
+
866
1017
  function policy(config: ResolvedConfig) {
867
1018
  return JSON.stringify({
868
1019
  dependencies: config.dependencies,
1020
+ files: config.files,
869
1021
  formatting: config.formatting,
870
1022
  safety: config.safety,
871
1023
  });
872
1024
  }
873
1025
 
1026
+ function pathRulePolicy(rule: ResolvedConfig["paths"][number]) {
1027
+ const { path: _path, ...policy } = rule;
1028
+ return JSON.stringify({
1029
+ ...policy,
1030
+ excludes: [...policy.excludes].sort(),
1031
+ includes: [...policy.includes].sort(),
1032
+ });
1033
+ }
1034
+
1035
+ function pathRuleEquivalent(
1036
+ leftConfig: ResolvedConfig,
1037
+ rightConfig: ResolvedConfig,
1038
+ left: ResolvedConfig["paths"][number],
1039
+ right: ResolvedConfig["paths"][number],
1040
+ ) {
1041
+ if (pathRulePolicy(left) !== pathRulePolicy(right)) return false;
1042
+ if (left.path === right.path) return true;
1043
+ const leftRelative = projectRelativePolicyPath(leftConfig, left);
1044
+ const rightRelative = projectRelativePolicyPath(rightConfig, right);
1045
+ return leftRelative !== undefined && leftRelative === rightRelative;
1046
+ }
1047
+
1048
+ function pathPoliciesEquivalent(left: ResolvedConfig, right: ResolvedConfig) {
1049
+ if (left.paths.length !== right.paths.length) return false;
1050
+ const unmatched = [...right.paths];
1051
+ for (const rule of left.paths) {
1052
+ const index = unmatched.findIndex((candidate) =>
1053
+ pathRuleEquivalent(left, right, rule, candidate),
1054
+ );
1055
+ if (index < 0) return false;
1056
+ unmatched.splice(index, 1);
1057
+ }
1058
+ return true;
1059
+ }
1060
+
1061
+ function policiesEquivalent(left: ResolvedConfig, right: ResolvedConfig) {
1062
+ return policy(left) === policy(right) && pathPoliciesEquivalent(left, right);
1063
+ }
1064
+
874
1065
  export async function resolveConfig(
875
1066
  options: ResolveConfigOptions = {},
876
1067
  ): Promise<ResolvedConfig> {
@@ -882,7 +1073,7 @@ export async function resolveConfig(
882
1073
  ),
883
1074
  );
884
1075
  const first = configs[0] as ResolvedConfig;
885
- if (configs.some((config) => policy(config) !== policy(first)))
1076
+ if (configs.some((config) => !policiesEquivalent(config, first)))
886
1077
  throw new ConfigurationError(
887
1078
  `Request spans workspace roots with conflicting ast-mcp policies: ${matched.join(", ")}`,
888
1079
  );
@@ -907,6 +1098,13 @@ export async function withConfig<T>(
907
1098
  return activeConfig.run(config, operation);
908
1099
  }
909
1100
 
1101
+ export async function withResolvedConfig<T>(
1102
+ config: ResolvedConfig,
1103
+ operation: () => Promise<T>,
1104
+ ): Promise<T> {
1105
+ return activeConfig.run(config, operation);
1106
+ }
1107
+
910
1108
  export function clearConfigCache() {
911
1109
  dprintConfigCache.clear();
912
1110
  layerCache.clear();