@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
package/src/config.ts CHANGED
@@ -1,67 +1,38 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
- import { stat } from "node:fs/promises";
2
+ import { realpath, stat } from "node:fs/promises";
3
3
  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
+ type WorktreesMode,
13
+ workspaceSchema,
14
+ } from "./config-schema-common";
15
+ import {
16
+ fileV2Schema,
17
+ type PathPolicy,
18
+ type PathRuleV2,
19
+ } from "./config-v2-schema";
7
20
  import { collectRequestPaths, normalizeConfigLayer } from "./helpers/config";
21
+ import {
22
+ clearGitWorktreeCache,
23
+ linkedWorktrees,
24
+ } from "./runtime/git-worktrees";
25
+ import { canonicalizePath } from "./runtime/path-utils";
8
26
 
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
27
+ export type { WorktreesMode };
28
+
29
+ const schemaVersion = 1 as const;
30
+ const hookSchema = createHookSchema(64);
31
+
32
+ const formatterSchema = createFormatterSchema({});
33
+ const fileV1Schema = z
57
34
  .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(),
35
+ dependencies: dependenciesSchema.optional(),
65
36
  formatting: z
66
37
  .object({
67
38
  dprint_config: z.string().min(1).optional(),
@@ -70,15 +41,7 @@ const fileSchema = z
70
41
  })
71
42
  .strict()
72
43
  .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(),
44
+ http: httpSchema.optional(),
82
45
  safety: z
83
46
  .object({
84
47
  allow_any_path: z.boolean().optional(),
@@ -90,35 +53,60 @@ const fileSchema = z
90
53
  })
91
54
  .strict()
92
55
  .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(),
56
+ version: z.literal(schemaVersion).optional(),
57
+ workspace: workspaceSchema.optional(),
98
58
  })
99
59
  .strict();
100
60
 
101
- type AstMcpFileConfig = z.infer<typeof fileSchema>;
61
+ type AstMcpFileConfig =
62
+ | z.infer<typeof fileV1Schema>
63
+ | z.infer<typeof fileV2Schema>;
102
64
 
103
65
  export interface ResolvedConfig {
104
66
  dependencies: { astBroBinary?: string; dprintBinary?: string };
67
+ files: {
68
+ patch: {
69
+ aiderMatchers: Array<
70
+ "exact" | "whitespace" | "relative-indentation" | "diff-match-patch"
71
+ >;
72
+ strategies: Array<"ast" | "aider_block">;
73
+ };
74
+ read: { modes: Array<"ast" | "text"> };
75
+ };
105
76
  formatting: {
106
77
  dprintConfig: string;
107
78
  enabled: boolean;
79
+ fallback: "preserve" | "dprint" | "reject";
108
80
  formatters: Array<{
109
81
  args: string[];
110
82
  command: string;
83
+ enabled?: boolean;
111
84
  extensions: string[];
112
85
  globs: string[];
86
+ id: string;
87
+ mode: "stdout" | "in_place";
113
88
  timeoutMs: number;
114
89
  }>;
115
90
  };
91
+ generation: number;
116
92
  http: {
117
93
  host: string;
118
94
  port: number;
119
95
  sessionTimeoutMs: number;
120
96
  sessionSweepIntervalMs: number;
121
97
  };
98
+ mcp: {
99
+ configuration: { enabled: boolean; requireApproval: boolean };
100
+ };
101
+ paths: Array<{
102
+ excludes: string[];
103
+ followSymlinks: boolean;
104
+ id: string;
105
+ includes: string[];
106
+ path: string;
107
+ policies: { delete: PathPolicy; read: PathPolicy; write: PathPolicy };
108
+ source: "global" | "project";
109
+ }>;
122
110
  projectRoot: string;
123
111
  provenance: Record<string, "default" | "global" | "project" | "environment">;
124
112
  safety: {
@@ -129,14 +117,14 @@ export interface ResolvedConfig {
129
117
  hook: { allowTools: string[]; blockTools: string[]; enabled: boolean };
130
118
  requireHash: boolean;
131
119
  };
132
- sources: {
133
- project?: string;
134
- global?: string;
135
- environment: string[];
136
- };
120
+ sources: { project?: string; global?: string; environment: string[] };
137
121
  trustedRoots: string[];
138
- version: 1;
139
- workspace: { roots: string[] };
122
+ version: 1 | 2;
123
+ workspace: {
124
+ linkedWorktrees: string[];
125
+ roots: string[];
126
+ worktrees: WorktreesMode;
127
+ };
140
128
  }
141
129
 
142
130
  export interface ResolveConfigOptions {
@@ -156,14 +144,27 @@ interface LoadedLayer {
156
144
 
157
145
  interface InternalConfig {
158
146
  dependencies?: { ast_bro_binary?: string; dprint_binary?: string };
147
+ files?: {
148
+ patch?: {
149
+ aider_matchers?: Array<
150
+ "exact" | "whitespace" | "relative-indentation" | "diff-match-patch"
151
+ >;
152
+ strategies?: Array<"ast" | "aider_block">;
153
+ };
154
+ read?: { modes?: Array<"ast" | "text"> };
155
+ };
159
156
  formatting?: {
160
157
  dprint_config?: string;
161
158
  enabled?: boolean;
159
+ fallback?: "preserve" | "dprint" | "reject";
162
160
  formatters?: Array<{
163
161
  args?: string[];
164
162
  command: string;
163
+ enabled?: boolean;
165
164
  extensions?: string[];
166
165
  globs?: string[];
166
+ id?: string;
167
+ mode?: "stdout" | "in_place";
167
168
  timeout_ms?: number;
168
169
  }>;
169
170
  };
@@ -173,6 +174,17 @@ interface InternalConfig {
173
174
  session_timeout_ms?: number;
174
175
  session_sweep_interval_ms?: number;
175
176
  };
177
+ mcp?: {
178
+ configuration?: { enabled?: boolean; require_approval?: boolean };
179
+ };
180
+ paths?: Array<{
181
+ excludes?: string[];
182
+ follow_symlinks?: boolean;
183
+ id: string;
184
+ includes?: string[];
185
+ path: string;
186
+ policies: { delete?: PathPolicy; read: PathPolicy; write: PathPolicy };
187
+ }>;
176
188
  safety?: {
177
189
  allow_any_path?: boolean;
178
190
  allow_external_roots?: boolean;
@@ -185,8 +197,8 @@ interface InternalConfig {
185
197
  };
186
198
  require_hash?: boolean;
187
199
  };
188
- version?: 1;
189
- workspace?: { roots?: string[] };
200
+ version?: 1 | 2;
201
+ workspace?: { roots?: string[]; worktrees?: WorktreesMode };
190
202
  }
191
203
 
192
204
  class ConfigurationError extends Error {
@@ -326,11 +338,51 @@ function _pathValue(value: string, base: string) {
326
338
  return path.resolve(base, value);
327
339
  }
328
340
 
329
- function normalizeLayer(
341
+ async function canonicalConfigurationPath(value: string): Promise<string> {
342
+ return canonicalizePath(value);
343
+ }
344
+
345
+ async function normalizeLayer(
330
346
  value: AstMcpFileConfig,
331
347
  filePath: string,
332
- ): AstMcpFileConfig {
333
- return normalizeConfigLayer(value, filePath);
348
+ ): Promise<AstMcpFileConfig> {
349
+ const normalized = normalizeConfigLayer(value, filePath);
350
+ if (normalized.version !== 2 || !normalized.paths) return normalized;
351
+ return {
352
+ ...normalized,
353
+ paths: await Promise.all(
354
+ normalized.paths.map(async (rule) => ({
355
+ ...rule,
356
+ path: await canonicalConfigurationPath(rule.path),
357
+ })),
358
+ ),
359
+ };
360
+ }
361
+
362
+ async function parseLayerValue(filePath: string): Promise<AstMcpFileConfig> {
363
+ let parsed: unknown;
364
+ try {
365
+ parsed = Bun.TOML.parse(await Bun.file(filePath).text());
366
+ } catch (error) {
367
+ throw new ConfigurationError(
368
+ `${filePath}: invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
369
+ );
370
+ }
371
+ const version =
372
+ parsed &&
373
+ typeof parsed === "object" &&
374
+ "version" in parsed &&
375
+ parsed.version === 2
376
+ ? 2
377
+ : 1;
378
+ const result = (version === 2 ? fileV2Schema : fileV1Schema).safeParse(
379
+ parsed,
380
+ );
381
+ if (!result.success)
382
+ throw new ConfigurationError(
383
+ `${filePath}: invalid configuration: ${diagnostic(result.error)}`,
384
+ );
385
+ return { ...result.data, version } as AstMcpFileConfig;
334
386
  }
335
387
 
336
388
  async function loadLayer(filePath: string): Promise<LoadedLayer> {
@@ -346,23 +398,10 @@ async function loadLayer(filePath: string): Promise<LoadedLayer> {
346
398
 
347
399
  const promise = (async () => {
348
400
  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
401
  return {
363
402
  fingerprint,
364
- path: filePath,
365
- value: normalizeLayer(result.data, filePath),
403
+ path: await canonicalConfigurationPath(filePath),
404
+ value: await normalizeLayer(await parseLayerValue(filePath), filePath),
366
405
  };
367
406
  })();
368
407
  layerCache.set(filePath, { fingerprint, promise });
@@ -513,6 +552,10 @@ function environmentLayer(
513
552
  const leaves = [
514
553
  "version",
515
554
  "workspace.roots",
555
+ "workspace.worktrees",
556
+ "mcp.configuration.enabled",
557
+ "mcp.configuration.require_approval",
558
+ "paths",
516
559
  "safety.allow_any_path",
517
560
  "safety.allow_external_roots",
518
561
  "safety.allow_temp_directory",
@@ -521,8 +564,12 @@ const leaves = [
521
564
  "safety.hook.block_tools",
522
565
  "safety.hook.enabled",
523
566
  "safety.require_hash",
567
+ "files.read.modes",
568
+ "files.patch.strategies",
569
+ "files.patch.aider_matchers",
524
570
  "formatting.dprint_config",
525
571
  "formatting.enabled",
572
+ "formatting.fallback",
526
573
  "formatting.formatters",
527
574
  "dependencies.ast_bro_binary",
528
575
  "dependencies.dprint_binary",
@@ -544,43 +591,100 @@ function leaf(value: InternalConfig, dotted: (typeof leaves)[number]) {
544
591
  );
545
592
  }
546
593
 
594
+ const mergeSections = [
595
+ "workspace",
596
+ "safety",
597
+ "files",
598
+ "formatting",
599
+ "dependencies",
600
+ "http",
601
+ "mcp",
602
+ ] as const;
603
+
604
+ type MergeSection = (typeof mergeSections)[number];
605
+
606
+ function definedProperties(value: object): object {
607
+ return Object.fromEntries(
608
+ Object.entries(value).filter(([, entry]) => entry !== undefined),
609
+ );
610
+ }
611
+
612
+ function mergeSafetyHook(
613
+ result: InternalConfig,
614
+ incoming: InternalConfig["safety"],
615
+ previousHook: NonNullable<InternalConfig["safety"]>["hook"],
616
+ ): void {
617
+ if (!incoming?.hook) return;
618
+ result.safety = {
619
+ ...result.safety,
620
+ hook: {
621
+ ...previousHook,
622
+ ...definedProperties(incoming.hook),
623
+ },
624
+ };
625
+ }
626
+
627
+ function mergeFileMethods(
628
+ result: InternalConfig,
629
+ incoming: InternalConfig["files"],
630
+ previous: InternalConfig["files"],
631
+ ): void {
632
+ if (!incoming) return;
633
+ result.files = {
634
+ patch: { ...previous?.patch, ...incoming.patch },
635
+ read: { ...previous?.read, ...incoming.read },
636
+ };
637
+ }
638
+
639
+ function mergeMcpConfiguration(
640
+ result: InternalConfig,
641
+ incoming: InternalConfig["mcp"],
642
+ previous: InternalConfig["mcp"],
643
+ ): void {
644
+ if (!incoming?.configuration) return;
645
+ result.mcp = {
646
+ configuration: {
647
+ ...previous?.configuration,
648
+ ...definedProperties(incoming.configuration),
649
+ },
650
+ };
651
+ }
652
+
653
+ function mergeSection(
654
+ result: InternalConfig,
655
+ layer: InternalConfig,
656
+ section: MergeSection,
657
+ ): void {
658
+ const incoming = layer[section];
659
+ if (!incoming) return;
660
+ const previousHook = result.safety?.hook;
661
+ const previousFiles = result.files;
662
+ const previousMcp = result.mcp;
663
+ result[section] = {
664
+ ...(result[section] as object | undefined),
665
+ ...definedProperties(incoming),
666
+ } as never;
667
+ if (section === "safety")
668
+ mergeSafetyHook(result, incoming as InternalConfig["safety"], previousHook);
669
+ if (section === "files")
670
+ mergeFileMethods(
671
+ result,
672
+ incoming as InternalConfig["files"],
673
+ previousFiles,
674
+ );
675
+ if (section === "mcp")
676
+ mergeMcpConfiguration(
677
+ result,
678
+ incoming as InternalConfig["mcp"],
679
+ previousMcp,
680
+ );
681
+ }
682
+
547
683
  function merge(...layers: InternalConfig[]): InternalConfig {
548
684
  const result: InternalConfig = {};
549
685
  for (const layer of layers) {
550
686
  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
- }
687
+ for (const section of mergeSections) mergeSection(result, layer, section);
584
688
  }
585
689
  return result;
586
690
  }
@@ -588,27 +692,44 @@ function merge(...layers: InternalConfig[]): InternalConfig {
588
692
  async function projectRoots(options: ResolveConfigOptions) {
589
693
  const env = options.env ?? process.env;
590
694
  const cwd = path.resolve(options.cwd ?? process.cwd());
695
+ const withCanonical = async (roots: string[]) => [
696
+ ...new Set([
697
+ ...roots,
698
+ ...(await Promise.all(roots.map(canonicalConfigurationPath))),
699
+ ]),
700
+ ];
591
701
  const clientRoots = await Promise.all(
592
702
  (options.clientRoots ?? []).map((item) =>
593
703
  existingDirectory(resolveFileUri(item)),
594
704
  ),
595
705
  );
596
706
  if (clientRoots.length)
597
- return { candidates: clientRoots, trustedRoots: clientRoots };
707
+ return {
708
+ candidates: clientRoots,
709
+ trustedRoots: await withCanonical(clientRoots),
710
+ };
598
711
 
599
712
  if (env.AST_MCP_PROJECT_ROOT) {
600
713
  const selected = path.resolve(cwd, env.AST_MCP_PROJECT_ROOT);
601
- return { candidates: [selected], trustedRoots: [selected] };
714
+ return {
715
+ candidates: [selected],
716
+ trustedRoots: await withCanonical([selected]),
717
+ };
602
718
  }
603
719
 
604
720
  const legacy = env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean);
605
- if (legacy?.length)
721
+ if (legacy?.length) {
722
+ const candidates = legacy.map((item) => path.resolve(cwd, item));
606
723
  return {
607
- candidates: legacy.map((item) => path.resolve(cwd, item)),
608
- trustedRoots: [cwd],
724
+ candidates,
725
+ trustedRoots: await withCanonical([cwd]),
609
726
  };
727
+ }
610
728
 
611
- return { candidates: [cwd], trustedRoots: [cwd] };
729
+ return {
730
+ candidates: [cwd],
731
+ trustedRoots: await withCanonical([cwd]),
732
+ };
612
733
  }
613
734
 
614
735
  function matchedProjectRoots(
@@ -638,16 +759,15 @@ function defaultInternalConfig(candidates: string[]): InternalConfig {
638
759
  session_sweep_interval_ms: 60 * 1000,
639
760
  session_timeout_ms: 30 * 60 * 1000,
640
761
  },
762
+ mcp: {
763
+ configuration: { enabled: true, require_approval: true },
764
+ },
641
765
  safety: {
642
- allow_any_path: false,
643
- allow_external_roots: false,
644
- allow_temp_directory: true,
645
- follow_symlinks: false,
646
766
  hook: { allow_tools: [], block_tools: [], enabled: true },
647
767
  require_hash: true,
648
768
  },
649
769
  version: 1,
650
- workspace: { roots: candidates },
770
+ workspace: { roots: candidates, worktrees: "include" },
651
771
  };
652
772
  }
653
773
 
@@ -669,16 +789,39 @@ function resolvedFormatting(
669
789
  value: InternalConfig,
670
790
  dprintConfig: string,
671
791
  ): ResolvedConfig["formatting"] {
792
+ const version = value.version ?? 1;
672
793
  return {
673
794
  dprintConfig,
674
795
  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
- })),
796
+ fallback:
797
+ value.formatting?.fallback ?? (version === 2 ? "preserve" : "dprint"),
798
+ formatters: (value.formatting?.formatters ?? []).map(
799
+ (formatter, index) => ({
800
+ args: formatter.args ?? [],
801
+ command: formatter.command,
802
+ enabled: formatter.enabled,
803
+ extensions: formatter.extensions ?? [],
804
+ globs: formatter.globs ?? [],
805
+ id: formatter.id ?? `legacy-${index + 1}`,
806
+ mode: formatter.mode ?? "stdout",
807
+ timeoutMs: formatter.timeout_ms ?? 30_000,
808
+ }),
809
+ ),
810
+ };
811
+ }
812
+
813
+ function resolvedFiles(value: InternalConfig): ResolvedConfig["files"] {
814
+ return {
815
+ patch: {
816
+ aiderMatchers: value.files?.patch?.aider_matchers ?? [
817
+ "exact",
818
+ "whitespace",
819
+ "relative-indentation",
820
+ "diff-match-patch",
821
+ ],
822
+ strategies: value.files?.patch?.strategies ?? ["ast", "aider_block"],
823
+ },
824
+ read: { modes: value.files?.read?.modes ?? ["ast", "text"] },
682
825
  };
683
826
  }
684
827
 
@@ -703,17 +846,81 @@ function resolvedHook(value: InternalConfig["safety"]) {
703
846
  };
704
847
  }
705
848
 
849
+ type ConfiguredPathRule = PathRuleV2;
850
+
706
851
  function resolvedSafety(value: InternalConfig): ResolvedConfig["safety"] {
852
+ const version = value.version ?? 1;
707
853
  return {
708
854
  allowAnyPath: withDefault(value.safety?.allow_any_path, false),
709
855
  allowExternalRoots: withDefault(value.safety?.allow_external_roots, false),
710
- allowTempDirectory: withDefault(value.safety?.allow_temp_directory, true),
856
+ allowTempDirectory: withDefault(
857
+ value.safety?.allow_temp_directory,
858
+ version === 1,
859
+ ),
711
860
  followSymlinks: withDefault(value.safety?.follow_symlinks, false),
712
861
  hook: resolvedHook(value.safety),
713
862
  requireHash: withDefault(value.safety?.require_hash, true),
714
863
  };
715
864
  }
716
865
 
866
+ function layerPathRules(
867
+ layer: LoadedLayer,
868
+ source: "global" | "project",
869
+ ): Array<{ rule: ConfiguredPathRule; source: "global" | "project" }> {
870
+ if (layer.value?.version !== 2) return [];
871
+ return (layer.value.paths ?? []).map((rule) => ({ rule, source }));
872
+ }
873
+
874
+ function resolvedMcp(value: InternalConfig): ResolvedConfig["mcp"] {
875
+ return {
876
+ configuration: {
877
+ enabled: value.mcp?.configuration?.enabled ?? true,
878
+ requireApproval: value.mcp?.configuration?.require_approval ?? true,
879
+ },
880
+ };
881
+ }
882
+
883
+ function resolvedPathEntries(
884
+ pathRules: ReturnType<typeof layerPathRules>,
885
+ ): ResolvedConfig["paths"] {
886
+ return pathRules.map(({ rule, source }) => ({
887
+ excludes: rule.excludes ?? [],
888
+ followSymlinks: rule.follow_symlinks ?? false,
889
+ id: rule.id,
890
+ includes: rule.includes ?? ["**/*"],
891
+ path: rule.path,
892
+ policies: {
893
+ delete: rule.policies.delete ?? rule.policies.write,
894
+ read: rule.policies.read,
895
+ write: rule.policies.write,
896
+ },
897
+ source,
898
+ }));
899
+ }
900
+
901
+ function resolvedSources(
902
+ environment: ReturnType<typeof environmentLayer>,
903
+ global: LoadedLayer,
904
+ project: LoadedLayer,
905
+ ): ResolvedConfig["sources"] {
906
+ return {
907
+ environment: environment.names,
908
+ global: global.value ? global.path : undefined,
909
+ project: project.value ? project.path : undefined,
910
+ };
911
+ }
912
+
913
+ function resolvedWorkspace(
914
+ value: InternalConfig,
915
+ candidates: string[],
916
+ ): ResolvedConfig["workspace"] {
917
+ return {
918
+ linkedWorktrees: [],
919
+ roots: value.workspace?.roots ?? candidates,
920
+ worktrees: value.workspace?.worktrees ?? "include",
921
+ };
922
+ }
923
+
717
924
  function resolvedConfiguration(args: {
718
925
  candidates: string[];
719
926
  dprintConfig: string;
@@ -741,19 +948,22 @@ function resolvedConfiguration(args: {
741
948
  astBroBinary: value.dependencies?.ast_bro_binary,
742
949
  dprintBinary: value.dependencies?.dprint_binary,
743
950
  },
951
+ files: resolvedFiles(value),
744
952
  formatting: resolvedFormatting(value, dprintConfig),
953
+ generation: 0,
745
954
  http: resolvedHttp(value),
955
+ mcp: resolvedMcp(value),
956
+ paths: resolvedPathEntries([
957
+ ...layerPathRules(global, "global"),
958
+ ...layerPathRules(project, "project"),
959
+ ]),
746
960
  projectRoot,
747
961
  provenance,
748
962
  safety: resolvedSafety(value),
749
- sources: {
750
- environment: environment.names,
751
- global: global.value ? global.path : undefined,
752
- project: project.value ? project.path : undefined,
753
- },
963
+ sources: resolvedSources(environment, global, project),
754
964
  trustedRoots,
755
- version: 1,
756
- workspace: { roots: value.workspace?.roots ?? candidates },
965
+ version: value.version ?? 1,
966
+ workspace: resolvedWorkspace(value, candidates),
757
967
  };
758
968
  }
759
969
 
@@ -812,6 +1022,71 @@ function resolutionCacheKey(args: {
812
1022
  });
813
1023
  }
814
1024
 
1025
+ async function sameResolvedPath(left: string, right: string): Promise<boolean> {
1026
+ if (path.resolve(left) === path.resolve(right)) return true;
1027
+ try {
1028
+ return (await realpath(left)) === (await realpath(right));
1029
+ } catch {
1030
+ return false;
1031
+ }
1032
+ }
1033
+
1034
+ async function appendUniqueRoots(
1035
+ existing: string[],
1036
+ candidates: string[],
1037
+ ): Promise<string[]> {
1038
+ const result = [...existing];
1039
+ for (const candidate of candidates) {
1040
+ let found = false;
1041
+ for (const item of result) {
1042
+ if (await sameResolvedPath(item, candidate)) {
1043
+ found = true;
1044
+ break;
1045
+ }
1046
+ }
1047
+ if (!found) result.push(candidate);
1048
+ }
1049
+ return result;
1050
+ }
1051
+
1052
+ async function discoveredLinkedWorktrees(
1053
+ projectRoot: string,
1054
+ candidates: string[],
1055
+ trustedRoots: string[],
1056
+ ): Promise<string[]> {
1057
+ const sources = [...new Set([projectRoot, ...candidates, ...trustedRoots])];
1058
+ return [
1059
+ ...new Set(
1060
+ (await Promise.all(sources.map((root) => linkedWorktrees(root)))).flat(),
1061
+ ),
1062
+ ];
1063
+ }
1064
+
1065
+ async function applyLinkedWorktrees(
1066
+ config: ResolvedConfig,
1067
+ linked: string[],
1068
+ ): Promise<ResolvedConfig> {
1069
+ const workspace = { ...config.workspace, linkedWorktrees: linked };
1070
+ if (config.workspace.worktrees === "ignore") return { ...config, workspace };
1071
+ const workspaceLinked = [
1072
+ ...new Set(
1073
+ (
1074
+ await Promise.all(
1075
+ config.workspace.roots.map((root) => linkedWorktrees(root)),
1076
+ )
1077
+ ).flat(),
1078
+ ),
1079
+ ];
1080
+ return {
1081
+ ...config,
1082
+ trustedRoots: await appendUniqueRoots(config.trustedRoots, linked),
1083
+ workspace: {
1084
+ ...workspace,
1085
+ roots: await appendUniqueRoots(config.workspace.roots, workspaceLinked),
1086
+ },
1087
+ };
1088
+ }
1089
+
815
1090
  async function resolveForProject(
816
1091
  projectRoot: string,
817
1092
  candidates: string[],
@@ -834,6 +1109,10 @@ async function resolveForProject(
834
1109
  { name: "environment", value: environment.value },
835
1110
  ];
836
1111
  const value = merge(...layers.map((item) => item.value));
1112
+ const sourceVersions = [global.value?.version, project.value?.version].filter(
1113
+ (version): version is 1 | 2 => version !== undefined,
1114
+ );
1115
+ if (sourceVersions.includes(1)) value.version = 1;
837
1116
  const dprint = await resolvedDprint(value);
838
1117
  const key = resolutionCacheKey({
839
1118
  candidates,
@@ -845,32 +1124,98 @@ async function resolveForProject(
845
1124
  projectRoot,
846
1125
  trustedRoots,
847
1126
  });
848
- const fingerprint = `${global.fingerprint}|${project.fingerprint}|${dprint.fingerprint}`;
849
- const cached = resolvedCache.get(key);
850
- if (cached?.fingerprint === fingerprint) return cached.value;
851
- const resolved = resolvedConfiguration({
852
- candidates,
853
- dprintConfig: dprint.config,
854
- environment,
855
- global,
856
- project,
1127
+ const linked = await discoveredLinkedWorktrees(
857
1128
  projectRoot,
858
- provenance: configProvenance(layers),
1129
+ candidates,
859
1130
  trustedRoots,
860
- value,
861
- });
1131
+ );
1132
+ const fingerprint = `${global.fingerprint}|${project.fingerprint}|${dprint.fingerprint}|${linked.join("\0")}`;
1133
+ const cached = resolvedCache.get(key);
1134
+ if (cached?.fingerprint === fingerprint) return cached.value;
1135
+ const resolved = await applyLinkedWorktrees(
1136
+ resolvedConfiguration({
1137
+ candidates,
1138
+ dprintConfig: dprint.config,
1139
+ environment,
1140
+ global,
1141
+ project,
1142
+ projectRoot,
1143
+ provenance: configProvenance(layers),
1144
+ trustedRoots,
1145
+ value,
1146
+ }),
1147
+ linked,
1148
+ );
862
1149
  resolvedCache.set(key, { fingerprint, value: resolved });
863
1150
  return resolved;
864
1151
  }
865
1152
 
1153
+ function projectRelativePolicyPath(
1154
+ config: ResolvedConfig,
1155
+ rule: ResolvedConfig["paths"][number],
1156
+ ): string | undefined {
1157
+ if (rule.source !== "project" || !config.sources.project) return undefined;
1158
+ const relative = path.relative(
1159
+ path.dirname(config.sources.project),
1160
+ rule.path,
1161
+ );
1162
+ const outside =
1163
+ relative === ".." ||
1164
+ relative.startsWith(`..${path.sep}`) ||
1165
+ path.isAbsolute(relative);
1166
+ return outside ? undefined : relative || ".";
1167
+ }
1168
+
866
1169
  function policy(config: ResolvedConfig) {
867
1170
  return JSON.stringify({
868
1171
  dependencies: config.dependencies,
1172
+ files: config.files,
869
1173
  formatting: config.formatting,
1174
+ mcp: config.mcp.configuration,
870
1175
  safety: config.safety,
1176
+ worktrees: config.workspace.worktrees,
871
1177
  });
872
1178
  }
873
1179
 
1180
+ function pathRulePolicy(rule: ResolvedConfig["paths"][number]) {
1181
+ const { path: _path, ...policy } = rule;
1182
+ return JSON.stringify({
1183
+ ...policy,
1184
+ excludes: [...policy.excludes].sort(),
1185
+ includes: [...policy.includes].sort(),
1186
+ });
1187
+ }
1188
+
1189
+ function pathRuleEquivalent(
1190
+ leftConfig: ResolvedConfig,
1191
+ rightConfig: ResolvedConfig,
1192
+ left: ResolvedConfig["paths"][number],
1193
+ right: ResolvedConfig["paths"][number],
1194
+ ) {
1195
+ if (pathRulePolicy(left) !== pathRulePolicy(right)) return false;
1196
+ if (left.path === right.path) return true;
1197
+ const leftRelative = projectRelativePolicyPath(leftConfig, left);
1198
+ const rightRelative = projectRelativePolicyPath(rightConfig, right);
1199
+ return leftRelative !== undefined && leftRelative === rightRelative;
1200
+ }
1201
+
1202
+ function pathPoliciesEquivalent(left: ResolvedConfig, right: ResolvedConfig) {
1203
+ if (left.paths.length !== right.paths.length) return false;
1204
+ const unmatched = [...right.paths];
1205
+ for (const rule of left.paths) {
1206
+ const index = unmatched.findIndex((candidate) =>
1207
+ pathRuleEquivalent(left, right, rule, candidate),
1208
+ );
1209
+ if (index < 0) return false;
1210
+ unmatched.splice(index, 1);
1211
+ }
1212
+ return true;
1213
+ }
1214
+
1215
+ function policiesEquivalent(left: ResolvedConfig, right: ResolvedConfig) {
1216
+ return policy(left) === policy(right) && pathPoliciesEquivalent(left, right);
1217
+ }
1218
+
874
1219
  export async function resolveConfig(
875
1220
  options: ResolveConfigOptions = {},
876
1221
  ): Promise<ResolvedConfig> {
@@ -882,7 +1227,7 @@ export async function resolveConfig(
882
1227
  ),
883
1228
  );
884
1229
  const first = configs[0] as ResolvedConfig;
885
- if (configs.some((config) => policy(config) !== policy(first)))
1230
+ if (configs.some((config) => !policiesEquivalent(config, first)))
886
1231
  throw new ConfigurationError(
887
1232
  `Request spans workspace roots with conflicting ast-mcp policies: ${matched.join(", ")}`,
888
1233
  );
@@ -907,7 +1252,15 @@ export async function withConfig<T>(
907
1252
  return activeConfig.run(config, operation);
908
1253
  }
909
1254
 
1255
+ export async function withResolvedConfig<T>(
1256
+ config: ResolvedConfig,
1257
+ operation: () => Promise<T>,
1258
+ ): Promise<T> {
1259
+ return activeConfig.run(config, operation);
1260
+ }
1261
+
910
1262
  export function clearConfigCache() {
1263
+ clearGitWorktreeCache();
911
1264
  dprintConfigCache.clear();
912
1265
  layerCache.clear();
913
1266
  resolvedCache.clear();