@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
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,68 +34,82 @@ 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({
40
+ allow_any_path: z.boolean().optional(),
84
41
  allow_external_roots: z.boolean().optional(),
42
+ allow_temp_directory: z.boolean().optional(),
85
43
  follow_symlinks: z.boolean().optional(),
86
44
  hook: hookSchema.optional(),
87
45
  require_hash: z.boolean().optional(),
88
46
  })
89
47
  .strict()
90
48
  .optional(),
91
- version: z.literal(1).optional(),
92
- workspace: z
93
- .object({ roots: z.array(z.string().min(1)).min(1).optional() })
94
- .strict()
95
- .optional(),
49
+ version: z.literal(schemaVersion).optional(),
50
+ workspace: workspaceSchema.optional(),
96
51
  })
97
52
  .strict();
98
53
 
99
- type AstMcpFileConfig = z.infer<typeof fileSchema>;
54
+ type AstMcpFileConfig =
55
+ | z.infer<typeof fileV1Schema>
56
+ | z.infer<typeof fileV2Schema>;
100
57
 
101
58
  export interface ResolvedConfig {
102
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
+ };
103
69
  formatting: {
104
70
  dprintConfig: string;
105
71
  enabled: boolean;
72
+ fallback: "preserve" | "dprint" | "reject";
106
73
  formatters: Array<{
107
74
  args: string[];
108
75
  command: string;
76
+ enabled?: boolean;
109
77
  extensions: string[];
110
78
  globs: string[];
79
+ id: string;
80
+ mode: "stdout" | "in_place";
111
81
  timeoutMs: number;
112
82
  }>;
113
83
  };
84
+ generation: number;
114
85
  http: {
115
86
  host: string;
116
87
  port: number;
117
88
  sessionTimeoutMs: number;
118
89
  sessionSweepIntervalMs: number;
119
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
+ }>;
120
100
  projectRoot: string;
121
101
  provenance: Record<string, "default" | "global" | "project" | "environment">;
122
102
  safety: {
103
+ allowAnyPath: boolean;
123
104
  allowExternalRoots: boolean;
105
+ allowTempDirectory: boolean;
124
106
  followSymlinks: boolean;
125
107
  hook: { allowTools: string[]; blockTools: string[]; enabled: boolean };
126
108
  requireHash: boolean;
127
109
  };
128
- sources: {
129
- project?: string;
130
- global?: string;
131
- environment: string[];
132
- };
110
+ sources: { project?: string; global?: string; environment: string[] };
133
111
  trustedRoots: string[];
134
- version: 1;
112
+ version: 1 | 2;
135
113
  workspace: { roots: string[] };
136
114
  }
137
115
 
@@ -152,14 +130,27 @@ interface LoadedLayer {
152
130
 
153
131
  interface InternalConfig {
154
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
+ };
155
142
  formatting?: {
156
143
  dprint_config?: string;
157
144
  enabled?: boolean;
145
+ fallback?: "preserve" | "dprint" | "reject";
158
146
  formatters?: Array<{
159
147
  args?: string[];
160
148
  command: string;
149
+ enabled?: boolean;
161
150
  extensions?: string[];
162
151
  globs?: string[];
152
+ id?: string;
153
+ mode?: "stdout" | "in_place";
163
154
  timeout_ms?: number;
164
155
  }>;
165
156
  };
@@ -169,8 +160,18 @@ interface InternalConfig {
169
160
  session_timeout_ms?: number;
170
161
  session_sweep_interval_ms?: number;
171
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
+ }>;
172
171
  safety?: {
172
+ allow_any_path?: boolean;
173
173
  allow_external_roots?: boolean;
174
+ allow_temp_directory?: boolean;
174
175
  follow_symlinks?: boolean;
175
176
  hook?: {
176
177
  allow_tools?: string[];
@@ -179,7 +180,7 @@ interface InternalConfig {
179
180
  };
180
181
  require_hash?: boolean;
181
182
  };
182
- version?: 1;
183
+ version?: 1 | 2;
183
184
  workspace?: { roots?: string[] };
184
185
  }
185
186
 
@@ -320,11 +321,51 @@ function _pathValue(value: string, base: string) {
320
321
  return path.resolve(base, value);
321
322
  }
322
323
 
323
- function normalizeLayer(
324
+ async function canonicalConfigurationPath(value: string): Promise<string> {
325
+ return canonicalizePath(value);
326
+ }
327
+
328
+ async function normalizeLayer(
324
329
  value: AstMcpFileConfig,
325
330
  filePath: string,
326
- ): AstMcpFileConfig {
327
- 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;
328
369
  }
329
370
 
330
371
  async function loadLayer(filePath: string): Promise<LoadedLayer> {
@@ -340,23 +381,10 @@ async function loadLayer(filePath: string): Promise<LoadedLayer> {
340
381
 
341
382
  const promise = (async () => {
342
383
  if (!metadata) return { fingerprint, path: filePath };
343
- let parsed: unknown;
344
- try {
345
- parsed = Bun.TOML.parse(await Bun.file(filePath).text());
346
- } catch (error) {
347
- throw new ConfigurationError(
348
- `${filePath}: invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
349
- );
350
- }
351
- const result = fileSchema.safeParse(parsed);
352
- if (!result.success)
353
- throw new ConfigurationError(
354
- `${filePath}: invalid configuration: ${diagnostic(result.error)}`,
355
- );
356
384
  return {
357
385
  fingerprint,
358
- path: filePath,
359
- value: normalizeLayer(result.data, filePath),
386
+ path: await canonicalConfigurationPath(filePath),
387
+ value: await normalizeLayer(await parseLayerValue(filePath), filePath),
360
388
  };
361
389
  })();
362
390
  layerCache.set(filePath, { fingerprint, promise });
@@ -457,13 +485,29 @@ function environmentHttp(env: NodeJS.ProcessEnv, usage: EnvironmentUsage) {
457
485
  }
458
486
 
459
487
  function environmentSafety(env: NodeJS.ProcessEnv, usage: EnvironmentUsage) {
460
- const allowExternal = usage.use(
488
+ const allowAnyPath = usage.use(
489
+ "AST_MCP_ALLOW_ANY_PATH",
490
+ booleanEnvironment(env, "AST_MCP_ALLOW_ANY_PATH"),
491
+ );
492
+ const allowExternalRoots = usage.use(
461
493
  "AST_MCP_ALLOW_EXTERNAL_ROOTS",
462
494
  booleanEnvironment(env, "AST_MCP_ALLOW_EXTERNAL_ROOTS"),
463
495
  );
464
- return allowExternal === undefined
465
- ? undefined
466
- : { allow_external_roots: allowExternal };
496
+ const allowTempDirectory = usage.use(
497
+ "AST_MCP_ALLOW_TEMP_DIRECTORY",
498
+ booleanEnvironment(env, "AST_MCP_ALLOW_TEMP_DIRECTORY"),
499
+ );
500
+ if (
501
+ allowAnyPath === undefined &&
502
+ allowExternalRoots === undefined &&
503
+ allowTempDirectory === undefined
504
+ )
505
+ return undefined;
506
+ return {
507
+ allow_any_path: allowAnyPath,
508
+ allow_external_roots: allowExternalRoots,
509
+ allow_temp_directory: allowTempDirectory,
510
+ };
467
511
  }
468
512
 
469
513
  function environmentLayer(
@@ -491,14 +535,21 @@ function environmentLayer(
491
535
  const leaves = [
492
536
  "version",
493
537
  "workspace.roots",
538
+ "paths",
539
+ "safety.allow_any_path",
494
540
  "safety.allow_external_roots",
541
+ "safety.allow_temp_directory",
495
542
  "safety.follow_symlinks",
496
543
  "safety.hook.allow_tools",
497
544
  "safety.hook.block_tools",
498
545
  "safety.hook.enabled",
499
546
  "safety.require_hash",
547
+ "files.read.modes",
548
+ "files.patch.strategies",
549
+ "files.patch.aider_matchers",
500
550
  "formatting.dprint_config",
501
551
  "formatting.enabled",
552
+ "formatting.fallback",
502
553
  "formatting.formatters",
503
554
  "dependencies.ast_bro_binary",
504
555
  "dependencies.dprint_binary",
@@ -520,43 +571,78 @@ function leaf(value: InternalConfig, dotted: (typeof leaves)[number]) {
520
571
  );
521
572
  }
522
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
+
523
641
  function merge(...layers: InternalConfig[]): InternalConfig {
524
642
  const result: InternalConfig = {};
525
643
  for (const layer of layers) {
526
644
  if (layer.version !== undefined) result.version = layer.version;
527
- for (const section of [
528
- "workspace",
529
- "safety",
530
- "formatting",
531
- "dependencies",
532
- "http",
533
- ] as const) {
534
- const incoming = layer[section];
535
- if (!incoming) continue;
536
- const previousHook = result.safety?.hook;
537
- const defined = Object.fromEntries(
538
- Object.entries(incoming).filter(([, value]) => value !== undefined),
539
- );
540
- result[section] = {
541
- ...(result[section] as object | undefined),
542
- ...defined,
543
- } as never;
544
- if (section === "safety") {
545
- const safetyIncoming = incoming as InternalConfig["safety"];
546
- if (safetyIncoming?.hook)
547
- result.safety = {
548
- ...result.safety,
549
- hook: {
550
- ...previousHook,
551
- ...Object.fromEntries(
552
- Object.entries(safetyIncoming.hook).filter(
553
- ([, value]) => value !== undefined,
554
- ),
555
- ),
556
- },
557
- };
558
- }
559
- }
645
+ for (const section of mergeSections) mergeSection(result, layer, section);
560
646
  }
561
647
  return result;
562
648
  }
@@ -564,27 +650,44 @@ function merge(...layers: InternalConfig[]): InternalConfig {
564
650
  async function projectRoots(options: ResolveConfigOptions) {
565
651
  const env = options.env ?? process.env;
566
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
+ ];
567
659
  const clientRoots = await Promise.all(
568
660
  (options.clientRoots ?? []).map((item) =>
569
661
  existingDirectory(resolveFileUri(item)),
570
662
  ),
571
663
  );
572
664
  if (clientRoots.length)
573
- return { candidates: clientRoots, trustedRoots: clientRoots };
665
+ return {
666
+ candidates: clientRoots,
667
+ trustedRoots: await withCanonical(clientRoots),
668
+ };
574
669
 
575
670
  if (env.AST_MCP_PROJECT_ROOT) {
576
671
  const selected = path.resolve(cwd, env.AST_MCP_PROJECT_ROOT);
577
- return { candidates: [selected], trustedRoots: [selected] };
672
+ return {
673
+ candidates: [selected],
674
+ trustedRoots: await withCanonical([selected]),
675
+ };
578
676
  }
579
677
 
580
678
  const legacy = env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean);
581
- if (legacy?.length)
679
+ if (legacy?.length) {
680
+ const candidates = legacy.map((item) => path.resolve(cwd, item));
582
681
  return {
583
- candidates: legacy.map((item) => path.resolve(cwd, item)),
584
- trustedRoots: [cwd],
682
+ candidates,
683
+ trustedRoots: await withCanonical([cwd]),
585
684
  };
685
+ }
586
686
 
587
- return { candidates: [cwd], trustedRoots: [cwd] };
687
+ return {
688
+ candidates: [cwd],
689
+ trustedRoots: await withCanonical([cwd]),
690
+ };
588
691
  }
589
692
 
590
693
  function matchedProjectRoots(
@@ -615,8 +718,6 @@ function defaultInternalConfig(candidates: string[]): InternalConfig {
615
718
  session_timeout_ms: 30 * 60 * 1000,
616
719
  },
617
720
  safety: {
618
- allow_external_roots: false,
619
- follow_symlinks: false,
620
721
  hook: { allow_tools: [], block_tools: [], enabled: true },
621
722
  require_hash: true,
622
723
  },
@@ -643,16 +744,39 @@ function resolvedFormatting(
643
744
  value: InternalConfig,
644
745
  dprintConfig: string,
645
746
  ): ResolvedConfig["formatting"] {
747
+ const version = value.version ?? 1;
646
748
  return {
647
749
  dprintConfig,
648
750
  enabled: value.formatting?.enabled ?? true,
649
- formatters: (value.formatting?.formatters ?? []).map((formatter) => ({
650
- args: formatter.args ?? [],
651
- command: formatter.command,
652
- extensions: formatter.extensions ?? [],
653
- globs: formatter.globs ?? [],
654
- timeoutMs: formatter.timeout_ms ?? 30_000,
655
- })),
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"] },
656
780
  };
657
781
  }
658
782
 
@@ -677,15 +801,31 @@ function resolvedHook(value: InternalConfig["safety"]) {
677
801
  };
678
802
  }
679
803
 
804
+ type ConfiguredPathRule = PathRuleV2;
805
+
680
806
  function resolvedSafety(value: InternalConfig): ResolvedConfig["safety"] {
807
+ const version = value.version ?? 1;
681
808
  return {
809
+ allowAnyPath: withDefault(value.safety?.allow_any_path, false),
682
810
  allowExternalRoots: withDefault(value.safety?.allow_external_roots, false),
811
+ allowTempDirectory: withDefault(
812
+ value.safety?.allow_temp_directory,
813
+ version === 1,
814
+ ),
683
815
  followSymlinks: withDefault(value.safety?.follow_symlinks, false),
684
816
  hook: resolvedHook(value.safety),
685
817
  requireHash: withDefault(value.safety?.require_hash, true),
686
818
  };
687
819
  }
688
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
+
689
829
  function resolvedConfiguration(args: {
690
830
  candidates: string[];
691
831
  dprintConfig: string;
@@ -708,13 +848,32 @@ function resolvedConfiguration(args: {
708
848
  trustedRoots,
709
849
  value,
710
850
  } = args;
851
+ const pathRules = [
852
+ ...layerPathRules(global, "global"),
853
+ ...layerPathRules(project, "project"),
854
+ ];
711
855
  return {
712
856
  dependencies: {
713
857
  astBroBinary: value.dependencies?.ast_bro_binary,
714
858
  dprintBinary: value.dependencies?.dprint_binary,
715
859
  },
860
+ files: resolvedFiles(value),
716
861
  formatting: resolvedFormatting(value, dprintConfig),
862
+ generation: 0,
717
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
+ })),
718
877
  projectRoot,
719
878
  provenance,
720
879
  safety: resolvedSafety(value),
@@ -724,7 +883,7 @@ function resolvedConfiguration(args: {
724
883
  project: project.value ? project.path : undefined,
725
884
  },
726
885
  trustedRoots,
727
- version: 1,
886
+ version: value.version ?? 1,
728
887
  workspace: { roots: value.workspace?.roots ?? candidates },
729
888
  };
730
889
  }
@@ -806,6 +965,10 @@ async function resolveForProject(
806
965
  { name: "environment", value: environment.value },
807
966
  ];
808
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;
809
972
  const dprint = await resolvedDprint(value);
810
973
  const key = resolutionCacheKey({
811
974
  candidates,
@@ -835,14 +998,70 @@ async function resolveForProject(
835
998
  return resolved;
836
999
  }
837
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
+
838
1017
  function policy(config: ResolvedConfig) {
839
1018
  return JSON.stringify({
840
1019
  dependencies: config.dependencies,
1020
+ files: config.files,
841
1021
  formatting: config.formatting,
842
1022
  safety: config.safety,
843
1023
  });
844
1024
  }
845
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
+
846
1065
  export async function resolveConfig(
847
1066
  options: ResolveConfigOptions = {},
848
1067
  ): Promise<ResolvedConfig> {
@@ -854,7 +1073,7 @@ export async function resolveConfig(
854
1073
  ),
855
1074
  );
856
1075
  const first = configs[0] as ResolvedConfig;
857
- if (configs.some((config) => policy(config) !== policy(first)))
1076
+ if (configs.some((config) => !policiesEquivalent(config, first)))
858
1077
  throw new ConfigurationError(
859
1078
  `Request spans workspace roots with conflicting ast-mcp policies: ${matched.join(", ")}`,
860
1079
  );
@@ -879,6 +1098,13 @@ export async function withConfig<T>(
879
1098
  return activeConfig.run(config, operation);
880
1099
  }
881
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
+
882
1108
  export function clearConfigCache() {
883
1109
  dprintConfigCache.clear();
884
1110
  layerCache.clear();