@mwillbanks/ast-mcp 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -16
  3. package/dist/ast-mcp.js +209 -147
  4. package/dist/ast-mcp.js.map +70 -50
  5. package/package.json +21 -15
  6. package/src/ast-bro/capability.ts +20 -10
  7. package/src/ast-bro/client.ts +12 -6
  8. package/src/ast-bro/result.ts +79 -0
  9. package/src/ast-bro/tools.json +29 -4
  10. package/src/cli.ts +10 -7
  11. package/src/config-cli.ts +166 -19
  12. package/src/config-edit.ts +236 -0
  13. package/src/config-migrate.ts +206 -0
  14. package/src/config-registry.ts +329 -0
  15. package/src/config-schema-common.ts +88 -0
  16. package/src/config-v2-schema.ts +109 -0
  17. package/src/config.ts +523 -170
  18. package/src/helpers/ast-bro.ts +1 -7
  19. package/src/helpers/config.ts +16 -3
  20. package/src/helpers/installer.ts +8 -0
  21. package/src/helpers/mcp-schema.ts +98 -4
  22. package/src/host-smoke.ts +182 -0
  23. package/src/http.ts +8 -3
  24. package/src/installer-transport.ts +6 -4
  25. package/src/installer.ts +242 -54
  26. package/src/patch/engine.ts +575 -280
  27. package/src/patch/languages.ts +9 -0
  28. package/src/patch/strategy/aiderBlock.ts +110 -0
  29. package/src/patch/strategy/ast.ts +170 -0
  30. package/src/patch/strategy.ts +61 -0
  31. package/src/runtime/approval.ts +438 -0
  32. package/src/runtime/config-write.ts +327 -0
  33. package/src/runtime/dependencies.ts +14 -78
  34. package/src/runtime/document-inspection.ts +78 -0
  35. package/src/runtime/file-capabilities.ts +250 -0
  36. package/src/runtime/file-delete.ts +110 -37
  37. package/src/runtime/file-read.ts +134 -15
  38. package/src/runtime/file-rename.ts +5 -2
  39. package/src/runtime/format.ts +90 -30
  40. package/src/runtime/git-worktrees.ts +179 -0
  41. package/src/runtime/path-policy.ts +643 -0
  42. package/src/runtime/path-utils.ts +80 -0
  43. package/src/runtime/paths.ts +171 -47
  44. package/src/server.ts +2 -1
  45. package/src/tools/ast-bro.ts +294 -75
  46. package/src/tools/configuration.ts +668 -0
  47. package/src/tools/configured.ts +49 -21
  48. package/src/tools/files.ts +169 -62
  49. package/src/tools/index.ts +2 -0
  50. package/src/tools/lifecycle.ts +82 -38
  51. package/templates/AGENTS.md +17 -15
  52. package/templates/skills/ast-mcp/SKILL.md +57 -20
  53. package/templates/skills/ast-mcp/evals/evals.json +319 -9
  54. package/templates/skills/ast-mcp/evals/score.ts +80 -0
  55. package/templates/skills/ast-mcp/evals/semantic.ts +3 -1
  56. package/templates/skills/ast-mcp/references/installation.md +12 -12
  57. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  58. package/templates/skills/ast-mcp/references/tool-catalog.md +18 -8
  59. package/templates/skills/ast-mcp/scripts/binary-resolution.ts +112 -0
  60. package/templates/skills/ast-mcp/scripts/check-install.ts +165 -51
  61. package/templates/skills/ast-mcp/scripts/managed-hook.ts +34 -2
  62. package/src/ast-bro/rewrite-capability.ts +0 -9
@@ -0,0 +1,236 @@
1
+ import { lstat, readFile } from "node:fs/promises";
2
+ import { fileV2Schema } from "./config-v2-schema";
3
+ import { replaceFileAtomically } from "./runtime/atomic";
4
+
5
+ export type TomlValue =
6
+ | boolean
7
+ | number
8
+ | string
9
+ | TomlValue[]
10
+ | { [key: string]: TomlValue };
11
+
12
+ const pathIdPattern =
13
+ /(?:^|\n)[ \t]*id[ \t]*=[ \t]*("(?:[^"\\]|\\.)*"|'[^']*')/;
14
+ const policyPairPattern = () =>
15
+ /([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*("(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z0-9_-]+)/g;
16
+
17
+ function encodeTomlValue(value: TomlValue): string {
18
+ if (typeof value === "boolean" || typeof value === "number")
19
+ return String(value);
20
+ if (typeof value === "string") return JSON.stringify(value);
21
+ if (Array.isArray(value))
22
+ return `[${value.map((item) => encodeTomlValue(item)).join(", ")}]`;
23
+ const entries = Object.entries(value).map(
24
+ ([key, item]) => `${key} = ${encodeTomlValue(item)}`,
25
+ );
26
+ return `{ ${entries.join(", ")} }`;
27
+ }
28
+
29
+ function nextTableHeader(source: string, start: number): number {
30
+ const rest = source.slice(start);
31
+ const match = /\n\[/.exec(rest);
32
+ return match ? start + match.index + 1 : source.length;
33
+ }
34
+
35
+ function sectionRange(
36
+ source: string,
37
+ header: string,
38
+ ): { bodyStart: number; end: number; start: number } | undefined {
39
+ const pattern = new RegExp(
40
+ `^[\\t ]*\\[${header.replaceAll(".", "\\.")}\\][\\t ]*(?:#.*)?$`,
41
+ "m",
42
+ );
43
+ const match = pattern.exec(source);
44
+ if (!match || match.index === undefined) return undefined;
45
+ const start = match.index;
46
+ const bodyStart = start + match[0].length;
47
+ return { bodyStart, end: nextTableHeader(source, bodyStart), start };
48
+ }
49
+
50
+ function ensureSection(source: string, header: string): string {
51
+ if (sectionRange(source, header)) return source;
52
+ return `${source.trimEnd()}\n\n[${header}]\n`;
53
+ }
54
+
55
+ function replaceKeyInRange(
56
+ source: string,
57
+ rangeStart: number,
58
+ rangeEnd: number,
59
+ key: string,
60
+ encoded: string,
61
+ ): string {
62
+ const body = source.slice(rangeStart, rangeEnd);
63
+ const keyPattern = new RegExp(`^[\\t ]*${key}[\\t ]*=.*$`, "m");
64
+ if (keyPattern.test(body)) {
65
+ const updated = body.replace(keyPattern, `${key} = ${encoded}`);
66
+ return `${source.slice(0, rangeStart)}${updated}${source.slice(rangeEnd)}`;
67
+ }
68
+ const insertion = body.endsWith("\n")
69
+ ? `${body}${key} = ${encoded}\n`
70
+ : `${body}\n${key} = ${encoded}\n`;
71
+ return `${source.slice(0, rangeStart)}${insertion}${source.slice(rangeEnd)}`;
72
+ }
73
+
74
+ export function setTomlSectionKey(
75
+ source: string,
76
+ header: string,
77
+ key: string,
78
+ value: TomlValue,
79
+ ): string {
80
+ const withSection = ensureSection(source, header);
81
+ const range = sectionRange(withSection, header);
82
+ if (!range) return withSection;
83
+ return replaceKeyInRange(
84
+ withSection,
85
+ range.bodyStart,
86
+ range.end,
87
+ key,
88
+ encodeTomlValue(value),
89
+ );
90
+ }
91
+
92
+ function pathBlocks(source: string): Array<{
93
+ end: number;
94
+ id?: string;
95
+ start: number;
96
+ }> {
97
+ const matches = [...source.matchAll(/^[ \t]*\[\[paths\]\][ \t]*(?:#.*)?$/gm)];
98
+ return matches.map((match, index) => {
99
+ const start = match.index ?? 0;
100
+ const nextStart = matches[index + 1]?.index;
101
+ const following = nextTableHeader(source, start + match[0].length);
102
+ const end =
103
+ nextStart === undefined ? following : Math.min(nextStart, following);
104
+ const body = source.slice(start, end);
105
+ const idMatch = pathIdPattern.exec(body);
106
+ const raw = idMatch?.[1];
107
+ const id = raw
108
+ ? raw.startsWith("'")
109
+ ? raw.slice(1, -1)
110
+ : (JSON.parse(raw) as string)
111
+ : undefined;
112
+ return { end, id, start };
113
+ });
114
+ }
115
+
116
+ function encodePathRule(rule: Record<string, TomlValue>): string {
117
+ const lines = ["[[paths]]"];
118
+ for (const key of [
119
+ "id",
120
+ "path",
121
+ "policies",
122
+ "follow_symlinks",
123
+ "includes",
124
+ "excludes",
125
+ ]) {
126
+ const value = rule[key];
127
+ if (value !== undefined) lines.push(`${key} = ${encodeTomlValue(value)}`);
128
+ }
129
+ return `${lines.join("\n")}\n`;
130
+ }
131
+
132
+ export function addPathTable(
133
+ source: string,
134
+ rule: Record<string, TomlValue>,
135
+ ): string {
136
+ return `${source.trimEnd()}\n\n${encodePathRule(rule)}`;
137
+ }
138
+
139
+ function requirePathBlock(source: string, id: string) {
140
+ const block = pathBlocks(source).find((item) => item.id === id);
141
+ if (!block)
142
+ throw Object.assign(new Error(`No [[paths]] rule with id ${id}`), {
143
+ code: "configuration_path_missing",
144
+ retryable: true,
145
+ });
146
+ return block;
147
+ }
148
+
149
+ export function removePathTable(source: string, id: string): string {
150
+ const block = requirePathBlock(source, id);
151
+ return `${source.slice(0, block.start)}${source.slice(block.end)}`.replace(
152
+ /\n{3,}/g,
153
+ "\n\n",
154
+ );
155
+ }
156
+
157
+ export function updatePathTable(
158
+ source: string,
159
+ id: string,
160
+ patch: Record<string, TomlValue>,
161
+ ): string {
162
+ const block = requirePathBlock(source, id);
163
+ let body = source.slice(block.start, block.end);
164
+ for (const [key, value] of Object.entries(patch)) {
165
+ const keyPattern = new RegExp(`^[\\t ]*${key}[\\t ]*=.*$`, "m");
166
+ const line = `${key} = ${encodeTomlValue(value)}`;
167
+ body = keyPattern.test(body)
168
+ ? body.replace(keyPattern, line)
169
+ : `${body.trimEnd()}\n${line}\n`;
170
+ }
171
+ return `${source.slice(0, block.start)}${body}${source.slice(block.end)}`;
172
+ }
173
+
174
+ export function pathTableIds(source: string): string[] {
175
+ return pathBlocks(source)
176
+ .map((block) => block.id)
177
+ .filter((id): id is string => Boolean(id));
178
+ }
179
+
180
+ export function existingPathPolicies(
181
+ source: string,
182
+ id: string,
183
+ ): Record<string, string> {
184
+ const block = pathBlocks(source).find((item) => item.id === id);
185
+ if (!block) return {};
186
+ const body = source.slice(block.start, block.end);
187
+ const match = /(?:^|\n)[ \t]*policies[ \t]*=[ \t]*\{([^}]*)\}/.exec(body);
188
+ if (!match?.[1]) return {};
189
+ const policies: Record<string, string> = {};
190
+ for (const item of match[1].matchAll(policyPairPattern()))
191
+ policies[item[1] ?? ""] = item[2]?.startsWith('"')
192
+ ? (JSON.parse(item[2]) as string)
193
+ : item[2]?.startsWith("'")
194
+ ? item[2].slice(1, -1)
195
+ : (item[2] ?? "");
196
+ return policies;
197
+ }
198
+
199
+ export function validateConfigSource(source: string, filePath: string): void {
200
+ let parsed: unknown;
201
+ try {
202
+ parsed = Bun.TOML.parse(source);
203
+ } catch (error) {
204
+ throw Object.assign(
205
+ new Error(
206
+ `${filePath}: invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
207
+ ),
208
+ { code: "configuration_invalid", retryable: true },
209
+ );
210
+ }
211
+ const result = fileV2Schema.safeParse(parsed);
212
+ if (!result.success)
213
+ throw Object.assign(
214
+ new Error(
215
+ `${filePath}: invalid configuration: ${result.error.issues
216
+ .map(
217
+ (issue) => `${issue.path.join(".") || "<root>"}: ${issue.message}`,
218
+ )
219
+ .join("; ")}`,
220
+ ),
221
+ { code: "configuration_invalid", retryable: true },
222
+ );
223
+ }
224
+
225
+ export async function writeConfigSource(
226
+ filePath: string,
227
+ source: string,
228
+ ): Promise<void> {
229
+ validateConfigSource(source, filePath);
230
+ const metadata = await lstat(filePath);
231
+ await replaceFileAtomically(filePath, source, metadata.mode);
232
+ }
233
+
234
+ export async function readConfigSource(filePath: string): Promise<string> {
235
+ return readFile(filePath, "utf8");
236
+ }
@@ -0,0 +1,206 @@
1
+ import { copyFile, lstat } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileV2Schema } from "./config-v2-schema";
5
+ import { replaceFileAtomically } from "./runtime/atomic";
6
+
7
+ export interface MigrationPreview {
8
+ changed: boolean;
9
+ fromVersion: number;
10
+ source: string;
11
+ toVersion: 2;
12
+ warnings: string[];
13
+ }
14
+
15
+ function quote(value: string): string {
16
+ return JSON.stringify(value);
17
+ }
18
+
19
+ function insertIntoSection(
20
+ source: string,
21
+ section: string,
22
+ line: string,
23
+ ): string {
24
+ const header = new RegExp(
25
+ `^[\\t ]*\\[${section.replaceAll(".", "\\.")}\\][\\t ]*(?:#.*)?$`,
26
+ "m",
27
+ );
28
+ const match = header.exec(source);
29
+ if (!match) return `${source.trimEnd()}\n\n[${section}]\n${line}\n`;
30
+ const index = match.index + match[0].length;
31
+ return `${source.slice(0, index)}\n${line}${source.slice(index)}`;
32
+ }
33
+
34
+ function formatterDefaults(source: string): string {
35
+ const headers = [
36
+ ...source.matchAll(
37
+ /^[\t ]*\[\[formatting\.formatters\]\][\t ]*(?:#.*)?$/gm,
38
+ ),
39
+ ];
40
+ let migrated = source;
41
+ for (let index = headers.length - 1; index >= 0; index -= 1) {
42
+ const header = headers[index] as RegExpMatchArray;
43
+ const start = (header.index ?? 0) + header[0].length;
44
+ const next = migrated.slice(start).search(/^[\t ]*\[/m);
45
+ const end = next < 0 ? migrated.length : start + next;
46
+ const body = migrated.slice(start, end);
47
+ const additions = [
48
+ /^[\t ]*id\s*=/m.test(body) ? undefined : `id = "legacy-${index + 1}"`,
49
+ /^[\t ]*enabled\s*=/m.test(body) ? undefined : "enabled = true",
50
+ /^[\t ]*mode\s*=/m.test(body) ? undefined : 'mode = "stdout"',
51
+ ].filter((item): item is string => Boolean(item));
52
+ if (additions.length)
53
+ migrated = `${migrated.slice(0, start)}\n${additions.join("\n")}${migrated.slice(start)}`;
54
+ }
55
+ return migrated;
56
+ }
57
+
58
+ function stripLegacySafety(source: string): string {
59
+ return source.replace(
60
+ /^\s*(allow_any_path|allow_external_roots|allow_temp_directory|follow_symlinks)\s*=.*(?:\r?\n|$)/gm,
61
+ "",
62
+ );
63
+ }
64
+
65
+ function rule(id: string, anchor: string, followSymlinks: boolean): string {
66
+ return [
67
+ "[[paths]]",
68
+ `id = ${quote(id)}`,
69
+ `path = ${quote(anchor)}`,
70
+ 'policies = { read = "allow", write = "allow", delete = "allow" }',
71
+ `follow_symlinks = ${followSymlinks}`,
72
+ 'includes = ["**/*"]',
73
+ 'excludes = [".git/**"]',
74
+ ].join("\n");
75
+ }
76
+
77
+ function parsedMigration(source: string) {
78
+ let parsed: Record<string, unknown>;
79
+ try {
80
+ parsed = Bun.TOML.parse(source) as Record<string, unknown>;
81
+ } catch (error) {
82
+ throw new Error(
83
+ `Invalid TOML: ${error instanceof Error ? error.message : String(error)}`,
84
+ );
85
+ }
86
+ const rawVersion = parsed.version;
87
+ const fromVersion = rawVersion === undefined ? 1 : Number(rawVersion);
88
+ if (!Number.isInteger(fromVersion) || fromVersion < 1 || fromVersion > 2)
89
+ throw new Error(`Unsupported ast-mcp.toml version: ${String(rawVersion)}`);
90
+ return { fromVersion, parsed };
91
+ }
92
+
93
+ function currentPreview(
94
+ parsed: Record<string, unknown>,
95
+ source: string,
96
+ ): MigrationPreview {
97
+ const result = fileV2Schema.safeParse(parsed);
98
+ if (!result.success)
99
+ throw new Error(`Invalid version 2 configuration: ${result.error.message}`);
100
+ return {
101
+ changed: false,
102
+ fromVersion: 2,
103
+ source,
104
+ toVersion: 2,
105
+ warnings: [],
106
+ };
107
+ }
108
+
109
+ function legacyRules(parsed: Record<string, unknown>, filePath: string) {
110
+ const safety = (parsed.safety ?? {}) as Record<string, unknown>;
111
+ const workspace = (parsed.workspace ?? {}) as { roots?: unknown };
112
+ const roots = Array.isArray(workspace.roots)
113
+ ? workspace.roots.filter((item): item is string => typeof item === "string")
114
+ : [];
115
+ const followSymlinks = safety.follow_symlinks === true;
116
+ const warnings: string[] = [];
117
+ const rules = roots.map((root, index) =>
118
+ rule(
119
+ `legacy-workspace-${index + 1}`,
120
+ path.resolve(path.dirname(filePath), root),
121
+ followSymlinks,
122
+ ),
123
+ );
124
+ if (safety.allow_temp_directory !== false)
125
+ rules.push(rule("legacy-os-temp", os.tmpdir(), followSymlinks));
126
+ if (safety.allow_any_path === true) {
127
+ rules.push(
128
+ rule(
129
+ "legacy-unrestricted",
130
+ path.parse(path.resolve(filePath)).root,
131
+ followSymlinks,
132
+ ),
133
+ );
134
+ warnings.push(
135
+ "UNRESTRICTED: safety.allow_any_path=true became an explicit catch-all path rule",
136
+ );
137
+ }
138
+ return { rules, warnings };
139
+ }
140
+
141
+ function migrateLegacyText(
142
+ source: string,
143
+ parsed: Record<string, unknown>,
144
+ filePath: string,
145
+ ) {
146
+ const { rules, warnings } = legacyRules(parsed, filePath);
147
+ let migrated = source;
148
+ const versionPattern = /^([\t ]*version[\t ]*=[\t ]*)[^\s#]+(.*)$/m;
149
+ migrated = versionPattern.test(migrated)
150
+ ? migrated.replace(
151
+ versionPattern,
152
+ (_match, prefix: string, suffix: string) => `${prefix}2${suffix}`,
153
+ )
154
+ : `version = 2\n\n${migrated}`;
155
+ const formatting = (parsed.formatting ?? {}) as Record<string, unknown>;
156
+ if (formatting.fallback === undefined)
157
+ migrated = insertIntoSection(migrated, "formatting", 'fallback = "dprint"');
158
+ migrated = formatterDefaults(migrated);
159
+ migrated = insertIntoSection(
160
+ migrated,
161
+ "files.patch",
162
+ 'aider_matchers = ["exact", "whitespace", "relative-indentation", "diff-match-patch"]',
163
+ );
164
+ migrated = stripLegacySafety(migrated);
165
+ migrated = `${migrated.trimEnd()}\n\n${rules.join("\n\n")}\n`;
166
+ const validated = fileV2Schema.safeParse(Bun.TOML.parse(migrated));
167
+ if (!validated.success)
168
+ throw new Error(
169
+ `Generated invalid version 2 configuration: ${validated.error.message}`,
170
+ );
171
+ return { migrated, warnings };
172
+ }
173
+
174
+ export function migrateConfigSource(
175
+ source: string,
176
+ filePath: string,
177
+ ): MigrationPreview {
178
+ const { fromVersion, parsed } = parsedMigration(source);
179
+ if (fromVersion === 2) return currentPreview(parsed, source);
180
+ const newline = source.includes("\r\n") ? "\r\n" : "\n";
181
+ const normalized = source.replaceAll("\r\n", "\n");
182
+ const { migrated, warnings } = migrateLegacyText(
183
+ normalized,
184
+ parsed,
185
+ filePath,
186
+ );
187
+ return {
188
+ changed: migrated !== normalized,
189
+ fromVersion,
190
+ source: newline === "\r\n" ? migrated.replaceAll("\n", "\r\n") : migrated,
191
+ toVersion: 2,
192
+ warnings,
193
+ };
194
+ }
195
+
196
+ export async function writeMigratedConfig(
197
+ filePath: string,
198
+ source: string,
199
+ backup = true,
200
+ ): Promise<string | undefined> {
201
+ const metadata = await lstat(filePath);
202
+ const backupPath = backup ? `${filePath}.v1.bak` : undefined;
203
+ if (backupPath) await copyFile(filePath, backupPath);
204
+ await replaceFileAtomically(filePath, source, metadata.mode);
205
+ return backupPath;
206
+ }