@mwillbanks/ast-mcp 0.3.0 → 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 (36) hide show
  1. package/README.md +5 -5
  2. package/dist/ast-mcp.js +172 -156
  3. package/dist/ast-mcp.js.map +35 -31
  4. package/package.json +11 -11
  5. package/src/ast-bro/client.ts +12 -6
  6. package/src/ast-bro/result.ts +79 -0
  7. package/src/ast-bro/tools.json +7 -2
  8. package/src/config-edit.ts +236 -0
  9. package/src/config-migrate.ts +3 -20
  10. package/src/config-registry.ts +8 -0
  11. package/src/config-schema-common.ts +8 -1
  12. package/src/config-v2-schema.ts +12 -0
  13. package/src/config.ts +194 -39
  14. package/src/helpers/config.ts +9 -3
  15. package/src/installer.ts +61 -14
  16. package/src/patch/engine.ts +36 -17
  17. package/src/runtime/config-write.ts +327 -0
  18. package/src/runtime/dependencies.ts +14 -78
  19. package/src/runtime/file-read.ts +4 -13
  20. package/src/runtime/format.ts +27 -5
  21. package/src/runtime/git-worktrees.ts +179 -0
  22. package/src/runtime/path-policy.ts +131 -45
  23. package/src/runtime/path-utils.ts +40 -0
  24. package/src/runtime/paths.ts +29 -3
  25. package/src/tools/ast-bro.ts +106 -8
  26. package/src/tools/configuration.ts +218 -0
  27. package/src/tools/files.ts +1 -1
  28. package/templates/AGENTS.md +5 -1
  29. package/templates/skills/ast-mcp/SKILL.md +30 -1
  30. package/templates/skills/ast-mcp/evals/evals.json +98 -0
  31. package/templates/skills/ast-mcp/references/installation.md +2 -2
  32. package/templates/skills/ast-mcp/references/patch-state-machine.md +2 -2
  33. package/templates/skills/ast-mcp/references/tool-catalog.md +8 -4
  34. package/templates/skills/ast-mcp/scripts/binary-resolution.ts +112 -0
  35. package/templates/skills/ast-mcp/scripts/check-install.ts +162 -39
  36. package/templates/skills/ast-mcp/scripts/managed-hook.ts +34 -2
@@ -9,20 +9,23 @@ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy
9
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
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
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.
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.
13
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
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.
15
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.
16
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.
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.
18
19
  - `policy_check({ checks })` explains batched read/write/delete decisions without side effects.
19
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`.
20
23
 
21
24
  ## Shape and source
22
25
 
23
26
  - `digest({ paths, include_private?, include_fields?, max_members?, json? })`: compact map of unfamiliar directories.
24
27
  - `map({ paths, glob?, no_private?, no_fields?, no_docs?, no_attrs?, no_lines?, json? })`: signatures, parse error counts, and line ranges.
25
- - `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.
26
29
  - `surface({ path, tree?, include_chain?, include_private?, max_depth?, lang?, json? })`: public API and re-exports.
27
30
 
28
31
  ## Discovery, dependencies, and calls
@@ -40,7 +43,7 @@ All tools are exposed directly by ast-mcp. Do not wrap ast-bro calls in a proxy
40
43
  - dry-run per-file diffs when `rewrite` is present and `write` is false or omitted;
41
44
  - disk rewrite when both `rewrite` and `write: true` are present.
42
45
 
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.
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.
44
47
 
45
48
  - `squeeze({ path, start?, end?, raw?, json? })`: compression for repetitive logs/text, not source code.
46
49
 
@@ -51,4 +54,5 @@ For pinned ast-bro 4.0.0, write mode changes the first match per file, caps a ca
51
54
  - Exact text edit: batched `file_read` with `mode: "text"` → `file_hash` → unique Aider block → bounded text verification.
52
55
  - Structured manifest: `document_query` with multiple selectors → targeted edit workflow; do not request the whole manifest.
53
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.
54
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
+ }
@@ -2,6 +2,15 @@
2
2
  import { readFile } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import {
6
+ directoryBinaryCandidates,
7
+ executableCandidate,
8
+ executableNames,
9
+ globalBinDirectories,
10
+ isExecutable,
11
+ resolveGlobalBinaryAlias,
12
+ } from "./binary-resolution";
13
+ import { managedAstMcpHookEntry } from "./managed-hook";
5
14
 
6
15
  type Scope = "local" | "global";
7
16
  type Target = "codex" | "claude" | "copilot";
@@ -94,10 +103,75 @@ function parse(args: string[]): CheckOptions {
94
103
 
95
104
  const instructionsBegin = "<!-- ast-mcp:begin -->";
96
105
  const instructionsEnd = "<!-- ast-mcp:end -->";
106
+ const astBroVersion = "4.2.0";
97
107
 
98
- async function astMcpEntry(entry: unknown): Promise<boolean> {
108
+ async function astMcpEntry(
109
+ entry: unknown,
110
+ root?: string,
111
+ home = os.homedir(),
112
+ ): Promise<boolean> {
99
113
  if (typeof entry !== "string") return false;
100
- return ["ast-mcp", "ast-mcp.js", "ast-mcp.ts"].includes(path.basename(entry));
114
+ const normalized = entry.replaceAll("\\", "/");
115
+ if (root) return normalized === "./node_modules/.bin/ast-mcp";
116
+ if (
117
+ ![
118
+ "ast-mcp",
119
+ "ast-mcp.bat",
120
+ "ast-mcp.cmd",
121
+ "ast-mcp.com",
122
+ "ast-mcp.exe",
123
+ ].includes(path.basename(normalized).toLowerCase())
124
+ )
125
+ return false;
126
+ const directory = path.dirname(path.resolve(entry));
127
+ const recognized = globalBinDirectories(
128
+ "ast-mcp",
129
+ process.platform,
130
+ home,
131
+ ).some((candidate) => path.resolve(candidate) === directory);
132
+ return recognized && isExecutable(entry);
133
+ }
134
+
135
+ async function astBroVersionCurrent(binary: string) {
136
+ if (!isExecutable(binary)) return false;
137
+ const result = Bun.spawnSync([binary, "--version"], {
138
+ stderr: "ignore",
139
+ stdout: "pipe",
140
+ });
141
+ return (
142
+ result.exitCode === 0 &&
143
+ result.stdout.toString().trim() === `ast-bro ${astBroVersion}`
144
+ );
145
+ }
146
+
147
+ async function astBroCurrent(options: CheckOptions, home: string) {
148
+ if (process.env.AST_BRO_BINARY)
149
+ return astBroVersionCurrent(process.env.AST_BRO_BINARY);
150
+ const localBinDirectory = path.join(options.root, "node_modules/.bin");
151
+ if (options.scope === "local") {
152
+ const projectBinary = executableCandidate(
153
+ directoryBinaryCandidates(
154
+ [localBinDirectory],
155
+ executableNames("ast-bro", process.platform),
156
+ ),
157
+ process.platform,
158
+ );
159
+ return projectBinary ? astBroVersionCurrent(projectBinary) : false;
160
+ }
161
+ const bundled = path.resolve(
162
+ import.meta.dir,
163
+ "../../../../node_modules/.bin/ast-bro",
164
+ );
165
+ if (isExecutable(bundled)) return astBroVersionCurrent(bundled);
166
+ const globalBinary = resolveGlobalBinaryAlias("ast-bro", {
167
+ globalBinDirectories: globalBinDirectories(
168
+ "ast-bro",
169
+ process.platform,
170
+ home,
171
+ ),
172
+ platform: process.platform,
173
+ });
174
+ return globalBinary ? astBroVersionCurrent(globalBinary) : false;
101
175
  }
102
176
 
103
177
  async function expectedReference(
@@ -141,8 +215,8 @@ async function skillCurrent(file: string) {
141
215
  async function hookCurrent(
142
216
  configFile: string,
143
217
  event: "PreToolUse" | "preToolUse",
144
- _scriptFile: string,
145
- _commandPath?: string,
218
+ root: string | undefined,
219
+ home: string,
146
220
  ) {
147
221
  const config = JSON.parse(
148
222
  await readFile(configFile, "utf8").catch(() => "{}"),
@@ -156,15 +230,21 @@ async function hookCurrent(
156
230
  : entries.flatMap((item: { hooks?: Array<{ command?: unknown }> }) =>
157
231
  (item.hooks ?? []).map((child) => child.command),
158
232
  );
159
- for (const command of commands) {
160
- if (typeof command !== "string") continue;
161
- const match = command.match(/^(.+) hook$/);
162
- if (!match) continue;
163
- try {
164
- if (await astMcpEntry(JSON.parse(match[1]))) return true;
165
- } catch {}
166
- }
167
- return false;
233
+ const managed = commands
234
+ .map((command) => ({
235
+ command,
236
+ entry: managedAstMcpHookEntry(command),
237
+ }))
238
+ .filter(
239
+ (item): item is { command: string; entry: string } =>
240
+ typeof item.command === "string" && typeof item.entry === "string",
241
+ );
242
+ if (managed.length !== 1) return false;
243
+ const [{ command, entry }] = managed;
244
+ return (
245
+ command === `${JSON.stringify(entry)} hook` &&
246
+ (await astMcpEntry(entry, root, home))
247
+ );
168
248
  }
169
249
 
170
250
  type McpEntry = {
@@ -186,9 +266,13 @@ function httpJsonMcpCurrent(
186
266
  (type !== "local" || Array.isArray(entry.tools))
187
267
  );
188
268
  }
189
- async function stdioCommandCurrent(entry: McpEntry | undefined) {
269
+ async function stdioCommandCurrent(
270
+ entry: McpEntry | undefined,
271
+ root?: string,
272
+ home = os.homedir(),
273
+ ) {
190
274
  return (
191
- (await astMcpEntry(entry?.command)) &&
275
+ (await astMcpEntry(entry?.command, root, home)) &&
192
276
  Array.isArray(entry?.args) &&
193
277
  entry.args.length === 1 &&
194
278
  entry.args[0] === "mcp"
@@ -220,9 +304,10 @@ async function stdioJsonMcpCurrent(
220
304
  entry: McpEntry | undefined,
221
305
  root: string | undefined,
222
306
  type: "local" | "stdio" | undefined,
307
+ home: string,
223
308
  ) {
224
309
  return (
225
- (await stdioCommandCurrent(entry)) &&
310
+ (await stdioCommandCurrent(entry, root, home)) &&
226
311
  stdioMetadataCurrent(entry as McpEntry, root, type)
227
312
  );
228
313
  }
@@ -233,12 +318,13 @@ async function jsonMcpCurrent(
233
318
  type?: "local" | "stdio",
234
319
  transport: Transport = "stdio",
235
320
  url?: string,
321
+ home = os.homedir(),
236
322
  ) {
237
323
  const value = JSON.parse(await readFile(file, "utf8").catch(() => "{}"));
238
324
  const entry: McpEntry | undefined = value[section]?.["ast-mcp"];
239
325
  return transport === "http"
240
326
  ? httpJsonMcpCurrent(entry, type, url)
241
- : stdioJsonMcpCurrent(entry, root, type);
327
+ : stdioJsonMcpCurrent(entry, root, type, home);
242
328
  }
243
329
 
244
330
  function codexHttpMcpCurrent(block: string, url: string | undefined) {
@@ -248,13 +334,17 @@ function codexHttpMcpCurrent(block: string, url: string | undefined) {
248
334
  !block.includes("command =")
249
335
  );
250
336
  }
251
- async function codexStdioMcpCurrent(block: string, _root: string | undefined) {
337
+ async function codexStdioMcpCurrent(
338
+ block: string,
339
+ root: string | undefined,
340
+ home: string,
341
+ ) {
252
342
  const command = block.match(/command = (".*")/);
253
343
  if (
254
344
  !block.includes("[mcp_servers.ast-mcp]") ||
255
345
  !block.includes('args = ["mcp"]') ||
256
346
  !command ||
257
- !(await astMcpEntry(JSON.parse(command[1])))
347
+ !(await astMcpEntry(JSON.parse(command[1]), root, home))
258
348
  )
259
349
  return false;
260
350
  return !block.includes("AST_MCP_PROJECT_ROOT") && !block.includes("env =");
@@ -264,13 +354,19 @@ async function codexMcpCurrent(
264
354
  root?: string,
265
355
  transport: Transport = "stdio",
266
356
  url?: string,
357
+ home = os.homedir(),
267
358
  ) {
268
359
  const content = await readFile(file, "utf8").catch(() => "");
360
+ if (
361
+ content.match(/# ast-mcp:begin/g)?.length !== 1 ||
362
+ content.match(/# ast-mcp:end/g)?.length !== 1
363
+ )
364
+ return false;
269
365
  const block =
270
366
  content.match(/# ast-mcp:begin\n([\s\S]*?)# ast-mcp:end/)?.[1] ?? "";
271
367
  return transport === "http"
272
368
  ? codexHttpMcpCurrent(block, url)
273
- : codexStdioMcpCurrent(block, root);
369
+ : codexStdioMcpCurrent(block, root, home);
274
370
  }
275
371
 
276
372
  type InstallChecks = Record<string, boolean>;
@@ -288,12 +384,13 @@ async function codexChecks(
288
384
  global ? undefined : options.root,
289
385
  options.transport,
290
386
  options.url,
387
+ home,
291
388
  ),
292
389
  hookCurrent(
293
390
  path.join(base, "hooks.json"),
294
391
  "PreToolUse",
295
- path.join(base, "hooks/ast-mcp.ts"),
296
- global ? path.join(base, "hooks/ast-mcp.ts") : ".codex/hooks/ast-mcp.ts",
392
+ global ? undefined : options.root,
393
+ home,
297
394
  ),
298
395
  skillCurrent(path.join(base, "skills/ast-mcp/SKILL.md")),
299
396
  instructionsCurrent(
@@ -322,14 +419,13 @@ async function claudeChecks(
322
419
  undefined,
323
420
  options.transport,
324
421
  options.url,
422
+ home,
325
423
  ),
326
424
  hookCurrent(
327
425
  path.join(base, "settings.json"),
328
426
  "PreToolUse",
329
- path.join(base, "hooks/ast-mcp.ts"),
330
- global
331
- ? path.join(base, "hooks/ast-mcp.ts")
332
- : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
427
+ global ? undefined : options.root,
428
+ home,
333
429
  ),
334
430
  skillCurrent(path.join(base, "skills/ast-mcp/SKILL.md")),
335
431
  instructionsCurrent(
@@ -358,12 +454,13 @@ async function copilotChecks(
358
454
  "local",
359
455
  options.transport,
360
456
  options.url,
457
+ home,
361
458
  ),
362
459
  hookCurrent(
363
460
  path.join(base, "hooks/ast-mcp.json"),
364
461
  "preToolUse",
365
- path.join(base, "hooks/ast-mcp.ts"),
366
- global ? path.join(base, "hooks/ast-mcp.ts") : ".github/hooks/ast-mcp.ts",
462
+ global ? undefined : options.root,
463
+ home,
367
464
  ),
368
465
  skillCurrent(path.join(base, "skills/ast-mcp/SKILL.md")),
369
466
  instructionsCurrent(
@@ -381,6 +478,7 @@ async function copilotChecks(
381
478
  "stdio",
382
479
  options.transport,
383
480
  options.url,
481
+ home,
384
482
  );
385
483
  return checks;
386
484
  }
@@ -405,7 +503,21 @@ async function serviceCurrent(options: CheckOptions, home: string) {
405
503
  const content = await readFile(serviceFile(options, home), "utf8").catch(
406
504
  () => "",
407
505
  );
506
+ const commandEntries = [
507
+ ...content.matchAll(
508
+ /(?:<string>|ExecStart=")([^"<\n]*ast-mcp)(?=<\/string>|")/g,
509
+ ),
510
+ ].map((match) => match[1]);
511
+ const commandCurrent =
512
+ options.scope === "local"
513
+ ? commandEntries.includes("./node_modules/.bin/ast-mcp")
514
+ : (
515
+ await Promise.all(
516
+ commandEntries.map((entry) => astMcpEntry(entry, undefined, home)),
517
+ )
518
+ ).some(Boolean);
408
519
  return (
520
+ commandCurrent &&
409
521
  content.includes("--transport") &&
410
522
  content.includes("http") &&
411
523
  content.includes(options.host) &&
@@ -415,7 +527,10 @@ async function serviceCurrent(options: CheckOptions, home: string) {
415
527
  }
416
528
  function installOperation(checks: InstallChecks) {
417
529
  if (Object.values(checks).every(Boolean)) return "none" as const;
418
- return Object.values(checks).some(Boolean)
530
+ const managedSurfaces = Object.entries(checks)
531
+ .filter(([name]) => name !== "astBro")
532
+ .map(([, current]) => current);
533
+ return managedSurfaces.some(Boolean)
419
534
  ? ("update" as const)
420
535
  : ("install" as const);
421
536
  }
@@ -424,16 +539,20 @@ function commandSuffix(options: CheckOptions, _global: boolean) {
424
539
  }
425
540
  function installCommands(options: CheckOptions, global: boolean) {
426
541
  const suffix = commandSuffix(options, global);
542
+ const updateCommand = global
543
+ ? `ast-mcp update ${suffix}`
544
+ : `./node_modules/.bin/ast-mcp update ${suffix}`;
427
545
  return {
428
546
  installCommand: global
429
- ? `bun add --global --trust @ast-bro/cli dprint @mwillbanks/ast-mcp && ast-mcp install ${suffix}`
430
- : `bun add --dev @mwillbanks/ast-mcp && bun pm trust @ast-bro/cli dprint && ./node_modules/.bin/ast-mcp install ${suffix}`,
547
+ ? `bun add --global --trust @ast-bro/cli@${astBroVersion} dprint @mwillbanks/ast-mcp && ast-mcp install ${suffix}`
548
+ : `bun add --dev @mwillbanks/ast-mcp @ast-bro/cli@${astBroVersion} && bun pm trust @ast-bro/cli dprint && ./node_modules/.bin/ast-mcp install ${suffix}`,
549
+ repairCommand: global
550
+ ? `bun add --global --trust @ast-bro/cli@${astBroVersion} && ${updateCommand}`
551
+ : `bun add --dev @ast-bro/cli@${astBroVersion} && bun pm trust @ast-bro/cli && ${updateCommand}`,
431
552
  uninstallCommand: global
432
553
  ? `ast-mcp uninstall ${suffix}`
433
554
  : `./node_modules/.bin/ast-mcp uninstall ${suffix}`,
434
- updateCommand: global
435
- ? `ast-mcp update ${suffix}`
436
- : `./node_modules/.bin/ast-mcp update ${suffix}`,
555
+ updateCommand,
437
556
  };
438
557
  }
439
558
  export async function checkInstall(
@@ -443,6 +562,7 @@ export async function checkInstall(
443
562
  const options = parse(args);
444
563
  const global = options.scope === "global";
445
564
  const checks = await targetChecks(options, home, global);
565
+ checks.astBro = await astBroCurrent(options, home);
446
566
  if (options.service) checks.service = await serviceCurrent(options, home);
447
567
  const installed = Object.values(checks).every(Boolean);
448
568
  const operation = installOperation(checks);
@@ -454,11 +574,14 @@ export async function checkInstall(
454
574
  needsUpdate: operation === "update",
455
575
  operation,
456
576
  recommendedCommand:
457
- operation === "update"
458
- ? commands.updateCommand
459
- : operation === "install"
460
- ? commands.installCommand
461
- : undefined,
577
+ !checks.astBro && operation !== "install"
578
+ ? commands.repairCommand
579
+ : operation === "update"
580
+ ? commands.updateCommand
581
+ : operation === "install"
582
+ ? commands.installCommand
583
+ : undefined,
584
+ repairCommand: commands.repairCommand,
462
585
  uninstallCommand: commands.uninstallCommand,
463
586
  updateCommand: commands.updateCommand,
464
587
  ...options,
@@ -1,5 +1,37 @@
1
+ import path from "node:path";
2
+
1
3
  export type HookEvent = "PreToolUse" | "preToolUse";
2
4
 
5
+ export function managedAstMcpHookEntry(command: unknown) {
6
+ if (typeof command !== "string") return undefined;
7
+ const normalized = command.trim();
8
+ if (!normalized.endsWith(" hook")) return undefined;
9
+ let invocation = normalized.slice(0, -" hook".length).trim();
10
+ if (invocation.startsWith("bun ")) {
11
+ invocation = invocation.slice(4).trim();
12
+ if (invocation.startsWith("run ")) invocation = invocation.slice(4).trim();
13
+ }
14
+ try {
15
+ invocation = JSON.parse(invocation);
16
+ } catch {}
17
+ if (typeof invocation !== "string") return undefined;
18
+ return [
19
+ "ast-mcp",
20
+ "ast-mcp.bat",
21
+ "ast-mcp.cmd",
22
+ "ast-mcp.com",
23
+ "ast-mcp.exe",
24
+ "ast-mcp.js",
25
+ "ast-mcp.ts",
26
+ ].includes(path.basename(invocation.replaceAll("\\", "/")).toLowerCase())
27
+ ? invocation
28
+ : undefined;
29
+ }
30
+
31
+ function commandMatches(actual: unknown, expected: string) {
32
+ return actual === expected || managedAstMcpHookEntry(actual) !== undefined;
33
+ }
34
+
3
35
  export function isManagedHook(
4
36
  item: unknown,
5
37
  event: HookEvent,
@@ -8,14 +40,14 @@ export function isManagedHook(
8
40
  if (!item || typeof item !== "object") return false;
9
41
  const value = item as Record<string, unknown>;
10
42
  if (event === "preToolUse")
11
- return value.command === command && value.type === "command";
43
+ return commandMatches(value.command, command) && value.type === "command";
12
44
  return (
13
45
  Array.isArray(value.hooks) &&
14
46
  value.hooks.some(
15
47
  (child) =>
16
48
  child &&
17
49
  typeof child === "object" &&
18
- (child as Record<string, unknown>).command === command &&
50
+ commandMatches((child as Record<string, unknown>).command, command) &&
19
51
  (child as Record<string, unknown>).type === "command",
20
52
  )
21
53
  );