@mwillbanks/ast-mcp 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CONTRIBUTING.md +13 -0
  2. package/README.md +18 -14
  3. package/dist/ast-mcp.js +183 -137
  4. package/dist/ast-mcp.js.map +58 -42
  5. package/package.json +17 -11
  6. package/src/ast-bro/capability.ts +20 -10
  7. package/src/ast-bro/tools.json +22 -2
  8. package/src/cli.ts +10 -7
  9. package/src/config-cli.ts +166 -19
  10. package/src/config-migrate.ts +223 -0
  11. package/src/config-registry.ts +321 -0
  12. package/src/config-schema-common.ts +81 -0
  13. package/src/config-v2-schema.ts +97 -0
  14. package/src/config.ts +375 -149
  15. package/src/helpers/ast-bro.ts +1 -7
  16. package/src/helpers/config.ts +12 -3
  17. package/src/helpers/installer.ts +8 -0
  18. package/src/helpers/mcp-schema.ts +105 -4
  19. package/src/host-smoke.ts +182 -0
  20. package/src/http.ts +8 -3
  21. package/src/installer-transport.ts +6 -4
  22. package/src/installer.ts +192 -51
  23. package/src/patch/engine.ts +555 -279
  24. package/src/patch/languages.ts +9 -0
  25. package/src/patch/strategy/aiderBlock.ts +110 -0
  26. package/src/patch/strategy/ast.ts +170 -0
  27. package/src/patch/strategy.ts +61 -0
  28. package/src/runtime/approval.ts +438 -0
  29. package/src/runtime/dependencies.ts +1 -1
  30. package/src/runtime/document-inspection.ts +78 -0
  31. package/src/runtime/file-capabilities.ts +250 -0
  32. package/src/runtime/file-delete.ts +122 -20
  33. package/src/runtime/file-read.ts +142 -14
  34. package/src/runtime/file-rename.ts +7 -6
  35. package/src/runtime/format.ts +65 -27
  36. package/src/runtime/path-policy.ts +557 -0
  37. package/src/runtime/path-utils.ts +40 -0
  38. package/src/runtime/paths.ts +204 -43
  39. package/src/server.ts +2 -1
  40. package/src/tools/ast-bro.ts +197 -76
  41. package/src/tools/configuration.ts +450 -0
  42. package/src/tools/configured.ts +49 -21
  43. package/src/tools/files.ts +177 -73
  44. package/src/tools/index.ts +2 -0
  45. package/src/tools/lifecycle.ts +89 -45
  46. package/templates/AGENTS.md +15 -17
  47. package/templates/skills/ast-mcp/SKILL.md +50 -34
  48. package/templates/skills/ast-mcp/evals/batch.evals.json +9 -9
  49. package/templates/skills/ast-mcp/evals/evals.json +221 -9
  50. package/templates/skills/ast-mcp/evals/measure.ts +27 -4
  51. package/templates/skills/ast-mcp/evals/score.test.ts +46 -3
  52. package/templates/skills/ast-mcp/evals/score.ts +87 -0
  53. package/templates/skills/ast-mcp/evals/semantic.test.ts +209 -28
  54. package/templates/skills/ast-mcp/evals/semantic.ts +151 -37
  55. package/templates/skills/ast-mcp/references/installation.md +12 -12
  56. package/templates/skills/ast-mcp/references/patch-state-machine.md +15 -14
  57. package/templates/skills/ast-mcp/references/tool-catalog.md +16 -10
  58. package/templates/skills/ast-mcp/scripts/check-install.ts +8 -17
  59. package/src/ast-bro/rewrite-capability.ts +0 -9
@@ -1,3 +1,4 @@
1
+ import os from "node:os";
1
2
  import path from "node:path";
2
3
  import { embeddedShellMutates, shellMutates } from "./shell-policy";
3
4
  import { advanceQuote } from "./source";
@@ -24,12 +25,14 @@ const toolKeys: Record<string, string[]> = {
24
25
  context: ["target"],
25
26
  deps: ["file"],
26
27
  digest: ["paths"],
28
+ document_query: ["filePath", "selectors"],
27
29
  file_hash: ["filePaths"],
28
30
  file_read: ["files"],
29
31
  find_related: ["path", "line"],
30
32
  impact: ["target"],
31
33
  implements: ["paths", "target"],
32
34
  map: ["paths"],
35
+ policy_check: ["checks"],
33
36
  reverse_deps: ["file"],
34
37
  run: ["pattern"],
35
38
  search: ["query"],
@@ -114,25 +117,38 @@ function hasBoolean(input: string, key: string, value: boolean) {
114
117
 
115
118
  type InputValidator = (input: string) => boolean;
116
119
 
117
- const hasKeyedPath = (input: string) => /["'][^"']+["']\s*:/.test(input);
120
+ const fileEntryKeyPattern =
121
+ "(?:aiderBlocks|astRules|chattr|content|destination|expectedSha256|forceReferences|patchStrategy|preview)";
122
+ const declaredFileBatchExpression = new RegExp(
123
+ `^\\s*(?:(?:await\\s+)?tools\\.mcp__ast_mcp__file_(?:chattr|delete|patch|rename|write)\\s*\\(\\s*)?\\{\\s*["']?files["']?\\s*:\\s*\\{\\s*["']([^"']+)["']\\s*:\\s*\\{\\s*["']?${fileEntryKeyPattern}["']?\\s*:`,
124
+ "s",
125
+ );
126
+
127
+ const hasDeclaredFileBatch = (input: string) => {
128
+ declaredFileBatchExpression.lastIndex = 0;
129
+ return declaredFileBatchExpression.test(withoutComments(input));
130
+ };
118
131
  const inputValidators: Record<string, InputValidator> = {
119
- file_chattr: (input) => hasKey(input, "chattr") && hasKeyedPath(input),
132
+ file_chattr: (input) =>
133
+ hasKey(input, "chattr") && hasDeclaredFileBatch(input),
120
134
  file_delete: (input) =>
121
- hasKey(input, "expectedSha256") && hasKeyedPath(input),
135
+ hasKey(input, "expectedSha256") && hasDeclaredFileBatch(input),
122
136
  file_patch: (input) =>
123
137
  hasKey(input, "expectedSha256") &&
124
138
  hasKey(input, "patchStrategy") &&
139
+ hasDeclaredFileBatch(input) &&
125
140
  (hasKey(input, "astRules") || hasKey(input, "aiderBlocks")),
126
141
  file_rename: (input) =>
127
142
  hasKey(input, "expectedSha256") &&
128
143
  hasKey(input, "destination") &&
129
- hasKeyedPath(input),
130
- file_write: (input) => hasKey(input, "content") && hasKeyedPath(input),
144
+ hasDeclaredFileBatch(input),
145
+ file_write: (input) =>
146
+ hasKey(input, "content") && hasDeclaredFileBatch(input),
131
147
  };
132
148
 
133
149
  function meaningfulInput(invocation: Invocation) {
134
150
  const input = withoutComments(invocation.input).trim();
135
- if (!input || input === "{}") return false;
151
+ if (!input || input === "{}") return invocation.tool === "config_status";
136
152
  const validator = inputValidators[invocation.tool];
137
153
  if (validator) return validator(input);
138
154
  return (toolKeys[invocation.tool] ?? []).every((key) => hasKey(input, key));
@@ -154,8 +170,10 @@ const singlePathExpression =
154
170
  /["']?(?:filePath|file|path|root|destination)["']?\s*:\s*["']([^"']+)["']/g;
155
171
  const pathArrayExpression =
156
172
  /["']?(?:filePaths|paths)["']?\s*:\s*\[([^\]]*)\]/gs;
157
- const keyedPathExpression =
158
- /["']([^"']+)["']\s*:\s*\{\s*(?:content|expectedSha256|destination|chattr|astRules|aiderBlocks|patchStrategy)\s*:/g;
173
+ const keyedPathExpression = new RegExp(
174
+ `["']([^"']+)["']\\s*:\\s*\\{\\s*["']?${fileEntryKeyPattern}["']?\\s*:`,
175
+ "g",
176
+ );
159
177
 
160
178
  function expressionValues(input: string, expression: RegExp) {
161
179
  expression.lastIndex = 0;
@@ -184,18 +202,80 @@ function escapedPath(candidate: string, roots: string[]) {
184
202
  return pathLike && !pathIsWithinRoot(candidate, roots);
185
203
  }
186
204
 
187
- function pathErrors(invocations: Invocation[], roots: string[]) {
188
- const errors: string[] = [];
189
- for (const invocation of invocations) {
190
- const candidates = pathCandidates(withoutComments(invocation.input));
191
- for (const candidate of candidates) {
192
- if (escapedPath(candidate, roots))
193
- errors.push(
194
- `${invocation.tool} input escapes transcript workspace roots: ${candidate}`,
195
- );
196
- }
197
- }
198
- return errors;
205
+ const fileOperationTools = new Set([
206
+ "file_chattr",
207
+ "file_delete",
208
+ "file_hash",
209
+ "file_patch",
210
+ "file_read",
211
+ "file_rename",
212
+ "file_write",
213
+ ]);
214
+
215
+ export interface FileOperationPolicy {
216
+ allowAnyPath?: boolean;
217
+ allowTempDirectory?: boolean;
218
+ roots?: string[];
219
+ }
220
+
221
+ interface InvocationPathPolicy {
222
+ allowAnyPath: boolean;
223
+ boundary: string;
224
+ roots: string[];
225
+ }
226
+
227
+ function effectiveFileOperationRoots(
228
+ workspaceRoots: string[],
229
+ policy: FileOperationPolicy,
230
+ ) {
231
+ if (policy.roots) return policy.roots;
232
+ return policy.allowTempDirectory === false
233
+ ? workspaceRoots
234
+ : [...workspaceRoots, os.tmpdir()];
235
+ }
236
+
237
+ function invocationPathPolicy(
238
+ invocation: Invocation,
239
+ workspaceRoots: string[],
240
+ fileOperationPolicy: FileOperationPolicy,
241
+ ): InvocationPathPolicy {
242
+ if (!fileOperationTools.has(invocation.tool))
243
+ return {
244
+ allowAnyPath: false,
245
+ boundary: "transcript workspace roots",
246
+ roots: workspaceRoots,
247
+ };
248
+ return {
249
+ allowAnyPath: fileOperationPolicy.allowAnyPath === true,
250
+ boundary: "transcript file-operation roots",
251
+ roots: effectiveFileOperationRoots(workspaceRoots, fileOperationPolicy),
252
+ };
253
+ }
254
+
255
+ function invocationPathErrors(
256
+ invocation: Invocation,
257
+ policy: InvocationPathPolicy,
258
+ ) {
259
+ if (policy.allowAnyPath) return [];
260
+ return pathCandidates(withoutComments(invocation.input))
261
+ .filter((candidate) => escapedPath(candidate, policy.roots))
262
+ .map(
263
+ (candidate) =>
264
+ `${invocation.tool} input escapes ${policy.boundary}: ${candidate}`,
265
+ );
266
+ }
267
+
268
+ function pathErrors(
269
+ invocations: Invocation[],
270
+ workspaceRoots: string[],
271
+ fileOperationPolicy: FileOperationPolicy,
272
+ ) {
273
+ return invocations.flatMap((invocation) =>
274
+ invocationPathErrors(
275
+ invocation,
276
+ invocationPathPolicy(invocation, workspaceRoots, fileOperationPolicy),
277
+ ),
278
+ );
199
279
  }
200
280
 
201
281
  function isBatch(invocation: Invocation) {
@@ -208,8 +288,10 @@ function isBatch(invocation: Invocation) {
208
288
  "file_delete",
209
289
  "file_rename",
210
290
  ].includes(invocation.tool)
211
- )
212
- return (input.match(/["'][^"']+["']\s*:\s*\{/g) ?? []).length > 1;
291
+ ) {
292
+ keyedPathExpression.lastIndex = 0;
293
+ return expressionValues(input, keyedPathExpression).length > 1;
294
+ }
213
295
  if (invocation.tool === "file_hash")
214
296
  return /filePaths\s*:\s*\[[^\]]+,[^\]]+\]/s.test(input);
215
297
  if (invocation.tool === "file_read")
@@ -247,11 +329,13 @@ function renameResultsCoverInputs(
247
329
  roots: string[] = [],
248
330
  ) {
249
331
  try {
250
- const request = JSON.parse(call.input) as Record<string, unknown>;
332
+ const request = JSON.parse(call.input) as {
333
+ files?: Record<string, unknown>;
334
+ };
251
335
  const result = JSON.parse(output) as { files?: RenameFiles };
252
- if (!result.files) return false;
336
+ if (!request.files || !result.files) return false;
253
337
  const workspaceRoot = roots[0] ?? process.cwd();
254
- return Object.entries(request).every((entry) =>
338
+ return Object.entries(request.files).every((entry) =>
255
339
  renameEntryMatches(result.files as RenameFiles, workspaceRoot, entry),
256
340
  );
257
341
  } catch {
@@ -393,23 +477,52 @@ function hashPrecedesMutation(context: AssertionContext) {
393
477
  );
394
478
  }
395
479
 
396
- function workflowAssertion(context: AssertionContext): boolean | undefined {
480
+ function declaredFileBatchAssertion(
481
+ context: AssertionContext,
482
+ ): boolean | undefined {
397
483
  const { invocations, normalized } = context;
484
+ if (!normalized.includes("declared") || !normalized.includes("files"))
485
+ return undefined;
486
+ const requireBatch = normalized.includes("batch");
487
+ return invocations.some(
488
+ (invocation) =>
489
+ [
490
+ "file_patch",
491
+ "file_write",
492
+ "file_chattr",
493
+ "file_delete",
494
+ "file_rename",
495
+ ].includes(invocation.tool) &&
496
+ hasDeclaredFileBatch(invocation.input) &&
497
+ (!requireBatch || isBatch(invocation)),
498
+ );
499
+ }
500
+
501
+ function previewAssertion(context: AssertionContext): boolean | undefined {
398
502
  const patchCalls = calls(context, "file_patch");
503
+ if (context.normalized.includes("preview true"))
504
+ return patchCalls.some((call) => hasBoolean(call.input, "preview", true));
505
+ if (
506
+ !context.normalized.includes("preview") &&
507
+ !context.normalized.includes("dry run")
508
+ )
509
+ return undefined;
510
+ return (
511
+ calls(context, "run").some(
512
+ (call) => !hasBoolean(call.input, "write", true),
513
+ ) || patchCalls.some((call) => hasBoolean(call.input, "preview", true))
514
+ );
515
+ }
516
+
517
+ function workflowAssertion(context: AssertionContext): boolean | undefined {
518
+ const declaredBatch = declaredFileBatchAssertion(context);
519
+ if (declaredBatch !== undefined) return declaredBatch;
520
+ const { invocations, normalized } = context;
399
521
  if (normalized.includes("batch") || normalized.includes("one keyed"))
400
522
  return invocations.some(isBatch);
401
523
  if (normalized.includes("fresh") && normalized.includes("hash"))
402
524
  return hashPrecedesMutation(context);
403
- if (normalized.includes("preview true"))
404
- return patchCalls.some((call) => hasBoolean(call.input, "preview", true));
405
- if (normalized.includes("preview") || normalized.includes("dry run")) {
406
- return (
407
- calls(context, "run").some(
408
- (call) => !hasBoolean(call.input, "write", true),
409
- ) || patchCalls.some((call) => hasBoolean(call.input, "preview", true))
410
- );
411
- }
412
- return undefined;
525
+ return previewAssertion(context);
413
526
  }
414
527
 
415
528
  function strategyAssertion(context: AssertionContext): boolean | undefined {
@@ -561,11 +674,12 @@ export function verifyEvaluation(
561
674
  invocations: Invocation[],
562
675
  output: string,
563
676
  roots: string[],
677
+ fileOperationPolicy: FileOperationPolicy = {},
564
678
  ) {
565
679
  const errors = [
566
680
  ...toolContractErrors(evaluation, invocations),
567
681
  ...sequenceErrors(evaluation, invocations),
568
- ...pathErrors(invocations, roots),
682
+ ...pathErrors(invocations, roots, fileOperationPolicy),
569
683
  ...fileEvidenceErrors(evaluation, invocations, output),
570
684
  ];
571
685
  if (
@@ -6,9 +6,9 @@ Use this only when the ast-mcp tools are absent, incomplete, or disconnected. Do
6
6
 
7
7
  From the installed skill directory, run the read-only checker:
8
8
 
9
- `bun run scripts/check-install.ts --scope local --target codex --root "$PWD"`
9
+ `bun run scripts/check-install.ts --scope local --target codex`
10
10
 
11
- Replace `codex` with `claude` or `copilot`. For a global installation, pass `--scope global`. For HTTP installations, also pass `--transport http --host <address> --port <number>` so the checker validates the generated URL. 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.
11
+ Replace `codex` with `claude` or `copilot`. Pass `--scope global` for a global installation. Pass the HTTP address and port for HTTP installations. The checker validates guidance, MCP definitions, hooks, skills, and managed assets. It also prints the required install or update command.
12
12
 
13
13
  ## Install from this package checkout
14
14
 
@@ -16,13 +16,13 @@ When the `@mwillbanks/ast-mcp` source checkout is already available, install its
16
16
 
17
17
  `bun install && bun run build`
18
18
 
19
- `bun run bin/ast-mcp.ts install --scope local --target all --root "$PWD"`
19
+ `bun run bin/ast-mcp.ts install --scope local --target all`
20
20
 
21
21
  For one host globally:
22
22
 
23
23
  `bun run bin/ast-mcp.ts install --scope global --target codex`
24
24
 
25
- Targets are `codex`, `claude`, `copilot`, or `all`. Stdio is the default transport. Use `--transport http --host 127.0.0.1 --port 3768` for HTTP host entries and add `--service` only when a macOS LaunchAgent or Linux systemd user unit should be managed.
25
+ Targets are `codex`, `claude`, `copilot`, or `all`. Stdio is the default transport. Use the HTTP options for HTTP host entries. Add `--service` to manage a macOS LaunchAgent or Linux systemd user unit.
26
26
 
27
27
  ## Install from the published package
28
28
 
@@ -36,7 +36,7 @@ When installing with Bun, allow the pinned native installers:
36
36
 
37
37
  `bun pm trust @ast-bro/cli dprint`
38
38
 
39
- `./node_modules/.bin/ast-mcp install --scope local --target all --root "$PWD"`
39
+ `./node_modules/.bin/ast-mcp install --scope local --target all`
40
40
 
41
41
  For a global host surface, use the package manager's persistent global install:
42
42
 
@@ -44,18 +44,18 @@ For a global host surface, use the package manager's persistent global install:
44
44
  npm install --global @mwillbanks/ast-mcp
45
45
  ```
46
46
 
47
- Then run `ast-mcp install --scope global --target codex`. Yarn 2+ should use a project-local installation because it does not provide the Yarn Classic global workflow. Bun blocks transitive lifecycle scripts by default; explicitly trusting `@ast-bro/cli` and `dprint` runs their pinned native installers instead of leaving stale or missing cache paths. If another manager blocks dependency build scripts, approve those two packages through that manager.
47
+ Then run `ast-mcp install --scope global --target codex`. Use a project-local installation with Yarn 2+. Yarn 2+ does not provide the Yarn Classic global workflow. Bun blocks transitive lifecycle scripts by default. Trust `@ast-bro/cli` and `dprint` to run their pinned native installers. Approve those packages when another manager blocks dependency build scripts.
48
48
 
49
- Do not use an ephemeral package executor for host installation because its temporary package path can disappear after configuration is written. The runtime checks ancestor `node_modules/.bin` directories, package metadata, Bun/pnpm/npm/Yarn global bins, and finally `PATH`. The installer records the stable installed CLI and uses its `mcp` and `hook` subcommands. For a local installation, run `./node_modules/.bin/ast-mcp update` to refresh managed surfaces and `./node_modules/.bin/ast-mcp uninstall` to remove them; global installations use `ast-mcp update` and `ast-mcp uninstall`.
49
+ Invoke the executable that must remain available. The installer records that path in MCP, hook, service, and manual-start output. The runtime checks package binaries, package metadata, global bins, and `PATH`. The installer uses the stable CLI and its `mcp` and `hook` subcommands. Run the local binary for local updates and removal. Run `ast-mcp update` or `ast-mcp uninstall` for global installations.
50
50
 
51
- The pinned `@ast-bro/cli@3.0.0` package has a precompiled binary only for macOS Apple Silicon. On Linux or macOS Intel, install it with `cargo install ast-bro --version 3.0.0 --locked`, set `AST_BRO_BINARY="$HOME/.cargo/bin/ast-bro"`, and persist that export in `~/.profile` or `~/.zprofile`. On Windows, use the same Cargo command and persist `AST_BRO_BINARY` as `$HOME\.cargo\bin\ast-bro.exe` in the user environment. GUI-launched hosts must inherit that variable from their launcher. The ast-mcp installer verifies the binary before modifying host configuration and returns these commands when manual setup is required.
51
+ The pinned package provides a precompiled binary for macOS Apple Silicon. Install ast-bro with Cargo on Linux or macOS Intel. Set `AST_BRO_BINARY` to the installed path and persist the export. Use the Cargo executable path on Windows. Ensure GUI-launched hosts inherit the variable. The installer verifies the binary before changing host configuration. It returns setup commands when required.
52
52
 
53
53
  ## Activate and verify
54
54
 
55
- 1. Run `ast-mcp config validate --root "$PWD"` before reconnecting. Use `ast-mcp config show --root "$PWD"` when the effective project, global, environment, or default source is unclear.
56
- 2. 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.
55
+ 1. Run `ast-mcp config validate` before reconnecting. Use `ast-mcp config show` when the effective source is unclear. `--root` remains deprecated for one release.
56
+ 2. Restart or reconnect MCP servers in the host. A skill file cannot make MCP tools callable. Send `SIGHUP` to request graceful cleanup and restart.
57
57
  3. Confirm `file_hash`, `file_read`, `file_write`, and `file_patch` are present.
58
58
  4. Confirm direct intelligence tools such as `digest`, `map`, `show`, `context`, and `impact` are present; there is no proxy tool.
59
- 5. 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.
59
+ 5. Verify that read and mutation tools accept their current batch fields. Reject dictionary-only mutation schemas and the legacy whole-file read schema.
60
60
  6. Rerun `check-install.ts` if the tool list remains incomplete.
61
- 7. 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.
61
+ 7. Run `bun run tools:check` from the package checkout when startup fails. Report the missing dependency or startup error. Preserve the write boundary.
@@ -4,14 +4,15 @@ The server distinguishes AST inspection from structural rewrite support. AST-cap
4
4
 
5
5
  ## Route selection
6
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 `patchStrategy`, ordered `astRules` or `aiderBlocks` arrays, optional `preview`, and normally one fresh `expectedSha256`.
10
- 4. Use one path-keyed `file_write` object for new files or existing non-structurally-rewritable files; existing replacements normally receive 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_rename` with a fresh byte hash for root-bounded moves; preflight every source and destination, reject duplicate destinations, lock all endpoints, use no-replace moves, and roll back prior moves when a later move fails. The contract is recoverable on ordinary failures, not crash-atomic. 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. `safety.require_hash = false` makes hashes optional for patch, existing write, rename, and delete, but any supplied hash remains enforced.
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`.
7
+ 1. Call `file_capabilities` when the route is uncertain. It is the authoritative contract shared by `file_read`, `run`, and `file_patch`, and reports intrinsic support separately from configuration-filtered methods.
8
+ 2. Choose `file_read.mode` explicitly when intent matters: `ast` returns a source map/requested symbols or RFC 6901-selected structured-document values, `text` returns a bounded slice, and `auto` prefers AST when available. Text remains selectable for AST-capable files.
9
+ 3. Choose `file_patch.patchStrategy` per target. `ast` and `aider_block` are both valid for parseable source when reported by `file_capabilities`; prefer AST for semantic or repeated structural changes and Aider for a small, exact, uniquely anchored text replacement. Configuration may narrow either method but never silently changes the agent's selection.
10
+ 4. Preview every ordered AST rule with `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. Aider patches also support the guarded preview receipt workflow.
11
+ 5. Use one `file_patch({ files: { ... } })` object for one or more files. Each path value declares exactly one `patchStrategy`, the corresponding ordered `astRules` or `aiderBlocks`, optional `preview`, and normally one fresh `expectedSha256`.
12
+ 6. Use one `file_write({ files: { ... } })` object for new files or explicit whole-file replacement where permitted. Use the shared `chattr` object for chmod/chown metadata. The complete batch policy preflight finishes before filesystem preparation.
13
+ 7. Use `file_rename`, `file_chattr`, and `file_delete` for their dedicated operations. Rename requires source `delete` and destination `write`; guarded mutations honor `safety.require_hash` and supplied hashes are always enforced.
14
+ 8. 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.
15
+ 9. Use direct `run` with `rewrite` and `write: true` only for an intentionally bounded lower-level rewrite; normal agent mutations belong to `file_patch`.
15
16
 
16
17
  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
 
@@ -21,19 +22,19 @@ MCP transport requests may contain a JSON-RPC array of requests and notification
21
22
  - Use `$NODE` for one node and `$$NODES` for zero or more nodes.
22
23
  - Preview with the same language, explicit paths, and optional glob.
23
24
  - 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
+ - ast-bro 4.0.0 changes only the first match in each file; narrow ambiguous patterns rather than assuming replace-all behavior.
25
26
  - Split declarations, calls, and type references into separate rules.
26
27
 
27
28
  ## Aider block discipline
28
29
 
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
+ Version 2 enables exact, whitespace-normalized, relative-indentation, and diff-match-patch matching by default. Repositories may narrow `[files.patch].aider_matchers` when they intentionally want a stricter matching policy. Use `file_read` with `mode: "text"` to identify the smallest unique surrounding block, expand the slice and block on ambiguity, and select Aider only when the capability result permits it. Matcher ambiguity or a disabled fallback is a safe stop, never a reason to broaden the patch silently.
30
31
 
31
32
  ## Rejections
32
33
 
33
34
  - `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.
35
+ - `read_mode_unavailable` or `patch_strategy_unavailable`: call `file_capabilities`, then make a supported explicit selection; do not retry a different method blindly.
36
+ - `matched N nodes; expected M`: inspect the returned bounded locations and narrow the rule.
37
+ - `first match per file`: narrow `file_patch` to one structural node or use a bounded direct run only when the lower-level rewrite is intentional.
37
38
  - capped preview or read: narrow paths, glob, pattern, line ranges, or byte caps.
38
39
  - formatter preflight failure: the selected external formatter or dprint fallback does not support the target; no write occurs. Formatting is skipped only when `[formatting].enabled = false`.
39
- - path or symlink rejection: use a real path under an effective workspace root. Final symlinks are followed only when `safety.follow_symlinks = true`, and their resolved targets must remain root-bounded.
40
+ - path or symlink rejection: use a real path permitted by the effective host baseline and top-level `[[paths]]` rules. Version 2 grants no implicit OS-temporary access; add a narrow explicit path rule when it is required. Legacy `safety.allow_temp_directory`, `safety.allow_any_path`, and `safety.follow_symlinks` apply only to version 1. In version 2, both a link and its resolved target must be authorized and the winning rule must set `follow_symlinks = true`.
@@ -5,14 +5,18 @@ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy
5
5
  ## File boundary
6
6
 
7
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 atomic commit.
12
- - `file_rename({ "/repo/a.txt": { destination, expectedSha256? } })`: renames multiple regular files in one root-bounded batch, locks every source and destination, rejects cross-root and duplicate/existing destinations, uses no-replace moves, rolls back prior moves when a later move fails, and reports a per-file result. Crash-atomic recovery is not guaranteed.
13
- - `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.
8
+ - `file_capabilities({ filePaths })`: batch up to 50 paths and return file kind, language, parse health, configuration generation, intrinsic read/patch/search support, and effective methods after configuration filtering.
9
+ - `file_read({ files })`: batch up to 50 files. Each request accepts `mode: "auto" | "ast" | "text"`, optional source `symbols`, structured-document RFC 6901 `selectors`, and `language`, plus `range: { start, end }`; the numeric zero-based, end-exclusive `lines: [start, end]` tuple remains a permanent compatibility alias. AST mode returns a source map/requested symbols or selected JSON, JSONC, TOML, or YAML values; text mode returns a bounded slice, and auto prefers AST when available.
10
+ - `file_chattr({ files: { "/repo/a.txt": { chattr, expectedSha256? } } })`: applies the shared `chattr` contract (`chmod?`, same-owner `chown?`) under deterministic locks and reports the effective attributes.
11
+ - `file_write({ files: { "/repo/a.txt": { content, chattr? }, "/repo/b.txt": { content, expectedSha256?, chattr? } } })`: create or replace multiple files in one declared batch; existing replacements remain limited to non-AST-rewritable files. The complete batch policy preflight runs first. For a new nested target, in-place formatter staging may transiently create, revalidate, and remove missing parents before the guarded commit recreates them; the live target is not written before commit.
12
+ - `file_patch({ files: { "/repo/src/a.ts": { expectedSha256?, patchStrategy: "ast" | "aider_block", astRules?: [...], aiderBlocks?: [...], chattr?, preview? } } })`: patch one or more files in one declared batch with an explicit agent-selected strategy supported by `file_capabilities`. A preview returns an opaque one-use `previewReceipt`; commit with `{ previewReceipt }` to reuse the reviewed formatted candidate after session, policy, generation, and source-hash rechecks.
13
+ - `file_rename({ files: { "/repo/a.txt": { destination, expectedSha256? } } })`: renames multiple regular files in one file-operation-root-bounded batch, locks every source and destination, rejects cross-root and duplicate/existing destinations, uses no-replace moves, rolls back prior moves when a later move fails, and reports a per-file result. Crash-atomic recovery is not guaranteed.
14
+ - `file_delete({ files: { "/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 allowed operation root.
14
15
  - `expectedSha256` is required by the secure default for patch, existing-file write, rename, and delete. `safety.require_hash = false` makes it optional; supplied hashes are always verified.
15
- - 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.
16
+ - Mutation tools use a declared `files` input object, preflight the complete batch, and return a `files` result map. Version 2 grants no implicit temporary access; use explicit top-level `[[paths]]` rules and approval policies. MCP transport also accepts JSON-RPC request/notification arrays and returns one response per request ID.
17
+ - `config_status({})` returns redacted effective configuration, source provenance, generation, health, and formatter selection.
18
+ - `policy_check({ checks })` explains batched read/write/delete decisions without side effects.
19
+ - `document_query({ filePath, selectors })` returns bounded RFC 6901-selected JSON, JSONC, TOML, or YAML values plus the whole-file hash.
16
20
 
17
21
  ## Shape and source
18
22
 
@@ -36,13 +40,15 @@ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy
36
40
  - dry-run per-file diffs when `rewrite` is present and `write` is false or omitted;
37
41
  - disk rewrite when both `rewrite` and `write: true` are present.
38
42
 
39
- 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.
43
+ For pinned ast-bro 4.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.
40
44
 
41
45
  - `squeeze({ path, start?, end?, raw?, json? })`: compression for repetitive logs/text, not source code.
42
46
 
43
47
  ## Common sequences
44
48
 
45
49
  - Rename: `impact` → `show`/`context` → `run` search → `run` dry diff → bounded `run.write` → AST absence check.
46
- - Atomic single-file edit: AST inspection → `run` search → `file_hash` → `file_patch` with one expected match → AST verification.
47
- - Unsupported text edit: bounded batched `file_read` → `file_hash` → unique Aider block → bounded `file_read` verification.
50
+ - Atomic single-file edit: `file_capabilities` when uncertain → select AST or Aider → preview → `file_hash` → `file_patch` → matching AST or text verification.
51
+ - Exact text edit: batched `file_read` with `mode: "text"` → `file_hash` → unique Aider block → bounded text verification.
52
+ - Structured manifest: `document_query` with multiple selectors → targeted edit workflow; do not request the whole manifest.
53
+ - Uncertain mutation policy: `config_status` → batched `policy_check` → preview → hash → mutation.
48
54
  - Refactor module: `surface` → `deps` + `reverse_deps` → `impact` → edits → `cycles`.
@@ -96,13 +96,8 @@ const instructionsBegin = "<!-- ast-mcp:begin -->";
96
96
  const instructionsEnd = "<!-- ast-mcp:end -->";
97
97
 
98
98
  async function astMcpEntry(entry: unknown): Promise<boolean> {
99
- if (entry === "./node_modules/.bin/ast-mcp") return true;
100
- if (typeof entry !== "string" || path.basename(entry) !== "ast-mcp")
101
- return false;
102
- const bin = path.dirname(entry);
103
- return (
104
- path.basename(bin) === "bin" && path.basename(path.dirname(bin)) === ".bun"
105
- );
99
+ if (typeof entry !== "string") return false;
100
+ return ["ast-mcp", "ast-mcp.js", "ast-mcp.ts"].includes(path.basename(entry));
106
101
  }
107
102
 
108
103
  async function expectedReference(
@@ -209,10 +204,8 @@ function entryTypeCurrent(
209
204
  return type !== "local" || Array.isArray(entry.tools);
210
205
  }
211
206
 
212
- function entryRootCurrent(entry: McpEntry, root: string | undefined) {
213
- return root
214
- ? entry.env?.AST_MCP_PROJECT_ROOT === root
215
- : Object.keys(entry.env ?? {}).length === 0;
207
+ function entryRootCurrent(entry: McpEntry, _root: string | undefined) {
208
+ return Object.keys(entry.env ?? {}).length === 0;
216
209
  }
217
210
 
218
211
  function stdioMetadataCurrent(
@@ -255,7 +248,7 @@ function codexHttpMcpCurrent(block: string, url: string | undefined) {
255
248
  !block.includes("command =")
256
249
  );
257
250
  }
258
- async function codexStdioMcpCurrent(block: string, root: string | undefined) {
251
+ async function codexStdioMcpCurrent(block: string, _root: string | undefined) {
259
252
  const command = block.match(/command = (".*")/);
260
253
  if (
261
254
  !block.includes("[mcp_servers.ast-mcp]") ||
@@ -264,9 +257,7 @@ async function codexStdioMcpCurrent(block: string, root: string | undefined) {
264
257
  !(await astMcpEntry(JSON.parse(command[1])))
265
258
  )
266
259
  return false;
267
- return root
268
- ? block.includes(`AST_MCP_PROJECT_ROOT = ${JSON.stringify(root)}`)
269
- : !block.includes("AST_MCP_PROJECT_ROOT");
260
+ return !block.includes("AST_MCP_PROJECT_ROOT") && !block.includes("env =");
270
261
  }
271
262
  async function codexMcpCurrent(
272
263
  file: string,
@@ -428,8 +419,8 @@ function installOperation(checks: InstallChecks) {
428
419
  ? ("update" as const)
429
420
  : ("install" as const);
430
421
  }
431
- function commandSuffix(options: CheckOptions, global: boolean) {
432
- return `--scope ${options.scope} --target ${options.target}${global ? "" : ` --root ${JSON.stringify(options.root)}`}${options.transport === "http" ? ` --transport http --host ${JSON.stringify(options.host)} --port ${options.port}` : ""}${options.service ? " --service" : ""}`;
422
+ function commandSuffix(options: CheckOptions, _global: boolean) {
423
+ return `--scope ${options.scope} --target ${options.target}${options.transport === "http" ? ` --transport http --host ${JSON.stringify(options.host)} --port ${options.port}` : ""}${options.service ? " --service" : ""}`;
433
424
  }
434
425
  function installCommands(options: CheckOptions, global: boolean) {
435
426
  const suffix = commandSuffix(options, global);
@@ -1,9 +0,0 @@
1
- import { astCapable } from "./capability";
2
-
3
- export async function astRewritable(
4
- filePath: string,
5
- language?: string,
6
- ): Promise<boolean> {
7
- if (language === "markdown") return false;
8
- return astCapable(filePath, language);
9
- }