@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
@@ -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, managed services, and exact ast-bro 4.2.0. It also detects stable package-manager aliases and duplicate handlers. It rejects package-internal or stale commands. It prints an exact install, update, or dependency-repair 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
+ Local MCP, hook, service, and repair surfaces always use `./node_modules/.bin/ast-mcp`. Global surfaces use a discovered Bun, npm, pnpm, or Yarn global-bin alias and reject package-internal paths. 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 every mutation tool accepts a declared `files` object containing path-keyed per-file operations; dictionary-only top-level mutation schemas and the legacy whole-file `file_read({ filePath })` schema are 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 `file_patch({ files: { ... } })` object for one or more files. The declared `files` property contains path keys; each value has one `patchStrategy`, ordered `astRules` or `aiderBlocks` arrays, optional `preview`, and normally one fresh `expectedSha256`.
10
- 4. Use one `file_write({ files: { ... } })` 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({ files: { ... } })` with a fresh byte hash for file-operation-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 dry run, use the same keyed `file_patch` entry with `preview: true`. Preview does not format; commit, including `previewReceipt` commit, formats. 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.2.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 or the OS temporary directory. Set `safety.allow_temp_directory = false` to remove the default temporary-directory allowance. `safety.allow_any_path = true` explicitly disables path protection for file tools. Final symlinks are followed only when `safety.follow_symlinks = true`, and their resolved targets must remain inside an allowed file-operation root unless unrestricted mode is enabled.
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,20 +5,27 @@ 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.
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.
9
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.
10
- - `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. Missing parents are created only after the write attempt returns `ENOENT`, then the path is revalidated.
11
- - `file_patch({ files: { "/repo/src/a.ts": { expectedSha256?, patchStrategy: "ast", astRules: [...], chattr? } } })`: patch one or more files in one declared batch. Use ordered `astRules` or `aiderBlocks`; every path has one atomic commit.
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` for the unformatted strategy candidate and does not run formatters; commit with `{ previewReceipt }` to format that candidate and reuse it after session, policy, generation, and source-hash rechecks.
12
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.
13
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
- - Mutation tools use a declared `files` input object and return a `files` result map. The OS temporary directory is allowed by default; configure `safety.allow_temp_directory = false` to disable it or `safety.allow_any_path = true` for explicit unrestricted file access. 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. `workspace.worktrees` reports `include`, `request`, or `ignore`; discovered linked worktree paths are listed as paths only.
18
+ - Agents working in a git worktree should pass absolute paths. Start the MCP against the config-bearing checkout; the server loads `ast-mcp.toml` from that checkout and authorizes linked worktrees of the same repository when `workspace.worktrees` is `include` or `request`. A toml-less worktree is not a different project root.
19
+ - `policy_check({ checks })` explains batched read/write/delete decisions without side effects.
20
+ - `document_query({ filePath, selectors })` returns bounded RFC 6901-selected JSON, JSONC, TOML, or YAML values plus the whole-file hash.
21
+ - `config_core({ target?, workspace?, safety?, files?, formatting?, http?, dependencies?, mcp? })` updates grouped version 2 core sections without rewriting the file or changing `[[paths]]`. Default `target` is `project`. Host approval is required unless `mcp.configuration.require_approval = false`; `[mcp.configuration]` changes always require approval. Disabled when `mcp.configuration.enabled = false`.
22
+ - `config_paths({ target?, operations })` adds, updates, or removes `[[paths]]` rules in one batch by `id`. Does not change core sections. Same approval and enablement contract as `config_core`.
16
23
 
17
24
  ## Shape and source
18
25
 
19
26
  - `digest({ paths, include_private?, include_fields?, max_members?, json? })`: compact map of unfamiliar directories.
20
27
  - `map({ paths, glob?, no_private?, no_fields?, no_docs?, no_attrs?, no_lines?, json? })`: signatures, parse error counts, and line ranges.
21
- - `show({ path, symbols, json? })`: source for known symbols.
28
+ - `show({ path, symbols, limit?, json? })`: v2 source extraction for files, directories, and glob targets. JSON uses `ast-bro.show.v2` with `files[]`, `files_scanned`, `total`, `shown`, `truncated`, coverage metadata, truncation details, and Markdown frontmatter symbols. Glob fixed prefixes and every match remain workspace-policy checked; authorized zero-match globs are valid.
22
29
  - `surface({ path, tree?, include_chain?, include_private?, max_depth?, lang?, json? })`: public API and re-exports.
23
30
 
24
31
  ## Discovery, dependencies, and calls
@@ -36,13 +43,16 @@ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy
36
43
  - dry-run per-file diffs when `rewrite` is present and `write` is false or omitted;
37
44
  - disk rewrite when both `rewrite` and `write: true` are present.
38
45
 
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.
46
+ For pinned ast-bro 4.2.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
47
 
41
48
  - `squeeze({ path, start?, end?, raw?, json? })`: compression for repetitive logs/text, not source code.
42
49
 
43
50
  ## Common sequences
44
51
 
45
52
  - 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.
53
+ - Atomic single-file edit: `file_capabilities` when uncertain → select AST or Aider → preview → `file_hash` → `file_patch` → matching AST or text verification.
54
+ - Exact text edit: batched `file_read` with `mode: "text"` → `file_hash` → unique Aider block → bounded text verification.
55
+ - Structured manifest: `document_query` with multiple selectors → targeted edit workflow; do not request the whole manifest.
56
+ - Uncertain mutation policy: `config_status` → batched `policy_check` → preview → hash → mutation.
57
+ - Configuration: `config_status` → grouped `config_core` and/or batched `config_paths` (never a whole-file rewrite) → `config_status` to confirm the new generation.
48
58
  - Refactor module: `surface` → `deps` + `reverse_deps` → `impact` → edits → `cycles`.
@@ -0,0 +1,112 @@
1
+ import { accessSync, constants } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export interface GlobalBinaryResolutionOptions {
6
+ globalBinDirectories?: string[];
7
+ home?: string;
8
+ platform?: NodeJS.Platform;
9
+ }
10
+
11
+ export function executableNames(name: string, platform: NodeJS.Platform) {
12
+ if (platform !== "win32") return [name];
13
+ const extensions = (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM")
14
+ .split(";")
15
+ .filter(Boolean);
16
+ return [name, ...extensions.map((extension) => `${name}${extension}`)];
17
+ }
18
+
19
+ export function isExecutable(
20
+ file: string,
21
+ platform: NodeJS.Platform = process.platform,
22
+ ) {
23
+ try {
24
+ accessSync(
25
+ file,
26
+ platform === "win32" ? constants.F_OK : constants.F_OK | constants.X_OK,
27
+ );
28
+ return true;
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ function commandOutput(command: string, args: string[]) {
35
+ try {
36
+ const result = Bun.spawnSync([command, ...args], {
37
+ stderr: "ignore",
38
+ stdout: "pipe",
39
+ });
40
+ return result.exitCode === 0 ? result.stdout.toString().trim() : "";
41
+ } catch {
42
+ return "";
43
+ }
44
+ }
45
+
46
+ export function globalBinDirectories(
47
+ binaryName: string,
48
+ platform: NodeJS.Platform,
49
+ home = os.homedir(),
50
+ ) {
51
+ const directories = new Set<string>();
52
+ const add = (value: string | undefined) => {
53
+ if (value) directories.add(path.resolve(value));
54
+ };
55
+ const yarnBinary = commandOutput("yarn", ["bin", binaryName]);
56
+ if (yarnBinary) add(path.dirname(yarnBinary));
57
+ add(process.env.BUN_INSTALL && path.join(process.env.BUN_INSTALL, "bin"));
58
+ add(process.env.PNPM_HOME);
59
+ add(
60
+ process.env.npm_config_prefix &&
61
+ (platform === "win32"
62
+ ? process.env.npm_config_prefix
63
+ : path.join(process.env.npm_config_prefix, "bin")),
64
+ );
65
+ add(path.join(home, ".bun/bin"));
66
+ add(path.join(home, ".bun/install/global/node_modules/.bin"));
67
+ add(commandOutput("bun", ["pm", "bin", "-g"]));
68
+ add(commandOutput("pnpm", ["bin", "-g"]));
69
+ add(commandOutput("yarn", ["global", "bin"]));
70
+ const npmPrefix = commandOutput("npm", ["prefix", "-g"]);
71
+ add(
72
+ npmPrefix &&
73
+ (platform === "win32" ? npmPrefix : path.join(npmPrefix, "bin")),
74
+ );
75
+ return [...directories];
76
+ }
77
+
78
+ export function directoryBinaryCandidates(
79
+ directories: string[],
80
+ names: string[],
81
+ ) {
82
+ const candidates: string[] = [];
83
+ for (const directory of directories) {
84
+ if (!directory) continue;
85
+ for (const name of names) candidates.push(path.join(directory, name));
86
+ }
87
+ return candidates;
88
+ }
89
+
90
+ export function executableCandidate(
91
+ candidates: string[],
92
+ platform: NodeJS.Platform,
93
+ ) {
94
+ return candidates.find((candidate) => isExecutable(candidate, platform));
95
+ }
96
+
97
+ export function resolveGlobalBinaryAlias(
98
+ binaryName: string,
99
+ options: GlobalBinaryResolutionOptions = {},
100
+ ) {
101
+ const platform = options.platform ?? process.platform;
102
+ const directories =
103
+ options.globalBinDirectories ??
104
+ globalBinDirectories(binaryName, platform, options.home);
105
+ return executableCandidate(
106
+ directoryBinaryCandidates(
107
+ directories,
108
+ executableNames(binaryName, platform),
109
+ ),
110
+ platform,
111
+ );
112
+ }