@mwillbanks/ast-mcp 0.1.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 (61) hide show
  1. package/CONTRIBUTING.md +60 -0
  2. package/LICENSE +21 -0
  3. package/README.md +109 -0
  4. package/dist/ast-mcp-hook.js +7 -0
  5. package/dist/ast-mcp-hook.js.map +11 -0
  6. package/dist/ast-mcp-install.js +22 -0
  7. package/dist/ast-mcp-install.js.map +12 -0
  8. package/dist/ast-mcp.js +115 -0
  9. package/dist/ast-mcp.js.map +89 -0
  10. package/dprint.json +37 -0
  11. package/logo.svg +1 -0
  12. package/package.json +89 -0
  13. package/src/ast-bro/capability.ts +21 -0
  14. package/src/ast-bro/client.ts +47 -0
  15. package/src/ast-bro/result.ts +42 -0
  16. package/src/ast-bro/rewrite-capability.ts +9 -0
  17. package/src/ast-bro/tools.json +603 -0
  18. package/src/hook.ts +79 -0
  19. package/src/http-entry.ts +3 -0
  20. package/src/http.ts +138 -0
  21. package/src/index.ts +8 -0
  22. package/src/installer.ts +501 -0
  23. package/src/lifecycle.ts +10 -0
  24. package/src/managed-hook.ts +4 -0
  25. package/src/patch/aider.ts +224 -0
  26. package/src/patch/engine.ts +446 -0
  27. package/src/patch/languages.ts +36 -0
  28. package/src/runtime/atomic.ts +26 -0
  29. package/src/runtime/attributes.ts +70 -0
  30. package/src/runtime/file-delete.ts +96 -0
  31. package/src/runtime/file-read.ts +178 -0
  32. package/src/runtime/format.ts +56 -0
  33. package/src/runtime/hash.ts +11 -0
  34. package/src/runtime/locks.ts +87 -0
  35. package/src/runtime/paths.ts +73 -0
  36. package/src/runtime/process-input.ts +25 -0
  37. package/src/runtime/signals.ts +47 -0
  38. package/src/server.ts +13 -0
  39. package/src/stdio.ts +154 -0
  40. package/src/tools/ast-bro.ts +172 -0
  41. package/src/tools/files.ts +173 -0
  42. package/src/tools/index.ts +11 -0
  43. package/src/tools/lifecycle.ts +124 -0
  44. package/templates/AGENTS.md +56 -0
  45. package/templates/skills/ast-mcp/SKILL.md +96 -0
  46. package/templates/skills/ast-mcp/agents/openai.yaml +4 -0
  47. package/templates/skills/ast-mcp/evals/batch.evals.json +274 -0
  48. package/templates/skills/ast-mcp/evals/evals.json +1209 -0
  49. package/templates/skills/ast-mcp/evals/file-hash.evals.json +50 -0
  50. package/templates/skills/ast-mcp/evals/measure.ts +18 -0
  51. package/templates/skills/ast-mcp/evals/results.md +17 -0
  52. package/templates/skills/ast-mcp/evals/score.ts +417 -0
  53. package/templates/skills/ast-mcp/evals/semantic.ts +332 -0
  54. package/templates/skills/ast-mcp/evals/trigger-queries.json +22 -0
  55. package/templates/skills/ast-mcp/evals/validate.ts +99 -0
  56. package/templates/skills/ast-mcp/references/installation.md +40 -0
  57. package/templates/skills/ast-mcp/references/managed-hook.ts +3 -0
  58. package/templates/skills/ast-mcp/references/patch-state-machine.md +39 -0
  59. package/templates/skills/ast-mcp/references/tool-catalog.md +46 -0
  60. package/templates/skills/ast-mcp/scripts/check-install.ts +269 -0
  61. package/templates/skills/ast-mcp/scripts/managed-hook.ts +22 -0
@@ -0,0 +1,332 @@
1
+ import path from "node:path";
2
+
3
+ export type EvalCase = {
4
+ id: number;
5
+ files: string[];
6
+ forbidden_tools: string[];
7
+ required_tools: string[];
8
+ expected_output: string;
9
+ assertions: string[];
10
+ };
11
+
12
+ export type Invocation = {
13
+ concurrent?: boolean;
14
+ index: number;
15
+ input: string;
16
+ tool: string;
17
+ };
18
+
19
+ const toolKeys: Record<string, string[]> = {
20
+ callees: ["target"],
21
+ callers: ["target"],
22
+ context: ["target"],
23
+ deps: ["file"],
24
+ digest: ["paths"],
25
+ file_hash: ["filePaths"],
26
+ file_read: ["files"],
27
+ find_related: ["path", "line"],
28
+ impact: ["target"],
29
+ implements: ["paths", "target"],
30
+ map: ["paths"],
31
+ reverse_deps: ["file"],
32
+ run: ["pattern"],
33
+ search: ["query"],
34
+ show: ["path", "symbols"],
35
+ squeeze: ["path"],
36
+ trace: ["from", "to"],
37
+ };
38
+
39
+ function hasKey(input: string, key: string) {
40
+ return new RegExp(`(?:["']${key}["']|\\b${key})\\s*:`).test(input);
41
+ }
42
+
43
+ function withoutComments(input: string) {
44
+ let output = "";
45
+ let quote = "";
46
+ let escaped = false;
47
+ for (let index = 0; index < input.length; index += 1) {
48
+ const character = input[index] as string;
49
+ const next = input[index + 1];
50
+ if (quote) {
51
+ output += character;
52
+ if (escaped) escaped = false;
53
+ else if (character === "\\") escaped = true;
54
+ else if (character === quote) quote = "";
55
+ continue;
56
+ }
57
+ if (character === '"' || character === "'" || character === "`") {
58
+ quote = character;
59
+ output += character;
60
+ continue;
61
+ }
62
+ if (character === "/" && next === "/") {
63
+ while (index + 1 < input.length && input[index + 1] !== "\n") index += 1;
64
+ output += "\n";
65
+ continue;
66
+ }
67
+ if (character === "/" && next === "*") {
68
+ index += 2;
69
+ while (
70
+ index + 1 < input.length &&
71
+ !(input[index] === "*" && input[index + 1] === "/")
72
+ )
73
+ index += 1;
74
+ index += 1;
75
+ output += " ";
76
+ continue;
77
+ }
78
+ output += character;
79
+ }
80
+ return output;
81
+ }
82
+
83
+ function hasBoolean(input: string, key: string, value: boolean) {
84
+ return new RegExp(
85
+ `(?:["']${key}["']|\\b${key})\\s*:\\s*${String(value)}\\b`,
86
+ ).test(input);
87
+ }
88
+
89
+ function meaningfulInput(invocation: Invocation) {
90
+ const input = withoutComments(invocation.input).trim();
91
+ if (!input || input === "{}") return false;
92
+ if (invocation.tool === "file_patch") {
93
+ return (
94
+ hasKey(input, "expectedSha256") &&
95
+ hasKey(input, "patchStrategy") &&
96
+ (hasKey(input, "astRules") || hasKey(input, "aiderBlocks"))
97
+ );
98
+ }
99
+ if (invocation.tool === "file_write")
100
+ return hasKey(input, "content") && /["'][^"']+["']\s*:/.test(input);
101
+ if (invocation.tool === "file_chattr")
102
+ return hasKey(input, "chattr") && /["'][^"']+["']\s*:/.test(input);
103
+ if (invocation.tool === "file_delete")
104
+ return hasKey(input, "expectedSha256") && /["'][^"']+["']\s*:/.test(input);
105
+ return (toolKeys[invocation.tool] ?? []).every((key) => hasKey(input, key));
106
+ }
107
+
108
+ function pathIsWithinRoot(candidate: string, roots: string[]) {
109
+ if (!path.isAbsolute(candidate))
110
+ return !candidate.split(/[\\/]+/).includes("..");
111
+ return roots.some((root) => {
112
+ const relative = path.relative(root, candidate);
113
+ return (
114
+ relative === "" ||
115
+ (!relative.startsWith("..") && !path.isAbsolute(relative))
116
+ );
117
+ });
118
+ }
119
+
120
+ function pathErrors(invocations: Invocation[], roots: string[]) {
121
+ const errors: string[] = [];
122
+ const singlePath =
123
+ /["']?(?:filePath|file|path|root)["']?\s*:\s*["']([^"']+)["']/g;
124
+ const pathArray = /["']?(?:filePaths|paths)["']?\s*:\s*\[([^\]]*)\]/gs;
125
+ const keyedPath =
126
+ /["']([^"']+)["']\s*:\s*\{\s*(?:content|expectedSha256|chattr|astRules|aiderBlocks|patchStrategy)\s*:/g;
127
+ for (const invocation of invocations) {
128
+ const input = withoutComments(invocation.input);
129
+ const candidates: string[] = [];
130
+ for (const expression of [singlePath, keyedPath]) {
131
+ expression.lastIndex = 0;
132
+ for (const match of input.matchAll(expression))
133
+ if (match[1]) candidates.push(match[1]);
134
+ }
135
+ pathArray.lastIndex = 0;
136
+ for (const match of input.matchAll(pathArray))
137
+ for (const value of match[1]?.matchAll(/["']([^"']+)["']/g) ?? [])
138
+ if (value[1]) candidates.push(value[1]);
139
+ for (const candidate of candidates)
140
+ if (
141
+ (candidate.includes("/") || candidate.includes("\\")) &&
142
+ !pathIsWithinRoot(candidate, roots)
143
+ )
144
+ errors.push(
145
+ `${invocation.tool} input escapes transcript workspace roots: ${candidate}`,
146
+ );
147
+ }
148
+ return errors;
149
+ }
150
+
151
+ function isBatch(invocation: Invocation) {
152
+ const input = withoutComments(invocation.input);
153
+ if (
154
+ ["file_patch", "file_write", "file_chattr", "file_delete"].includes(
155
+ invocation.tool,
156
+ )
157
+ )
158
+ return (input.match(/["'][^"']+["']\s*:\s*\{/g) ?? []).length > 1;
159
+ if (invocation.tool === "file_hash")
160
+ return /filePaths\s*:\s*\[[^\]]+,[^\]]+\]/s.test(input);
161
+ if (invocation.tool === "file_read")
162
+ return (input.match(/filePath\s*:/g) ?? []).length > 1;
163
+ return false;
164
+ }
165
+
166
+ function assertionSatisfied(
167
+ assertion: string,
168
+ evaluation: EvalCase,
169
+ invocations: Invocation[],
170
+ output: string,
171
+ ) {
172
+ const normalized = assertion.toLowerCase();
173
+ const sanitizedInvocations = invocations.map((invocation) => ({
174
+ ...invocation,
175
+ input: withoutComments(invocation.input),
176
+ }));
177
+ const tools = new Set(
178
+ sanitizedInvocations.map((invocation) => invocation.tool),
179
+ );
180
+ const source = sanitizedInvocations
181
+ .map((invocation) => invocation.input)
182
+ .join("\n");
183
+ const calls = (tool: string) =>
184
+ sanitizedInvocations.filter((invocation) => invocation.tool === tool);
185
+ if (
186
+ normalized.includes("does not call") ||
187
+ normalized.includes("does not use") ||
188
+ normalized.includes("never calls")
189
+ )
190
+ return evaluation.forbidden_tools.every((tool) => !tools.has(tool));
191
+ if (
192
+ normalized.includes("direct filesystem") ||
193
+ normalized.includes("direct editor") ||
194
+ normalized.includes("shell mutation")
195
+ )
196
+ return !/(?:writeFile|apply_patch|sed\s+-i|tee\s|>\s*["']?[^=])/i.test(
197
+ source,
198
+ );
199
+ if (normalized.includes("bounded") && normalized.includes("lines"))
200
+ return calls("file_read").some((call) =>
201
+ /lines\s*:\s*\[\s*\d+\s*,\s*\d+\s*\]/.test(call.input),
202
+ );
203
+ if (normalized.includes("maxbytes") || normalized.includes("64 kib"))
204
+ return calls("file_read").every((call) => hasKey(call.input, "maxBytes"));
205
+ if (normalized.includes("batch") || normalized.includes("one keyed"))
206
+ return invocations.some(isBatch);
207
+ if (normalized.includes("fresh") && normalized.includes("hash")) {
208
+ const hashIndex = calls("file_hash")[0]?.index;
209
+ const mutationIndex = invocations.find((call) =>
210
+ ["file_patch", "file_write", "file_delete"].includes(call.tool),
211
+ )?.index;
212
+ return (
213
+ hashIndex !== undefined &&
214
+ mutationIndex !== undefined &&
215
+ hashIndex < mutationIndex
216
+ );
217
+ }
218
+ if (normalized.includes("preview true"))
219
+ return calls("file_patch").some((call) =>
220
+ hasBoolean(call.input, "preview", true),
221
+ );
222
+ if (normalized.includes("preview") || normalized.includes("dry run"))
223
+ return (
224
+ calls("run").some((call) => !hasBoolean(call.input, "write", true)) ||
225
+ calls("file_patch").some((call) =>
226
+ hasBoolean(call.input, "preview", true),
227
+ )
228
+ );
229
+ if (normalized.includes("exactly one match"))
230
+ return calls("file_patch").some((call) =>
231
+ /expectedMatches\s*:\s*1\b/.test(call.input),
232
+ );
233
+ if (
234
+ normalized.includes("ast strategy") ||
235
+ normalized.includes("patchstrategy ast")
236
+ )
237
+ return calls("file_patch").some((call) =>
238
+ /patchStrategy\s*:\s*["']ast["']/.test(call.input),
239
+ );
240
+ if (normalized.includes("aider"))
241
+ return calls("file_patch").some((call) =>
242
+ /patchStrategy\s*:\s*["']aider_block["']/.test(call.input),
243
+ );
244
+ if (
245
+ normalized.includes("reports") ||
246
+ normalized.includes("verification") ||
247
+ normalized.includes("output")
248
+ )
249
+ return output.trim().length > 0;
250
+ return (
251
+ evaluation.required_tools.every((tool) => tools.has(tool)) &&
252
+ sanitizedInvocations.every(meaningfulInput) &&
253
+ output.trim().length > 0
254
+ );
255
+ }
256
+
257
+ export function verifyEvaluation(
258
+ evaluation: EvalCase,
259
+ invocations: Invocation[],
260
+ output: string,
261
+ roots: string[],
262
+ ) {
263
+ const errors: string[] = [];
264
+ const sanitizedInvocations = invocations.map((invocation) => ({
265
+ ...invocation,
266
+ input: withoutComments(invocation.input),
267
+ }));
268
+ const tools = new Set(
269
+ sanitizedInvocations.map((invocation) => invocation.tool),
270
+ );
271
+ for (const tool of evaluation.required_tools)
272
+ if (!tools.has(tool)) errors.push(`missing required tool: ${tool}`);
273
+ for (const tool of evaluation.forbidden_tools)
274
+ if (tools.has(tool)) errors.push(`used forbidden tool: ${tool}`);
275
+ for (const invocation of invocations)
276
+ if (!meaningfulInput(invocation))
277
+ errors.push(`${invocation.tool} has empty or schema-incomplete input`);
278
+ if (
279
+ evaluation.required_tools.length > 1 &&
280
+ invocations.some(
281
+ (invocation) =>
282
+ invocation.concurrent &&
283
+ evaluation.required_tools.includes(invocation.tool),
284
+ )
285
+ )
286
+ errors.push("required tool sequence is concurrent and cannot be proven");
287
+ let priorIndex = -1;
288
+ for (const tool of evaluation.required_tools) {
289
+ const next = invocations.find(
290
+ (invocation) => invocation.tool === tool && invocation.index > priorIndex,
291
+ );
292
+ if (!next) {
293
+ if (tools.has(tool))
294
+ errors.push(`required tool sequence is not satisfied at: ${tool}`);
295
+ continue;
296
+ }
297
+ priorIndex = next.index;
298
+ }
299
+ errors.push(...pathErrors(invocations, roots));
300
+ for (const file of evaluation.files) {
301
+ if (
302
+ !invocations.some((invocation) =>
303
+ withoutComments(invocation.input).includes(file),
304
+ )
305
+ )
306
+ errors.push(`input does not target required file: ${file}`);
307
+ if (!output.includes(file))
308
+ errors.push(`output does not prove file result: ${file}`);
309
+ }
310
+ if (
311
+ !assertionSatisfied(
312
+ evaluation.expected_output,
313
+ evaluation,
314
+ invocations,
315
+ output,
316
+ )
317
+ )
318
+ errors.push(`expected output not proven: ${evaluation.expected_output}`);
319
+ if (
320
+ evaluation.required_tools.length === 0 &&
321
+ !evaluation.expected_output
322
+ .toLowerCase()
323
+ .split(/\W+/)
324
+ .filter((word) => word.length >= 7)
325
+ .some((word) => output.toLowerCase().includes(word))
326
+ )
327
+ errors.push("output does not prove expected transport behavior");
328
+ for (const assertion of evaluation.assertions)
329
+ if (!assertionSatisfied(assertion, evaluation, invocations, output))
330
+ errors.push(`assertion not proven: ${assertion}`);
331
+ return errors;
332
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "should_not_trigger": [
3
+ "Explain what an abstract syntax tree is.",
4
+ "Draft a project status email.",
5
+ "Summarize this pasted paragraph without opening a repository.",
6
+ "Generate a standalone image of a dependency graph.",
7
+ "What is the latest stable Bun release?",
8
+ "Review this already supplied diff without changing files or exploring the checkout.",
9
+ "Translate this error message into Spanish.",
10
+ "Create a calendar reminder for tomorrow."
11
+ ],
12
+ "should_trigger": [
13
+ "Map this unfamiliar repository before I change its public API.",
14
+ "Find every caller of this method and rename it safely.",
15
+ "Create a new source file without using shell writes.",
16
+ "Patch this README paragraph through the AST-isolated environment.",
17
+ "Show the blast radius of changing PaymentService.",
18
+ "The ast-mcp tools disappeared; help me restore the local MCP.",
19
+ "Install the code-intelligence and blocking hooks globally for Codex.",
20
+ "Trace how the request handler reaches the database call."
21
+ ]
22
+ }
@@ -0,0 +1,99 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ type EvalCase = {
5
+ id: number;
6
+ surface: string;
7
+ category: "positive" | "variant" | "negative";
8
+ variant: string;
9
+ prompt: string;
10
+ expected_output: string;
11
+ required_tools: string[];
12
+ forbidden_tools: string[];
13
+ assertions: string[];
14
+ files: string[];
15
+ };
16
+
17
+ type EvalSuite = {
18
+ skill_name: string;
19
+ mcp_tools: string[];
20
+ special_surfaces?: string[];
21
+ evals: EvalCase[];
22
+ };
23
+
24
+ const suitePath = path.join(import.meta.dir, "evals.json");
25
+ const suite = await (async () => {
26
+ const [primaryJson, fileHashJson, batchJson] = await Promise.all([
27
+ readFile(suitePath, "utf8"),
28
+ readFile(path.join(import.meta.dir, "file-hash.evals.json"), "utf8"),
29
+ readFile(path.join(import.meta.dir, "batch.evals.json"), "utf8"),
30
+ ]);
31
+ const primary = JSON.parse(primaryJson) as EvalSuite;
32
+ const fileHashEvals = JSON.parse(fileHashJson) as EvalCase[];
33
+ const batchEvals = JSON.parse(batchJson) as EvalCase[];
34
+ return {
35
+ ...primary,
36
+ evals: [...primary.evals, ...fileHashEvals, ...batchEvals],
37
+ };
38
+ })();
39
+ const errors: string[] = [];
40
+ const known = new Set([...suite.mcp_tools, ...(suite.special_surfaces ?? [])]);
41
+
42
+ if (suite.skill_name !== "ast-mcp") errors.push("skill_name must be ast-mcp");
43
+
44
+ if (new Set(suite.mcp_tools).size !== suite.mcp_tools.length)
45
+ errors.push("mcp_tools contains duplicate names");
46
+
47
+ if (suite.evals.length < known.size * 3)
48
+ errors.push("suite must contain at least three cases per surface");
49
+
50
+ const ids = new Set<number>();
51
+ for (const evaluation of suite.evals) {
52
+ if (ids.has(evaluation.id))
53
+ errors.push(`duplicate eval id: ${evaluation.id}`);
54
+ ids.add(evaluation.id);
55
+
56
+ if (!known.has(evaluation.surface))
57
+ errors.push(`unknown surface: ${evaluation.surface}`);
58
+
59
+ for (const tool of [
60
+ ...evaluation.required_tools,
61
+ ...evaluation.forbidden_tools,
62
+ ])
63
+ if (!known.has(tool))
64
+ errors.push(`eval ${evaluation.id} references unknown tool: ${tool}`);
65
+
66
+ if (!evaluation.prompt || !evaluation.expected_output)
67
+ errors.push(`eval ${evaluation.id} must define prompt and expected_output`);
68
+
69
+ if (evaluation.assertions.length < 3)
70
+ errors.push(`eval ${evaluation.id} needs at least three assertions`);
71
+ }
72
+
73
+ for (const surface of known) {
74
+ const cases = suite.evals.filter(
75
+ (evaluation) => evaluation.surface === surface,
76
+ );
77
+ if (cases.length < 3) errors.push(`${surface} has fewer than three cases`);
78
+ if (
79
+ cases.filter((evaluation) => evaluation.category === "positive").length < 1
80
+ )
81
+ errors.push(`${surface} has no positive case`);
82
+ if (
83
+ cases.filter((evaluation) => evaluation.category === "variant").length < 1
84
+ )
85
+ errors.push(`${surface} has no variant case`);
86
+ if (
87
+ cases.filter((evaluation) => evaluation.category === "negative").length < 1
88
+ )
89
+ errors.push(`${surface} has no negative case`);
90
+ }
91
+
92
+ if (errors.length > 0) {
93
+ console.error(errors.map((error) => `- ${error}`).join("\n"));
94
+ process.exit(1);
95
+ }
96
+
97
+ console.log(
98
+ `Validated ${suite.evals.length} eval cases across ${suite.mcp_tools.length} MCP surfaces.`,
99
+ );
@@ -0,0 +1,40 @@
1
+ # Installation and recovery
2
+
3
+ Use this only when the ast-mcp tools are absent, incomplete, or disconnected. Do not continue with a different editor.
4
+
5
+ ## Diagnose
6
+
7
+ From the installed skill directory, run the read-only checker:
8
+
9
+ `bun run scripts/check-install.ts --scope local --target codex --root "$PWD"`
10
+
11
+ Replace `codex` with `claude` or `copilot`. For a global installation, pass `--scope global`. The JSON result validates the marked guidance against the bundled template, checks the host-specific MCP, hook payload and registration, skill, and prints the appropriate install or update command.
12
+
13
+ ## Install from this package checkout
14
+
15
+ When the `@mwillbanks/ast-mcp` source checkout is already available:
16
+
17
+ `bun run bin/ast-mcp-install.ts install --scope local --target all --root "$PWD"`
18
+
19
+ For one host globally:
20
+
21
+ `bun run bin/ast-mcp-install.ts install --scope global --target codex`
22
+
23
+ Targets are `codex`, `claude`, `copilot`, or `all`.
24
+
25
+ ## Install from the published package
26
+
27
+ If the package is not already installed, obtain user authorization before allowing Bun to download or install it. Then run:
28
+
29
+ `bunx --package @mwillbanks/ast-mcp ast-mcp-install install --scope local --target all --root "$PWD"`
30
+
31
+ For a global host surface, change the scope and select one target. The installer preserves unrelated configuration and updates the managed ast-mcp blocks idempotently. Run the same command with `update` to refresh MCP definitions, hook payloads and registrations, the skill, and the marked instruction block. Run it with `uninstall` to remove only ast-mcp-managed content.
32
+
33
+ ## Activate and verify
34
+
35
+ 1. Restart or reconnect MCP servers in the host; a skill file alone cannot make MCP tools callable. A supervised ast-mcp process may receive `SIGHUP`, which performs graceful cleanup and exits 0 so the host can restart it from refreshed code and configuration.
36
+ 2. Confirm `file_hash`, `file_read`, `file_write`, and `file_patch` are present.
37
+ 3. Confirm direct intelligence tools such as `digest`, `map`, `show`, `context`, and `impact` are present; there is no proxy tool.
38
+ 4. Verify that `file_read` accepts batched `files`, `file_hash` accepts batched `filePaths`, and `file_write`/`file_patch` accept path-keyed batches with ordered per-file operations; the legacy whole-file `file_read({ filePath })` schema is stale.
39
+ 5. Rerun `check-install.ts` if the tool list remains incomplete.
40
+ 6. If configuration is correct but startup fails, run the package's `bun run tools:check` from its checkout and report the missing dependency or startup error. Do not bypass the write boundary.
@@ -0,0 +1,3 @@
1
+ export type { HookEvent } from "../scripts/managed-hook";
2
+
3
+ export { isManagedHook } from "../scripts/managed-hook";
@@ -0,0 +1,39 @@
1
+ # Patch state machine
2
+
3
+ The server distinguishes AST inspection from structural rewrite support. AST-capable files use `map`, `show`, `search`, `context`, or `run` for content discovery; a rewrite target is structurally capable only when its language supports `run` and ast-bro reports `error_count: 0`.
4
+
5
+ ## Route selection
6
+
7
+ 1. Inspect AST-capable content with intelligence tools. Inspect unsupported content with batched, bounded `file_read` slices.
8
+ 2. Preview every ordered structural rule with ast-bro `run`; for the full guarded and formatted dry run, use the same keyed `file_patch` entry with `preview: true`, then obtain one fresh `file_hash` per keyed path immediately before mutation.
9
+ 3. Use one path-keyed `file_patch` object for one or more files. Each value has one `expectedSha256`, one `patchStrategy`, ordered `astRules` or `aiderBlocks` arrays, and optional `preview`.
10
+ 4. Use one path-keyed `file_write` object for new files or existing non-structurally-rewritable files; existing replacements still require their own fresh `expectedSha256`. Use the shared `chattr` object for chmod/chown metadata. Missing parents are created only after a guarded write returns `ENOENT`, followed by path revalidation.
11
+ 5. Use `file_chattr` for metadata-only changes. Use `file_delete` with a fresh hash for deletion; it preflights all targets and AST import references before any deletion, rejects referenced source unless `forceReferences` is explicit, then removes empty ancestor directories after releasing locks.
12
+ 6. Operations for one path are serialized under one lock and one atomic commit. A preview returns a bounded diff and leaves that path unchanged; a failed rule also leaves it unchanged.
13
+ 7. Use direct `run` with `rewrite` and `write: true` only for an intentionally bounded lower-level rewrite; normal agent mutations belong to `file_patch`.
14
+ 8. New files use `file_write`.
15
+
16
+ MCP transport requests may contain a JSON-RPC array of requests and notifications. Preserve request IDs and expect one response per request, with notifications omitted.
17
+
18
+ ## Structural rule discipline
19
+
20
+ - Pattern the smallest complete syntax node that uniquely expresses the change.
21
+ - Use `$NODE` for one node and `$$NODES` for zero or more nodes.
22
+ - Preview with the same language, explicit paths, and optional glob.
23
+ - Inspect search matches, then use `file_patch` with `preview: true` for the full guarded diff; keep direct `run.write` for exceptional lower-level rewrites only.
24
+ - ast-bro 3.0.0 changes only the first match in each file; narrow ambiguous patterns rather than assuming replace-all behavior.
25
+ - Split declarations, calls, and type references into separate rules.
26
+
27
+ ## Aider block discipline
28
+
29
+ The native TypeScript matcher attempts exact, whitespace-normalized, relative-indentation, and diff-match-patch matching. Use bounded `file_read` slices to identify the smallest unique surrounding block, expand the slice and block on ambiguity, and never use fallback matching to bypass a structurally rewritable route.
30
+
31
+ ## Rejections
32
+
33
+ - `Stale file context`: refresh `file_hash`, re-inspect through the correct AST or bounded non-AST route, and rebuild the patch.
34
+ - AST-capable `file_read` rejection: route to `map`, `show`, `search`, `context`, or `run`.
35
+ - `matched N nodes; expected M`: inspect and narrow the rule.
36
+ - `first match per file`: reduce file_patch to one match or use a bounded direct run across files.
37
+ - capped preview or read: narrow paths, glob, pattern, line ranges, or byte caps.
38
+ - dprint preflight failure: the formatter does not support the target under the active configuration; no direct run write occurs.
39
+ - path or symlink rejection: use a real path under `AST_MCP_ROOTS`.
@@ -0,0 +1,46 @@
1
+ # Direct tool catalog
2
+
3
+ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy tool and do not shell out to ast-bro.
4
+
5
+ ## File boundary
6
+
7
+ - `file_hash({ filePaths })`: batch up to 50 AST or non-AST paths and stream each whole file into SHA-256 without returning source content.
8
+ - `file_read({ files })`: batch up to 50 non-AST files. Each request accepts a zero-based, end-exclusive `lines` tuple and `maxBytes`; defaults are `[0, 100]` and 1 MiB, with hard caps of 1,000 lines and 1 MiB per slice. AST-capable files are rejected and routed to intelligence tools.
9
+ - `file_chattr({ "/repo/a.txt": { chattr, expectedSha256? } })`: applies the shared `chattr` contract (`chmod?`, same-owner `chown?`) under deterministic locks and reports the effective attributes.
10
+ - `file_write({ "/repo/a.txt": { content, chattr? }, "/repo/b.txt": { content, expectedSha256?, chattr? } })`: create or replace multiple files in one keyed batch; existing replacements remain limited to non-AST-rewritable files. Missing parents are created only after the write attempt returns `ENOENT`, then the path is revalidated.
11
+ - `file_patch({ "/repo/src/a.ts": { expectedSha256, patchStrategy: "ast", astRules: [...], chattr? } })`: patch one or more files in one keyed batch. Use ordered `astRules` or `aiderBlocks`; every path has one fresh hash and one atomic commit.
12
+ - `file_delete({ "/repo/a.txt": { expectedSha256, forceReferences? } })`: preflights all targets and AST import references before any deletion, rejects referenced source unless explicitly overridden, and removes empty ancestor directories within the configured root.
13
+ - The keyed mutation tools return a `files` result map. MCP transport also accepts JSON-RPC request/notification arrays and returns one response per request ID.
14
+
15
+ ## Shape and source
16
+
17
+ - `digest({ paths, include_private?, include_fields?, max_members?, json? })`: compact map of unfamiliar directories.
18
+ - `map({ paths, glob?, no_private?, no_fields?, no_docs?, no_attrs?, no_lines?, json? })`: signatures, parse error counts, and line ranges.
19
+ - `show({ path, symbols, json? })`: source for known symbols.
20
+ - `surface({ path, tree?, include_chain?, include_private?, max_depth?, lang?, json? })`: public API and re-exports.
21
+
22
+ ## Discovery, dependencies, and calls
23
+
24
+ - `search({ query, path?, top_k?, alpha?, languages?, json? })`, `find_related({ path, line, root?, top_k?, json? })`, `context({ target, path?, budget?, json? })`, `index({ path?, rebuild?, stats?, json? })`.
25
+ - `deps({ file, ... })`, `reverse_deps({ file, ... })`, `graph({ path?, ... })`, `cycles({ path?, ... })`.
26
+ - `callers({ target, ... })`, `callees({ target, ... })`, `trace({ from, to, ... })`, `implements({ target, paths?, direct?, json? })`.
27
+ - `impact({ target, path?, mode?, depth?, limit?, tests?, exclude_tests?, hide_ambiguous?, json? })`: combined blast radius. Valid modes are `all`, `deps`, `dependents`, and `tests`.
28
+
29
+ ## Structural run
30
+
31
+ `run({ pattern, paths?, lang?, glob?, rewrite?, write?, json? })` provides:
32
+
33
+ - search when `rewrite` is omitted, including location and matched text;
34
+ - dry-run per-file diffs when `rewrite` is present and `write` is false or omitted;
35
+ - disk rewrite when both `rewrite` and `write: true` are present.
36
+
37
+ For pinned ast-bro 3.0.0, write mode changes the first match per file, caps a call at 50 files, and reports rewritten files rather than node counts. Through ast-mcp, paths are root-checked, search is repeated as a non-capped safety preview, each candidate is checked against dprint, and each rewritten file is atomically formatted. Narrow rules to one intended match per file.
38
+
39
+ - `squeeze({ path, start?, end?, raw?, json? })`: compression for repetitive logs/text, not source code.
40
+
41
+ ## Common sequences
42
+
43
+ - Rename: `impact` → `show`/`context` → `run` search → `run` dry diff → bounded `run.write` → AST absence check.
44
+ - Atomic single-file edit: AST inspection → `run` search → `file_hash` → `file_patch` with one expected match → AST verification.
45
+ - Unsupported text edit: bounded batched `file_read` → `file_hash` → unique Aider block → bounded `file_read` verification.
46
+ - Refactor module: `surface` → `deps` + `reverse_deps` → `impact` → edits → `cycles`.