@mwillbanks/ast-mcp 0.6.6 → 0.7.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 (55) hide show
  1. package/CONTRIBUTING.md +6 -0
  2. package/dist/ast-mcp.js +358 -337
  3. package/dist/ast-mcp.js.map +45 -32
  4. package/dist/workers/sql-postgres-worker.js +5 -0
  5. package/dist/workers/sql-postgres-worker.js.map +10 -0
  6. package/package.json +3 -2
  7. package/src/cli/doctor.ts +103 -0
  8. package/src/cli/index.ts +9 -1
  9. package/src/config/index.ts +61 -6
  10. package/src/config/registry.ts +209 -67
  11. package/src/config/v2-schema.ts +2 -0
  12. package/src/helpers/installer.ts +10 -1
  13. package/src/http/index.ts +12 -5
  14. package/src/installer/codex.ts +237 -0
  15. package/src/installer/diagnostics.ts +387 -0
  16. package/src/installer/directory-ancestry.ts +55 -0
  17. package/src/installer/index.ts +386 -119
  18. package/src/installer/ownership.ts +165 -0
  19. package/src/installer/service-state.ts +151 -0
  20. package/src/installer/service.ts +131 -7
  21. package/src/installer/transaction.ts +342 -0
  22. package/src/installer/transport.ts +22 -31
  23. package/src/intelligence/mutation/locks.ts +4 -1
  24. package/src/patch/engine.ts +157 -11
  25. package/src/runtime/approval.ts +427 -66
  26. package/src/runtime/config-write.ts +27 -1
  27. package/src/runtime/diagnostics.ts +115 -0
  28. package/src/runtime/file-capabilities.ts +2 -0
  29. package/src/runtime/hosts/codex.ts +16 -0
  30. package/src/runtime/path-policy.ts +2 -0
  31. package/src/runtime/release.ts +220 -0
  32. package/src/runtime/sql-assistance.ts +439 -0
  33. package/src/runtime/sql-options-schema.ts +31 -0
  34. package/src/runtime/sql-postgres-worker.ts +72 -0
  35. package/src/runtime/sql-postgres.ts +245 -0
  36. package/src/server/index.ts +35 -5
  37. package/src/server/lifecycle.ts +1 -1
  38. package/src/tools/configuration.ts +2 -0
  39. package/src/tools/diagnostics.ts +85 -0
  40. package/src/tools/files.ts +2 -0
  41. package/src/tools/index.ts +9 -0
  42. package/templates/skills/ast-mcp/SKILL.md +20 -1
  43. package/templates/skills/ast-mcp/evals/evals.json +274 -0
  44. package/templates/skills/ast-mcp/evals/semantic.ts +2 -0
  45. package/templates/skills/ast-mcp/evals/trigger-queries.json +4 -1
  46. package/templates/skills/ast-mcp/references/cli.md +97 -0
  47. package/templates/skills/ast-mcp/references/configuration.md +11 -3
  48. package/templates/skills/ast-mcp/references/diagnostics.md +106 -0
  49. package/templates/skills/ast-mcp/references/host-context.md +85 -0
  50. package/templates/skills/ast-mcp/references/installation.md +37 -0
  51. package/templates/skills/ast-mcp/references/issue-reporting.md +80 -0
  52. package/templates/skills/ast-mcp/references/patch-state-machine.md +10 -0
  53. package/templates/skills/ast-mcp/references/tool-catalog.md +120 -50
  54. package/templates/skills/ast-mcp/scripts/check-install.ts +223 -24
  55. package/templates/skills/ast-mcp/scripts/release.ts +220 -0
@@ -1,5 +1,16 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+
3
+ import {
4
+ launchFields,
5
+ launchReceipt,
6
+ parseLaunchReceipt,
7
+ removeManagedEntry,
8
+ } from "./ownership";
9
+
1
10
  type TomlDocument = Record<string, unknown>;
2
11
 
12
+ export { parseConfig as parseCodexConfig };
13
+
3
14
  function parseConfig(content: string): TomlDocument {
4
15
  try {
5
16
  return Bun.TOML.parse(content) as TomlDocument;
@@ -140,6 +151,81 @@ function assignmentValue(statement: string, replacement: string) {
140
151
  throw new Error("Cannot locate Codex approval assignment");
141
152
  }
142
153
 
154
+ function codexLaunchReceipt(content: string) {
155
+ const encoded = content.match(/^# ast-mcp:launch (.*)$/m)?.[1];
156
+ if (!encoded) return undefined;
157
+ try {
158
+ return parseLaunchReceipt(JSON.parse(encoded));
159
+ } catch {
160
+ return undefined;
161
+ }
162
+ }
163
+
164
+ /** Replace owned launch fields while retaining user tool and server settings. */
165
+ export function refreshCodexMcp(
166
+ content: string,
167
+ launch: Record<string, unknown>,
168
+ ): string {
169
+ const document = parseConfig(content);
170
+ const servers = record(document.mcp_servers) ? document.mcp_servers : {};
171
+ const existing = record(servers["ast-mcp"]) ? { ...servers["ast-mcp"] } : {};
172
+ const receipt = launchReceipt(existing, launch, codexLaunchReceipt(content));
173
+ for (const key of ["command", "args", "cwd", "url", "type"])
174
+ delete existing[key];
175
+ let section: string[] = [];
176
+ const clean = statements(content)
177
+ .filter((statement) => {
178
+ if (
179
+ /^# ast-mcp:(?:begin|end)\s*$/.test(statement.trim()) ||
180
+ statement.startsWith("# ast-mcp:launch ")
181
+ )
182
+ return false;
183
+ if (statement.trimStart().startsWith("[")) {
184
+ section =
185
+ headerPath(parseConfig(`${statement}\n__ast_mcp_probe = true\n`)) ??
186
+ [];
187
+ return !(section[0] === "mcp_servers" && section[1] === "ast-mcp");
188
+ }
189
+ if (section[0] === "mcp_servers" && section[1] === "ast-mcp")
190
+ return false;
191
+ const value = parseConfig(statement);
192
+ if (Object.keys(value).length === 0) return true;
193
+ const relative =
194
+ headerPath(
195
+ parseConfig(assignmentValue(statement, "{ __ast_mcp_probe = true }")),
196
+ ) ?? [];
197
+ const absolute = [...section, ...relative];
198
+ if (absolute[0] === "mcp_servers" && absolute[1] === "ast-mcp")
199
+ return false;
200
+ if (
201
+ record(value.mcp_servers) &&
202
+ value.mcp_servers["ast-mcp"] !== undefined
203
+ )
204
+ throw new Error(
205
+ "Expand inline Codex MCP server configuration before updating",
206
+ );
207
+ return true;
208
+ })
209
+ .join("")
210
+ .trimEnd();
211
+ const lines = [
212
+ "[mcp_servers.ast-mcp]",
213
+ ...Object.entries(launch).map(
214
+ ([key, value]) => `${key} = ${JSON.stringify(value)}`,
215
+ ),
216
+ ];
217
+ if (Object.keys(existing).length) {
218
+ const retained = Bun.TOML.stringify({
219
+ mcp_servers: { "ast-mcp": existing },
220
+ });
221
+ lines.push(retained.replace(/^\[mcp_servers\.ast-mcp\]\n/, "").trimEnd());
222
+ }
223
+ const block = `# ast-mcp:launch ${JSON.stringify(receipt)}\n# ast-mcp:begin\n${lines.join("\n")}\n# ast-mcp:end\n`;
224
+ const result = `${clean ? `${clean}\n\n` : ""}${block}`;
225
+ parseConfig(result);
226
+ return result;
227
+ }
228
+
143
229
  /** Enable elicitation while preserving unrelated TOML and approval categories. */
144
230
  export function enableCodexElicitation(content: string, inheritedContent = "") {
145
231
  const document = parseConfig(content);
@@ -293,5 +379,156 @@ export function enableCodexElicitation(content: string, inheritedContent = "") {
293
379
  "Cannot safely enable Codex MCP elicitation in this TOML layout",
294
380
  );
295
381
  }
382
+ const overlays = changed
383
+ .map(
384
+ (target) =>
385
+ "# ast-mcp:approval-overlay " +
386
+ JSON.stringify({
387
+ keys: target.keys,
388
+ enabled: target.enabled,
389
+ ...(get(document, target.keys) !== undefined
390
+ ? { previous: get(document, target.keys) }
391
+ : {}),
392
+ }) +
393
+ "\n",
394
+ )
395
+ .join("");
396
+ result = result.replace(
397
+ /^# ast-mcp:approval-overlay (.*)\r?\n/gm,
398
+ (line, encoded: string) => {
399
+ try {
400
+ const metadata = JSON.parse(encoded);
401
+ return changed.some((target) =>
402
+ isDeepStrictEqual(metadata?.keys, target.keys),
403
+ )
404
+ ? ""
405
+ : line;
406
+ } catch {
407
+ return line;
408
+ }
409
+ },
410
+ );
411
+ return overlays + result;
412
+ }
413
+
414
+ /** Remove only generated overlays that the user has not subsequently changed. */
415
+ function removeApprovalOverlays(content: string): string {
416
+ const document = parseConfig(content);
417
+ const removable: Array<{ keys: string[]; previous?: unknown }> = [];
418
+ const withoutMetadata = content.replace(
419
+ /^# ast-mcp:approval-overlay (.*)\r?\n/gm,
420
+ (_line, encoded: string) => {
421
+ try {
422
+ const overlay: unknown = JSON.parse(encoded);
423
+ if (!record(overlay) || !Array.isArray(overlay.keys)) return "";
424
+ const keys = overlay.keys;
425
+ if (
426
+ !(
427
+ (keys.length === 1 && keys[0] === "approval_policy") ||
428
+ (keys.length === 3 &&
429
+ keys[0] === "profiles" &&
430
+ typeof keys[1] === "string" &&
431
+ keys[2] === "approval_policy")
432
+ )
433
+ )
434
+ return "";
435
+ if (isDeepStrictEqual(get(document, keys), overlay.enabled))
436
+ removable.push({
437
+ keys,
438
+ ...(Object.hasOwn(overlay, "previous")
439
+ ? { previous: overlay.previous }
440
+ : {}),
441
+ });
442
+ } catch {
443
+ // Unrecognized metadata never authorizes configuration removal.
444
+ }
445
+ return "";
446
+ },
447
+ );
448
+ let section: string[] = [];
449
+ const retained = statements(withoutMetadata)
450
+ .filter((statement) => {
451
+ if (statement.trimStart().startsWith("[")) {
452
+ section =
453
+ headerPath(parseConfig(statement + "\n__ast_mcp_probe = true\n")) ??
454
+ [];
455
+ return !removable.some(({ keys }) =>
456
+ keys.every((key, index) => section[index] === key),
457
+ );
458
+ }
459
+ if (Object.keys(parseConfig(statement)).length === 0) return true;
460
+ const relative =
461
+ headerPath(
462
+ parseConfig(assignmentValue(statement, "{ __ast_mcp_probe = true }")),
463
+ ) ?? [];
464
+ const absolute = [...section, ...relative];
465
+ return !removable.some(({ keys }) =>
466
+ keys.every((key, index) => absolute[index] === key),
467
+ );
468
+ })
469
+ .join("");
470
+ const restored = removable.filter((entry) =>
471
+ Object.hasOwn(entry, "previous"),
472
+ );
473
+ const chunks = statements(retained);
474
+ const insertions = new Map<number, string[]>();
475
+ for (const { keys, previous } of restored) {
476
+ let position = -1;
477
+ let prefix: string[] = [];
478
+ for (let index = 0; index < chunks.length; index++) {
479
+ const chunk = chunks[index]!;
480
+ if (!chunk.trimStart().startsWith("[")) continue;
481
+ const candidate =
482
+ headerPath(parseConfig(chunk + "\n__ast_mcp_probe = true\n")) ?? [];
483
+ if (
484
+ candidate.length < keys.length &&
485
+ candidate.length > prefix.length &&
486
+ candidate.every((key, part) => keys[part] === key)
487
+ ) {
488
+ position = index;
489
+ prefix = candidate;
490
+ }
491
+ }
492
+ const assignment =
493
+ keys
494
+ .slice(prefix.length)
495
+ .map((key) => JSON.stringify(key))
496
+ .join(".") +
497
+ " = " +
498
+ (record(previous) ? inlineTable(previous) : JSON.stringify(previous)) +
499
+ "\n";
500
+ insertions.set(position, [...(insertions.get(position) ?? []), assignment]);
501
+ }
502
+ const result =
503
+ (insertions.get(-1) ?? []).join("") +
504
+ chunks
505
+ .map((chunk, index) => chunk + (insertions.get(index) ?? []).join(""))
506
+ .join("");
507
+ parseConfig(result);
296
508
  return result;
297
509
  }
510
+
511
+ /** Uninstall launch fields without deleting retained user server configuration. */
512
+ export function removeCodexMcpConfiguration(content: string): string {
513
+ const cleaned = removeApprovalOverlays(content);
514
+ if (!/^# ast-mcp:begin\s*$/m.test(cleaned)) return cleaned;
515
+ const document = parseConfig(cleaned);
516
+ const servers = record(document.mcp_servers) ? document.mcp_servers : {};
517
+ const existing = record(servers["ast-mcp"]) ? servers["ast-mcp"] : {};
518
+ const legacyLaunchOnly =
519
+ !/^# ast-mcp:launch /m.test(cleaned) &&
520
+ Object.keys(existing).every((key) =>
521
+ (launchFields as readonly string[]).includes(key),
522
+ );
523
+ const remaining = legacyLaunchOnly
524
+ ? undefined
525
+ : removeManagedEntry(existing, codexLaunchReceipt(cleaned));
526
+ const refreshed = refreshCodexMcp(cleaned, {});
527
+ return refreshed
528
+ .replace(/^# ast-mcp:launch .*\r?\n/gm, "")
529
+ .replace(/# ast-mcp:begin\n[\s\S]*?# ast-mcp:end\n?/g, () =>
530
+ remaining
531
+ ? Bun.TOML.stringify({ mcp_servers: { "ast-mcp": remaining } })
532
+ : "",
533
+ );
534
+ }
@@ -0,0 +1,387 @@
1
+ import { readFile, realpath, stat } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { codexHome } from "../helpers/installer";
6
+
7
+ type HostTarget = "auto" | "codex" | "claude" | "copilot";
8
+ type Scope = "local" | "global";
9
+ type Document = Record<string, unknown>;
10
+
11
+ function record(value: unknown): value is Document {
12
+ return value !== null && typeof value === "object" && !Array.isArray(value);
13
+ }
14
+
15
+ async function document(file: string, kind: "toml" | "json") {
16
+ try {
17
+ const info = await stat(file);
18
+ if (!info.isFile() || info.size > 1024 * 1024)
19
+ return { status: "unreadable" as const, value: {} as Document };
20
+ const source = await readFile(file, "utf8");
21
+ const value =
22
+ kind === "toml" ? Bun.TOML.parse(source) : Bun.JSONC.parse(source);
23
+ return record(value)
24
+ ? { status: "loaded" as const, value }
25
+ : { status: "invalid" as const, value: {} as Document };
26
+ } catch (error) {
27
+ const code = (error as NodeJS.ErrnoException).code;
28
+ return {
29
+ status:
30
+ code === "ENOENT"
31
+ ? ("missing" as const)
32
+ : code === undefined
33
+ ? ("invalid" as const)
34
+ : ("unreadable" as const),
35
+ value: {} as Document,
36
+ };
37
+ }
38
+ }
39
+
40
+ function policySummary(policy: unknown) {
41
+ if (policy === "never") return { policy: "never", elicitation: "blocked" };
42
+ if (policy === "on-request" || policy === "untrusted")
43
+ return { policy, elicitation: "allowed" };
44
+ if (record(policy) && record(policy.granular)) {
45
+ const enabled = policy.granular.mcp_elicitations;
46
+ return {
47
+ policy: "granular",
48
+ elicitation:
49
+ enabled === true
50
+ ? "allowed"
51
+ : enabled === false
52
+ ? "blocked"
53
+ : "unknown",
54
+ };
55
+ }
56
+ return {
57
+ policy: policy === undefined ? "default" : "unsupported",
58
+ elicitation: "unknown",
59
+ };
60
+ }
61
+
62
+ function profilePolicy(value: Document, profile: string | undefined) {
63
+ if (!profile || !record(value.profiles)) return undefined;
64
+ const entry = value.profiles[profile];
65
+ return record(entry) ? entry.approval_policy : undefined;
66
+ }
67
+
68
+ function selectedProfile(value: unknown): string | undefined {
69
+ return typeof value === "string" && /^[\w.-]{1,100}$/.test(value)
70
+ ? value
71
+ : undefined;
72
+ }
73
+
74
+ async function projectConfiguration(root: string) {
75
+ const candidates: string[] = [];
76
+ let directory = root;
77
+ let boundaryFound = false;
78
+ for (let depth = 0; depth < 64; depth++) {
79
+ candidates.push(directory);
80
+ if (
81
+ await stat(path.join(directory, ".git")).then(
82
+ () => true,
83
+ () => false,
84
+ )
85
+ ) {
86
+ boundaryFound = true;
87
+ break;
88
+ }
89
+ const parent = path.dirname(directory);
90
+ if (parent === directory) break;
91
+ directory = parent;
92
+ }
93
+ const layers = await Promise.all(
94
+ (boundaryFound ? candidates.reverse() : [root]).map((candidate) =>
95
+ document(path.join(candidate, ".codex/config.toml"), "toml"),
96
+ ),
97
+ );
98
+ const invalid = layers.find(
99
+ (layer) => layer.status === "invalid" || layer.status === "unreadable",
100
+ );
101
+ const loaded = layers.filter((layer) => layer.status === "loaded");
102
+ return {
103
+ status:
104
+ invalid?.status ??
105
+ (loaded.length ? ("loaded" as const) : ("missing" as const)),
106
+ value: Object.assign({}, ...loaded.map((layer) => layer.value)) as Document,
107
+ count: loaded.length,
108
+ };
109
+ }
110
+
111
+ export async function inspectCodexConfiguration(options: {
112
+ root: string;
113
+ scope: Scope;
114
+ home?: string;
115
+ env?: NodeJS.ProcessEnv;
116
+ profile?: string;
117
+ }) {
118
+ const home = options.home ?? os.homedir();
119
+ const env = options.env ?? process.env;
120
+ const global = await document(
121
+ path.join(codexHome(home, env), "config.toml"),
122
+ "toml",
123
+ );
124
+ const project =
125
+ options.scope === "local"
126
+ ? await projectConfiguration(options.root)
127
+ : { status: "not-selected" as const, value: {} as Document, count: 0 };
128
+ // Modern Codex loads named global profile files below trusted project overrides.
129
+ // Older hosts used inline profiles; report both interpretations when they differ.
130
+ const profile = options.profile ?? selectedProfile(global.value.profile);
131
+ const profileFile = profile
132
+ ? await document(
133
+ path.join(codexHome(home, env), `${profile}.config.toml`),
134
+ "toml",
135
+ )
136
+ : { status: "not-selected" as const, value: {} as Document };
137
+ const projects = record(global.value.projects) ? global.value.projects : {};
138
+ const trustKey = Object.keys(projects)
139
+ .filter((candidate) => {
140
+ const relative = path.relative(candidate, options.root);
141
+ return (
142
+ relative === "" ||
143
+ (!relative.startsWith(`..${path.sep}`) &&
144
+ relative !== ".." &&
145
+ !path.isAbsolute(relative))
146
+ );
147
+ })
148
+ .sort((first, second) => second.length - first.length)[0];
149
+ const trustedEntry = trustKey ? projects[trustKey] : undefined;
150
+ const trust = record(trustedEntry) ? trustedEntry.trust_level : undefined;
151
+ const projectPolicy = project.value.approval_policy;
152
+ const projectTrustUnknown = project.count > 0 && trust !== "trusted";
153
+ const modernPolicy =
154
+ projectPolicy ??
155
+ profileFile.value.approval_policy ??
156
+ global.value.approval_policy;
157
+ const profileProject = profilePolicy(project.value, profile);
158
+ const profileGlobal = profilePolicy(global.value, profile);
159
+ const legacyPolicy =
160
+ profileProject ??
161
+ profileGlobal ??
162
+ projectPolicy ??
163
+ global.value.approval_policy;
164
+ const legacyAmbiguous =
165
+ profileFile.status !== "loaded" &&
166
+ (profileProject !== undefined || profileGlobal !== undefined) &&
167
+ JSON.stringify(policySummary(legacyPolicy)) !==
168
+ JSON.stringify(policySummary(modernPolicy));
169
+ const source =
170
+ projectPolicy !== undefined
171
+ ? "project"
172
+ : profileFile.value.approval_policy !== undefined
173
+ ? "profile-file"
174
+ : global.value.approval_policy !== undefined
175
+ ? "global"
176
+ : "default";
177
+ const invalid = [global.status, project.status, profileFile.status].some(
178
+ (status) => status === "invalid" || status === "unreadable",
179
+ );
180
+ const summary =
181
+ invalid || legacyAmbiguous || projectTrustUnknown || trust === "untrusted"
182
+ ? { policy: "unknown", elicitation: "unknown" }
183
+ : policySummary(modernPolicy);
184
+ return {
185
+ target: "codex",
186
+ layers: {
187
+ global: global.status,
188
+ project: project.status,
189
+ projectLayerCount: project.count,
190
+ profileFile: profileFile.status,
191
+ customHome: Boolean(env.CODEX_HOME),
192
+ legacyInlineProfiles:
193
+ profileProject !== undefined || profileGlobal !== undefined,
194
+ },
195
+ selectedProfile: profile ?? "unknown",
196
+ disk: {
197
+ ...summary,
198
+ source:
199
+ invalid || projectTrustUnknown
200
+ ? "unknown"
201
+ : legacyAmbiguous
202
+ ? "host-version-dependent"
203
+ : source,
204
+ trust: trust === "trusted" || trust === "untrusted" ? trust : "unknown",
205
+ modernCandidate: policySummary(modernPolicy),
206
+ legacyCandidate: policySummary(legacyPolicy),
207
+ },
208
+ session: {
209
+ approvalPolicy: "unknown",
210
+ backendVersion: "unknown",
211
+ overrides: "unknown",
212
+ readiness: "unknown",
213
+ },
214
+ guidance: [
215
+ "Disk configuration does not establish the running session policy.",
216
+ "Codex Desktop Full access can override disk settings with approval_policy=never.",
217
+ "CLI approval flags can override disk policy. Modern named profile files load below trusted project overrides.",
218
+ "Project profile declarations are ignored by modern Codex; older inline-profile behavior can differ.",
219
+ "Use a session policy that permits MCP elicitation, reconnect when required, and answer the real approval form.",
220
+ "Per-tool approval settings do not authorize the separate AST-MCP filesystem challenge.",
221
+ ],
222
+ };
223
+ }
224
+
225
+ async function inspectJsonHost(
226
+ target: "claude" | "copilot",
227
+ root: string,
228
+ scope: Scope,
229
+ home: string,
230
+ ) {
231
+ const file =
232
+ target === "claude"
233
+ ? scope === "global"
234
+ ? path.join(home, ".claude.json")
235
+ : path.join(root, ".mcp.json")
236
+ : scope === "global"
237
+ ? path.join(home, ".copilot/mcp-config.json")
238
+ : path.join(root, ".github/mcp.json");
239
+ const loaded = await document(file, "json");
240
+ const servers = record(loaded.value.mcpServers)
241
+ ? loaded.value.mcpServers
242
+ : {};
243
+ const configured = record(servers["ast-mcp"]);
244
+ return {
245
+ target,
246
+ configuration: loaded.status,
247
+ astMcpConfigured: configured,
248
+ session: {
249
+ approvalPolicy: "unknown",
250
+ backendVersion: "unknown",
251
+ readiness: "unknown",
252
+ },
253
+ guidance: [
254
+ "Use live MCP diagnostics to inspect negotiated capabilities and approval outcomes.",
255
+ ],
256
+ };
257
+ }
258
+
259
+ async function packageVersion(file: string): Promise<string> {
260
+ const result = await document(file, "json");
261
+ return result.value.name === "@mwillbanks/ast-mcp" &&
262
+ typeof result.value.version === "string" &&
263
+ /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]+)?$/.test(result.value.version)
264
+ ? result.value.version
265
+ : "unknown";
266
+ }
267
+
268
+ async function globalPackageVersion() {
269
+ const binary = Bun.which("ast-mcp");
270
+ if (!binary) return "unknown";
271
+ try {
272
+ let directory = path.dirname(await realpath(binary));
273
+ for (let depth = 0; depth < 4; depth++) {
274
+ const version = await packageVersion(
275
+ path.join(directory, "package.json"),
276
+ );
277
+ if (version !== "unknown") return version;
278
+ const parent = path.dirname(directory);
279
+ if (parent === directory) break;
280
+ directory = parent;
281
+ }
282
+ } catch {}
283
+ return "unknown";
284
+ }
285
+
286
+ async function upgradeGuidance(root: string, scope: Scope, target: HostTarget) {
287
+ const project = await document(path.join(root, "package.json"), "json");
288
+ let manager =
289
+ typeof project.value.packageManager === "string"
290
+ ? /^(bun|npm|pnpm|yarn)@/.exec(project.value.packageManager)?.[1]
291
+ : undefined;
292
+ if (scope === "global") {
293
+ const binary = (Bun.which("ast-mcp") ?? "").replaceAll("\\", "/");
294
+ manager = binary.includes("/.bun/")
295
+ ? "bun"
296
+ : binary.includes("/pnpm/")
297
+ ? "pnpm"
298
+ : binary.includes("/npm/")
299
+ ? "npm"
300
+ : undefined;
301
+ } else if (!manager) {
302
+ const locks = [
303
+ ["bun", "bun.lock"],
304
+ ["bun", "bun.lockb"],
305
+ ["pnpm", "pnpm-lock.yaml"],
306
+ ["yarn", "yarn.lock"],
307
+ ["npm", "package-lock.json"],
308
+ ] as const;
309
+ const present = await Promise.all(
310
+ locks.map(
311
+ async ([name, file]) =>
312
+ await stat(path.join(root, file)).then(
313
+ () => name,
314
+ () => undefined,
315
+ ),
316
+ ),
317
+ );
318
+ const managers = new Set(present.filter(Boolean));
319
+ if (managers.size === 1) manager = [...managers][0];
320
+ }
321
+ const local: Record<string, string> = {
322
+ bun: "bun add --dev @mwillbanks/ast-mcp@latest",
323
+ npm: "npm install --save-dev @mwillbanks/ast-mcp@latest",
324
+ pnpm: "pnpm add --save-dev @mwillbanks/ast-mcp@latest",
325
+ yarn: "yarn add --dev @mwillbanks/ast-mcp@latest",
326
+ };
327
+ const global: Record<string, string> = {
328
+ bun: "bun add --global @mwillbanks/ast-mcp@latest",
329
+ npm: "npm install --global @mwillbanks/ast-mcp@latest",
330
+ pnpm: "pnpm add --global @mwillbanks/ast-mcp@latest",
331
+ };
332
+ return {
333
+ manager: manager ?? "unknown",
334
+ command: manager
335
+ ? ((scope === "global" ? global : local)[manager] ?? "unknown")
336
+ : "unknown",
337
+ refreshCommand: `${scope === "local" ? "./node_modules/.bin/ast-mcp" : "ast-mcp"} update --scope ${scope} --target ${target === "auto" ? "all" : target}`,
338
+ automatic: false,
339
+ steps: [
340
+ "Use the existing installation package manager and scope. Consult the installation skill reference when the manager is unknown.",
341
+ "After an authorized package upgrade, refresh managed host configuration, reconnect the MCP server, and rerun live diagnostics.",
342
+ "A newer shell executable does not establish that the connected server restarted.",
343
+ ],
344
+ };
345
+ }
346
+
347
+ export async function inspectHostConfiguration(options: {
348
+ root: string;
349
+ scope: Scope;
350
+ target: HostTarget;
351
+ profile?: string;
352
+ home?: string;
353
+ env?: NodeJS.ProcessEnv;
354
+ }) {
355
+ const home = options.home ?? os.homedir();
356
+ const requested =
357
+ options.target === "auto"
358
+ ? (["codex", "claude", "copilot"] as const)
359
+ : [options.target];
360
+ const hosts = await Promise.all(
361
+ requested.map((target) =>
362
+ target === "codex"
363
+ ? inspectCodexConfiguration({ ...options, home })
364
+ : inspectJsonHost(target, options.root, options.scope, home),
365
+ ),
366
+ );
367
+ return {
368
+ scope: options.scope,
369
+ requestedTarget: options.target,
370
+ hosts,
371
+ upgrade: await upgradeGuidance(options.root, options.scope, options.target),
372
+ installedPackages: {
373
+ projectVersion: await packageVersion(
374
+ path.join(
375
+ options.root,
376
+ "node_modules/@mwillbanks/ast-mcp/package.json",
377
+ ),
378
+ ),
379
+ pathExecutableVersion: await globalPackageVersion(),
380
+ connectedServerVersion: "unknown",
381
+ desktopBackendVersion: "unknown",
382
+ },
383
+ guidance: [
384
+ "The CLI process, PATH executable, project package, and connected MCP server can run different versions. Run MCP diagnostics for the connected server.",
385
+ ],
386
+ };
387
+ }
@@ -0,0 +1,55 @@
1
+ import { lstatSync, realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ export type DirectoryIdentity = { real: string; ino: number; dev: number };
5
+ type AncestryPaths = Pick<typeof path, "resolve" | "dirname" | "relative">;
6
+ type AncestryOptions = {
7
+ paths?: AncestryPaths;
8
+ inspect?: (directory: string) => DirectoryIdentity;
9
+ };
10
+
11
+ function inspectDirectory(directory: string): DirectoryIdentity {
12
+ const info = lstatSync(directory);
13
+ if (!info.isDirectory())
14
+ throw new Error("Created-directory boundary must be a directory");
15
+ return { real: realpathSync(directory), ino: info.ino, dev: info.dev };
16
+ }
17
+
18
+ function sameDirectory(
19
+ left: DirectoryIdentity,
20
+ right: DirectoryIdentity,
21
+ paths: AncestryPaths,
22
+ ) {
23
+ if (left.dev !== right.dev) return false;
24
+ // Some filesystems omit inode identifiers. Canonical location is the conservative fallback.
25
+ if (left.ino !== 0 && right.ino !== 0) return left.ino === right.ino;
26
+ return paths.relative(left.real, right.real) === "";
27
+ }
28
+
29
+ /** Return cleanup ownership only after proving the first directory created by recursive mkdir. */
30
+ export function createdDirectoryAncestors(
31
+ directory: string,
32
+ first: string,
33
+ options: AncestryOptions = {},
34
+ ): Map<string, DirectoryIdentity> {
35
+ const paths = options.paths ?? path;
36
+ const inspect = options.inspect ?? inspectDirectory;
37
+ const boundary = inspect(paths.resolve(first));
38
+ const candidates = new Map<string, DirectoryIdentity>();
39
+ let current = paths.resolve(directory);
40
+ // dirname must progress toward a root. The length bound also protects injected path adapters.
41
+ for (let remaining = current.length + 1; remaining > 0; remaining -= 1) {
42
+ const parent = paths.dirname(current);
43
+ if (parent === current || candidates.has(current)) break;
44
+ const identity = inspect(current);
45
+ candidates.set(current, identity);
46
+ if (sameDirectory(identity, boundary, paths)) return candidates;
47
+ current = parent;
48
+ }
49
+ throw Object.assign(
50
+ new Error(
51
+ "Cannot verify created-directory ancestry; refusing cleanup ownership",
52
+ ),
53
+ { code: "configuration_conflict", retryable: true },
54
+ );
55
+ }