@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/package.json CHANGED
@@ -7,21 +7,21 @@
7
7
  "url": "https://github.com/mwillbanks/ast-mcp/issues"
8
8
  },
9
9
  "dependencies": {
10
- "@ast-bro/cli": "3.0.0",
11
- "@modelcontextprotocol/client": "2.0.0-beta.5",
12
- "@modelcontextprotocol/server": "^2.0.0-beta.5",
10
+ "@ast-bro/cli": "4.0.0",
11
+ "@modelcontextprotocol/client": "2.0.0",
12
+ "@modelcontextprotocol/server": "2.0.0",
13
13
  "diff-match-patch-ts": "^2.0.0",
14
14
  "dprint": "0.55.2",
15
- "unbash": "^4.0.3",
15
+ "unbash": "^4.0.4",
16
16
  "zod": "^4.4.3"
17
17
  },
18
18
  "description": "Zero-trust MCP file writes, AST edits, ast-bro intelligence, hooks, and agent skills",
19
19
  "devDependencies": {
20
- "@biomejs/biome": "^2.5.5",
21
- "@modelcontextprotocol/inspector": "^1.0.0",
20
+ "@biomejs/biome": "^2.5.6",
21
+ "@modelcontextprotocol/inspector": "^2.0.0",
22
22
  "@types/bun": "^1.3.14",
23
- "@types/node": "^26.1.1",
24
- "fallow": "^3.7.1",
23
+ "@types/node": "^26.1.2",
24
+ "fallow": "^3.10.0",
25
25
  "typescript": "^7.0.2"
26
26
  },
27
27
  "engines": {
@@ -58,8 +58,10 @@
58
58
  "url": "git+https://github.com/mwillbanks/ast-mcp.git"
59
59
  },
60
60
  "scripts": {
61
+ "ast-bro:schemas": "bun run scripts/sync-ast-bro-tools.ts --write",
62
+ "ast-bro:schemas:check": "bun run scripts/sync-ast-bro-tools.ts",
61
63
  "build": "bun run scripts/build.ts",
62
- "check": "bun run tools:check && bun run format:check && bun run typecheck && bun run test",
64
+ "check": "bun run tools:check && bun run templates:check && bun run prose:check && bun run format:check && bun run typecheck && bun run test",
63
65
  "dev": "bun run --watch src/index.ts",
64
66
  "dev:http": "bun run --watch src/http-entry.ts",
65
67
  "evals:check": "bun run templates/skills/ast-mcp/evals/validate.ts",
@@ -73,11 +75,15 @@
73
75
  "inspect:http": "bunx @modelcontextprotocol/inspector",
74
76
  "lint": "biome check . --reporter concise --error-on-warnings",
75
77
  "prepack": "bun run build",
78
+ "prose:check": "bun run scripts/check-prose-cli.ts",
76
79
  "skill:check": "bunx skills-ref validate templates/skills/ast-mcp",
80
+ "smoke:hosts": "bun run scripts/host-smoke.ts",
77
81
  "start": "bun run src/index.ts",
78
82
  "start:http": "bun run src/http-entry.ts",
83
+ "templates:check": "bun run scripts/check-template-drift.ts",
84
+ "templates:sync": "bun run scripts/check-template-drift.ts --write",
79
85
  "test": "bun test --bail --max-concurrency=1 --timeout=30000",
80
- "tools:check": "bun run scripts/verify-tools.ts",
86
+ "tools:check": "bun run scripts/verify-tools.ts && bun run ast-bro:schemas:check",
81
87
  "typecheck": "bunx tsc --noEmit"
82
88
  },
83
89
  "sideEffects": false,
@@ -86,5 +92,5 @@
86
92
  "dprint"
87
93
  ],
88
94
  "type": "module",
89
- "version": "0.2.2"
95
+ "version": "0.3.0"
90
96
  }
@@ -6,21 +6,31 @@ type AstBroMapPayload = {
6
6
  files?: Array<{ error_count?: number; path?: unknown }>;
7
7
  };
8
8
 
9
- export async function astCapable(
9
+ export async function astErrorCount(
10
10
  filePath: string,
11
11
  language?: string,
12
- ): Promise<boolean> {
13
- if (!language) return false;
14
- const processHandle = Bun.spawn([AST_BRO_BINARY, "map", "--json", filePath], {
12
+ ): Promise<number | undefined> {
13
+ const command = [AST_BRO_BINARY, "map", "--json", filePath];
14
+ void language;
15
+ const process = Bun.spawn(command, {
15
16
  cwd: path.dirname(filePath),
17
+ env: { ...Bun.env, NO_COLOR: "1" },
16
18
  stderr: "pipe",
17
19
  stdout: "pipe",
18
20
  });
19
- const result = await captureProcess(processHandle);
20
- const stdout = successfulProcessOutput("ast-bro map", result);
21
- const payload = JSON.parse(stdout) as AstBroMapPayload;
22
- const file = (payload.files ?? []).find(
23
- (candidate) => candidate.path === filePath,
21
+ const output = successfulProcessOutput(
22
+ "ast-bro map",
23
+ await captureProcess(process),
24
24
  );
25
- return file?.error_count === 0;
25
+ if (!output.trim()) return undefined;
26
+ const payload = JSON.parse(output) as AstBroMapPayload;
27
+ const file = (payload.files ?? []).find((entry) => entry.path === filePath);
28
+ return file ? (file.error_count ?? 0) : undefined;
29
+ }
30
+
31
+ export async function astCapable(
32
+ filePath: string,
33
+ language?: string,
34
+ ): Promise<boolean> {
35
+ return (await astErrorCount(filePath, language)) === 0;
26
36
  }
@@ -15,6 +15,11 @@
15
15
  "json": {
16
16
  "type": "boolean"
17
17
  },
18
+ "limit": {
19
+ "description": "Cap result count (default 200). The reported total stays exact.",
20
+ "minimum": 1,
21
+ "type": "integer"
22
+ },
18
23
  "path": {
19
24
  "description": "Repo root (default \".\").",
20
25
  "type": "string"
@@ -146,9 +151,13 @@
146
151
  }
147
152
  },
148
153
  "digest": {
149
- "description": "One-page module map for an unfamiliar directory: every file's types and public methods. Returns text by default; set `json: true` for `ast-bro.map.v1`.",
154
+ "description": "One-page module map for an unfamiliar directory: every file's types and public methods. Alias for `map` with detail=names, public-only, max_members=50. Returns text by default; set `json: true` for `ast-bro.map.v1`.",
150
155
  "inputSchema": {
151
156
  "properties": {
157
+ "glob": {
158
+ "description": "Glob filter applied during directory walk.",
159
+ "type": "string"
160
+ },
152
161
  "include_fields": {
153
162
  "type": "boolean"
154
163
  },
@@ -159,7 +168,8 @@
159
168
  "type": "boolean"
160
169
  },
161
170
  "max_members": {
162
- "description": "Cap members per type (default 50).",
171
+ "description": "Cap members per type (default 50); the output reports what was cut.",
172
+ "minimum": 0,
163
173
  "type": "integer"
164
174
  },
165
175
  "paths": {
@@ -330,6 +340,11 @@
330
340
  "description": "AST-based structural map of source files — signatures with line ranges, no method bodies. Returns text by default (5–10× smaller than reading the file). Set `json: true` for the machine-readable schema `ast-bro.map.v1`.",
331
341
  "inputSchema": {
332
342
  "properties": {
343
+ "detail": {
344
+ "description": "Detail level: `full` (signatures + docs, default), `signatures` (no docs), `names` (bare member names — the digest renderer).",
345
+ "enum": ["names", "signatures", "full"],
346
+ "type": "string"
347
+ },
333
348
  "glob": {
334
349
  "description": "Glob filter applied during directory walk.",
335
350
  "type": "string"
@@ -338,6 +353,11 @@
338
353
  "description": "Return JSON (schema `ast-bro.map.v1`) instead of text.",
339
354
  "type": "boolean"
340
355
  },
356
+ "max_members": {
357
+ "description": "Cap members shown per type; the output reports what was cut.",
358
+ "minimum": 0,
359
+ "type": "integer"
360
+ },
341
361
  "no_attrs": {
342
362
  "description": "Hide attributes / decorators.",
343
363
  "type": "boolean"
package/src/cli.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export interface CliHandlers {
2
- config(args: string[]): Promise<void>;
2
+ config(args: string[]): Promise<number | undefined> | Promise<void>;
3
3
  hook(): Promise<number>;
4
4
  installer(args: string[]): Promise<void>;
5
5
  mcp(args: string[]): Promise<void>;
@@ -7,12 +7,12 @@ export interface CliHandlers {
7
7
  stdout?(text: string): void;
8
8
  }
9
9
 
10
- const rootHelp = `ast-mcp - AST-aware Model Context Protocol server\n\nUsage:\n ast-mcp <command> [options]\n\nCommands:\n config Validate or display layered ast-mcp.toml configuration\n install Configure ast-mcp for one or more supported hosts\n update Refresh an existing ast-mcp configuration\n uninstall Remove ast-mcp-managed configuration\n mcp Start the stdio or Streamable HTTP MCP server\n hook Run the pre-tool-use filesystem guard\n help Display help for a command\n\nOptions:\n -h, --help Display help\n\nRun "ast-mcp help <command>" for command-specific help.\n`;
10
+ const rootHelp = `ast-mcp - AST-aware Model Context Protocol server\n\nUsage:\n ast-mcp <command> [options]\n\nCommands:\n config Validate, display, or migrate ast-mcp.toml configuration\n install Configure ast-mcp for one or more supported hosts\n update Refresh an existing ast-mcp configuration\n uninstall Remove ast-mcp-managed configuration\n mcp Start the stdio or Streamable HTTP MCP server\n hook Run the pre-tool-use filesystem guard\n help Display help for a command\n\nOptions:\n -h, --help Display help\n\nRun "ast-mcp help <command>" for command-specific help.\n`;
11
11
 
12
- const installerOptions = `Options:\n -s, --scope <scope> Installation scope: local or global (default: local)\n -t, --target <target> Host: codex, claude, copilot, or all (default: all)\n -r, --root <path> Project root for local scope (default: current directory)\n --transport <mode> MCP transport: stdio or http (default: stdio)\n --host <address> HTTP bind host (default: layered configuration)\n --port <number> HTTP bind port (default: layered configuration)\n --service Install and start a managed user HTTP service\n --no-service Stop and remove a managed user HTTP service\n -h, --help Display help\n`;
12
+ const installerOptions = `Options:\n -s, --scope <scope> Installation scope: local or global (default: local)\n -t, --target <target> Host: codex, claude, copilot, or all (default: all)\n -r, --root <path> Deprecated root override (default: current directory)\n --transport <mode> MCP transport: stdio or http (default: stdio)\n --host <address> HTTP bind host (default: layered configuration)\n --port <number> HTTP bind port (default: layered configuration)\n --service Install and start a managed user HTTP service\n --no-service Stop and remove a managed user HTTP service\n -h, --help Display help\n`;
13
13
 
14
14
  const commandHelp: Record<string, string> = {
15
- config: `Usage:\n ast-mcp config <validate|show> [options]\n\nValidate configuration or display the resolved values, sources, and provenance.\n\nOptions:\n -r, --root <path> Project root to resolve (default: current directory)\n -h, --help Display help\n`,
15
+ config: `Usage:\n ast-mcp config <validate|show|migrate> [options]\n\nValidate, display, or migrate layered ast-mcp.toml configuration. Migration previews by default and never rewrites automatically.\n\nOptions:\n -r, --root <path> Deprecated root or migration target directory\n --file <path> Migrate an explicit configuration file\n --global Migrate the user-global configuration\n --to <version> Migration target version (currently 2)\n --check Exit 2 when migration is required\n --write Atomically write the migration\n --no-backup Do not create the default v1 backup\n -h, --help Display help\n`,
16
16
  hook: `Usage:\n ast-mcp hook\n\nRun the pre-tool-use filesystem guard. Hook input is read from stdin.\n\nOptions:\n -h, --help Display help\n`,
17
17
  install: `Usage:\n ast-mcp install [options]\n\nConfigure ast-mcp for supported hosts.\n\n${installerOptions}`,
18
18
  mcp: `Usage:\n ast-mcp mcp [options]\n\nStart the MCP server. Stdio is the default; HTTP listens on the layered configuration unless flags override it.\n\nOptions:\n --transport <mode> MCP transport: stdio or http (default: stdio)\n --host <address> HTTP bind host\n --port <number> HTTP bind port\n -h, --help Display help\n`,
@@ -91,10 +91,13 @@ async function runConfiguredCommand(
91
91
  command: string,
92
92
  rest: string[],
93
93
  handlers: CliHandlers,
94
- ) {
94
+ ): Promise<number | undefined> {
95
95
  try {
96
- if (command === "config") await handlers.config(rest);
97
- else await handlers.installer([command, ...rest]);
96
+ if (command === "config") {
97
+ const result = await handlers.config(rest);
98
+ return typeof result === "number" ? result : undefined;
99
+ }
100
+ await handlers.installer([command, ...rest]);
98
101
  return undefined;
99
102
  } catch (error) {
100
103
  if (isCliUsageError(error))
package/src/config-cli.ts CHANGED
@@ -1,5 +1,7 @@
1
+ import { readFile } from "node:fs/promises";
1
2
  import path from "node:path";
2
- import { resolveConfig } from "./config";
3
+ import { globalConfigPath, resolveConfig } from "./config";
4
+ import { migrateConfigSource, writeMigratedConfig } from "./config-migrate";
3
5
 
4
6
  class ConfigurationUsageError extends Error {
5
7
  constructor(message: string) {
@@ -19,29 +21,99 @@ function valueAfter(tokens: string[], index: number) {
19
21
  return value;
20
22
  }
21
23
 
22
- export async function runConfigCli(
23
- args: string[],
24
- write: (text: string) => void = stdout.write.bind(stdout),
25
- ) {
26
- const tokens = args.flatMap((token) => {
27
- const match = /^--root=(.*)$/.exec(token);
28
- return match ? ["--root", match[1] as string] : [token];
24
+ type ConfigOperation = "validate" | "show" | "migrate";
25
+
26
+ type ConfigOptions = {
27
+ backup: boolean;
28
+ check: boolean;
29
+ file?: string;
30
+ global: boolean;
31
+ root: string;
32
+ write: boolean;
33
+ };
34
+
35
+ function normalizeTokens(args: string[]): string[] {
36
+ return args.flatMap((token) => {
37
+ for (const option of ["root", "file", "to"])
38
+ if (token.startsWith(`--${option}=`))
39
+ return [`--${option}`, token.slice(option.length + 3)];
40
+ return [token];
29
41
  });
30
- const operation = tokens.shift();
31
- if (operation !== "validate" && operation !== "show")
32
- throw new ConfigurationUsageError(
33
- `Expected config validate or config show; received "${operation ?? ""}"`,
34
- );
42
+ }
35
43
 
36
- let root = process.cwd();
44
+ function configOperation(token: string | undefined): ConfigOperation {
45
+ if (token === "validate" || token === "show" || token === "migrate")
46
+ return token;
47
+ throw new ConfigurationUsageError(
48
+ `Expected config validate, config show, or config migrate; received "${token ?? ""}"`,
49
+ );
50
+ }
51
+
52
+ function valueOption(
53
+ token: string | undefined,
54
+ tokens: string[],
55
+ index: number,
56
+ options: ConfigOptions,
57
+ ): boolean {
58
+ if (token === "--root" || token === "-r")
59
+ options.root = valueAfter(tokens, index);
60
+ else if (token === "--file") options.file = valueAfter(tokens, index);
61
+ else if (token === "--to") {
62
+ if (valueAfter(tokens, index) !== "2")
63
+ throw new ConfigurationUsageError("Only --to 2 is supported");
64
+ } else return false;
65
+ return true;
66
+ }
67
+
68
+ function flagOption(
69
+ token: string | undefined,
70
+ options: ConfigOptions,
71
+ ): boolean {
72
+ if (token === "--global") options.global = true;
73
+ else if (token === "--check") options.check = true;
74
+ else if (token === "--write") options.write = true;
75
+ else if (token === "--no-backup") options.backup = false;
76
+ else return false;
77
+ return true;
78
+ }
79
+
80
+ function configOptions(tokens: string[]): ConfigOptions {
81
+ const options: ConfigOptions = {
82
+ backup: true,
83
+ check: false,
84
+ global: false,
85
+ root: process.cwd(),
86
+ write: false,
87
+ };
37
88
  for (let index = 0; index < tokens.length; index += 1) {
38
- if (tokens[index] !== "--root" && tokens[index] !== "-r")
39
- throw new ConfigurationUsageError(`Unknown option: ${tokens[index]}`);
40
- root = valueAfter(tokens, index);
41
- index += 1;
89
+ const token = tokens[index];
90
+ if (valueOption(token, tokens, index, options)) index += 1;
91
+ else if (!flagOption(token, options))
92
+ throw new ConfigurationUsageError(`Unknown option: ${token}`);
42
93
  }
94
+ return options;
95
+ }
96
+
97
+ function assertReadOptions(options: ConfigOptions): void {
98
+ if (
99
+ options.file ||
100
+ options.global ||
101
+ options.check ||
102
+ options.write ||
103
+ !options.backup
104
+ )
105
+ throw new ConfigurationUsageError(
106
+ "Migration options require config migrate",
107
+ );
108
+ }
43
109
 
44
- const config = await resolveConfig({ cwd: path.resolve(root) });
110
+ async function runConfigRead(
111
+ operation: Exclude<ConfigOperation, "migrate">,
112
+ options: ConfigOptions,
113
+ write: (text: string) => void,
114
+ ): Promise<void> {
115
+ assertReadOptions(options);
116
+ const config = await resolveConfig({ cwd: path.resolve(options.root) });
45
117
  const output =
46
118
  operation === "show"
47
119
  ? config
@@ -49,6 +121,81 @@ export async function runConfigCli(
49
121
  projectRoot: config.projectRoot,
50
122
  sources: config.sources,
51
123
  valid: true,
124
+ version: config.version,
52
125
  };
53
126
  write(`${JSON.stringify(output, null, 2)}\n`);
54
127
  }
128
+
129
+ function migrationTarget(options: ConfigOptions): string {
130
+ if (options.file) return path.resolve(options.file);
131
+ if (options.global) return path.resolve(globalConfigPath());
132
+ return path.resolve(options.root, "ast-mcp.toml");
133
+ }
134
+
135
+ async function migrationBackup(
136
+ options: ConfigOptions,
137
+ migration: ReturnType<typeof migrateConfigSource>,
138
+ target: string,
139
+ ) {
140
+ if (!options.write || !migration.changed) return undefined;
141
+ return writeMigratedConfig(target, migration.source, options.backup);
142
+ }
143
+
144
+ function migrationReport(
145
+ options: ConfigOptions,
146
+ migration: ReturnType<typeof migrateConfigSource>,
147
+ target: string,
148
+ backupPath: string | undefined,
149
+ ) {
150
+ return {
151
+ backupPath,
152
+ changed: migration.changed,
153
+ file: target,
154
+ fromVersion: migration.fromVersion,
155
+ preview: options.write ? undefined : migration.source,
156
+ toVersion: migration.toVersion,
157
+ warnings: migration.warnings,
158
+ written: options.write && migration.changed,
159
+ };
160
+ }
161
+
162
+ async function runMigration(
163
+ options: ConfigOptions,
164
+ write: (text: string) => void,
165
+ ): Promise<number> {
166
+ if (options.file && options.global)
167
+ throw new ConfigurationUsageError("Choose only one of --file or --global");
168
+ if (options.check && options.write)
169
+ throw new ConfigurationUsageError("--check and --write cannot be combined");
170
+ const target = migrationTarget(options);
171
+ const migration = migrateConfigSource(await readFile(target, "utf8"), target);
172
+ const backupPath = await migrationBackup(options, migration, target);
173
+ write(
174
+ `${JSON.stringify(
175
+ migrationReport(options, migration, target, backupPath),
176
+ null,
177
+ 2,
178
+ )}\n`,
179
+ );
180
+ return options.check && migration.changed ? 2 : 0;
181
+ }
182
+
183
+ export async function runConfigCli(
184
+ args: string[],
185
+ write: (text: string) => void = stdout.write.bind(stdout),
186
+ ): Promise<number | undefined> {
187
+ if (
188
+ args.some(
189
+ (token) =>
190
+ token === "--root" || token === "-r" || token.startsWith("--root="),
191
+ )
192
+ )
193
+ process.stderr.write(
194
+ "ast-mcp: --root is deprecated; run this command from the project root.\n",
195
+ );
196
+ const tokens = normalizeTokens(args);
197
+ const operation = configOperation(tokens.shift());
198
+ const options = configOptions(tokens);
199
+ if (operation === "migrate") return runMigration(options, write);
200
+ await runConfigRead(operation, options, write);
201
+ }
@@ -0,0 +1,223 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ chmod,
4
+ copyFile,
5
+ lstat,
6
+ rename,
7
+ unlink,
8
+ writeFile,
9
+ } from "node:fs/promises";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { fileV2Schema } from "./config-v2-schema";
13
+
14
+ export interface MigrationPreview {
15
+ changed: boolean;
16
+ fromVersion: number;
17
+ source: string;
18
+ toVersion: 2;
19
+ warnings: string[];
20
+ }
21
+
22
+ function quote(value: string): string {
23
+ return JSON.stringify(value);
24
+ }
25
+
26
+ function insertIntoSection(
27
+ source: string,
28
+ section: string,
29
+ line: string,
30
+ ): string {
31
+ const header = new RegExp(
32
+ `^[\\t ]*\\[${section.replaceAll(".", "\\.")}\\][\\t ]*(?:#.*)?$`,
33
+ "m",
34
+ );
35
+ const match = header.exec(source);
36
+ if (!match) return `${source.trimEnd()}\n\n[${section}]\n${line}\n`;
37
+ const index = match.index + match[0].length;
38
+ return `${source.slice(0, index)}\n${line}${source.slice(index)}`;
39
+ }
40
+
41
+ function formatterDefaults(source: string): string {
42
+ const headers = [
43
+ ...source.matchAll(
44
+ /^[\t ]*\[\[formatting\.formatters\]\][\t ]*(?:#.*)?$/gm,
45
+ ),
46
+ ];
47
+ let migrated = source;
48
+ for (let index = headers.length - 1; index >= 0; index -= 1) {
49
+ const header = headers[index] as RegExpMatchArray;
50
+ const start = (header.index ?? 0) + header[0].length;
51
+ const next = migrated.slice(start).search(/^[\t ]*\[/m);
52
+ const end = next < 0 ? migrated.length : start + next;
53
+ const body = migrated.slice(start, end);
54
+ const additions = [
55
+ /^[\t ]*id\s*=/m.test(body) ? undefined : `id = "legacy-${index + 1}"`,
56
+ /^[\t ]*enabled\s*=/m.test(body) ? undefined : "enabled = true",
57
+ /^[\t ]*mode\s*=/m.test(body) ? undefined : 'mode = "stdout"',
58
+ ].filter((item): item is string => Boolean(item));
59
+ if (additions.length)
60
+ migrated = `${migrated.slice(0, start)}\n${additions.join("\n")}${migrated.slice(start)}`;
61
+ }
62
+ return migrated;
63
+ }
64
+
65
+ function stripLegacySafety(source: string): string {
66
+ return source.replace(
67
+ /^\s*(allow_any_path|allow_external_roots|allow_temp_directory|follow_symlinks)\s*=.*(?:\r?\n|$)/gm,
68
+ "",
69
+ );
70
+ }
71
+
72
+ function rule(id: string, anchor: string, followSymlinks: boolean): string {
73
+ return [
74
+ "[[paths]]",
75
+ `id = ${quote(id)}`,
76
+ `path = ${quote(anchor)}`,
77
+ 'policies = { read = "allow", write = "allow", delete = "allow" }',
78
+ `follow_symlinks = ${followSymlinks}`,
79
+ 'includes = ["**/*"]',
80
+ 'excludes = [".git/**"]',
81
+ ].join("\n");
82
+ }
83
+
84
+ function parsedMigration(source: string) {
85
+ let parsed: Record<string, unknown>;
86
+ try {
87
+ parsed = Bun.TOML.parse(source) as Record<string, unknown>;
88
+ } catch (error) {
89
+ throw new Error(
90
+ `Invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
91
+ );
92
+ }
93
+ const rawVersion = parsed.version;
94
+ const fromVersion = rawVersion === undefined ? 1 : Number(rawVersion);
95
+ if (!Number.isInteger(fromVersion) || fromVersion < 1 || fromVersion > 2)
96
+ throw new Error(`Unsupported ast-mcp.toml version: ${String(rawVersion)}`);
97
+ return { fromVersion, parsed };
98
+ }
99
+
100
+ function currentPreview(
101
+ parsed: Record<string, unknown>,
102
+ source: string,
103
+ ): MigrationPreview {
104
+ const result = fileV2Schema.safeParse(parsed);
105
+ if (!result.success)
106
+ throw new Error(`Invalid version 2 configuration: ${result.error.message}`);
107
+ return {
108
+ changed: false,
109
+ fromVersion: 2,
110
+ source,
111
+ toVersion: 2,
112
+ warnings: [],
113
+ };
114
+ }
115
+
116
+ function legacyRules(parsed: Record<string, unknown>, filePath: string) {
117
+ const safety = (parsed.safety ?? {}) as Record<string, unknown>;
118
+ const workspace = (parsed.workspace ?? {}) as { roots?: unknown };
119
+ const roots = Array.isArray(workspace.roots)
120
+ ? workspace.roots.filter((item): item is string => typeof item === "string")
121
+ : [];
122
+ const followSymlinks = safety.follow_symlinks === true;
123
+ const warnings: string[] = [];
124
+ const rules = roots.map((root, index) =>
125
+ rule(
126
+ `legacy-workspace-${index + 1}`,
127
+ path.resolve(path.dirname(filePath), root),
128
+ followSymlinks,
129
+ ),
130
+ );
131
+ if (safety.allow_temp_directory !== false)
132
+ rules.push(rule("legacy-os-temp", os.tmpdir(), followSymlinks));
133
+ if (safety.allow_any_path === true) {
134
+ rules.push(
135
+ rule(
136
+ "legacy-unrestricted",
137
+ path.parse(path.resolve(filePath)).root,
138
+ followSymlinks,
139
+ ),
140
+ );
141
+ warnings.push(
142
+ "UNRESTRICTED: safety.allow_any_path=true became an explicit catch-all path rule",
143
+ );
144
+ }
145
+ return { rules, warnings };
146
+ }
147
+
148
+ function migrateLegacyText(
149
+ source: string,
150
+ parsed: Record<string, unknown>,
151
+ filePath: string,
152
+ ) {
153
+ const { rules, warnings } = legacyRules(parsed, filePath);
154
+ let migrated = source;
155
+ const versionPattern = /^([\t ]*version[\t ]*=[\t ]*)[^\s#]+(.*)$/m;
156
+ migrated = versionPattern.test(migrated)
157
+ ? migrated.replace(
158
+ versionPattern,
159
+ (_match, prefix: string, suffix: string) => `${prefix}2${suffix}`,
160
+ )
161
+ : `version = 2\n\n${migrated}`;
162
+ const formatting = (parsed.formatting ?? {}) as Record<string, unknown>;
163
+ if (formatting.fallback === undefined)
164
+ migrated = insertIntoSection(migrated, "formatting", 'fallback = "dprint"');
165
+ migrated = formatterDefaults(migrated);
166
+ migrated = insertIntoSection(
167
+ migrated,
168
+ "files.patch",
169
+ 'aider_matchers = ["exact", "whitespace", "relative-indentation", "diff-match-patch"]',
170
+ );
171
+ migrated = stripLegacySafety(migrated);
172
+ migrated = `${migrated.trimEnd()}\n\n${rules.join("\n\n")}\n`;
173
+ const validated = fileV2Schema.safeParse(Bun.TOML.parse(migrated));
174
+ if (!validated.success)
175
+ throw new Error(
176
+ `Generated invalid version 2 configuration: ${validated.error.message}`,
177
+ );
178
+ return { migrated, warnings };
179
+ }
180
+
181
+ export function migrateConfigSource(
182
+ source: string,
183
+ filePath: string,
184
+ ): MigrationPreview {
185
+ const { fromVersion, parsed } = parsedMigration(source);
186
+ if (fromVersion === 2) return currentPreview(parsed, source);
187
+ const newline = source.includes("\r\n") ? "\r\n" : "\n";
188
+ const normalized = source.replaceAll("\r\n", "\n");
189
+ const { migrated, warnings } = migrateLegacyText(
190
+ normalized,
191
+ parsed,
192
+ filePath,
193
+ );
194
+ return {
195
+ changed: migrated !== normalized,
196
+ fromVersion,
197
+ source: newline === "\r\n" ? migrated.replaceAll("\n", "\r\n") : migrated,
198
+ toVersion: 2,
199
+ warnings,
200
+ };
201
+ }
202
+
203
+ export async function writeMigratedConfig(
204
+ filePath: string,
205
+ source: string,
206
+ backup = true,
207
+ ): Promise<string | undefined> {
208
+ const metadata = await lstat(filePath);
209
+ const backupPath = backup ? `${filePath}.v1.bak` : undefined;
210
+ if (backupPath) await copyFile(filePath, backupPath);
211
+ const temporary = path.join(
212
+ path.dirname(filePath),
213
+ `.${path.basename(filePath)}.migrate-${randomUUID()}`,
214
+ );
215
+ try {
216
+ await writeFile(temporary, source, { flag: "wx", mode: metadata.mode });
217
+ await chmod(temporary, metadata.mode);
218
+ await rename(temporary, filePath);
219
+ } finally {
220
+ await unlink(temporary).catch(() => undefined);
221
+ }
222
+ return backupPath;
223
+ }