@mwillbanks/ast-mcp 0.6.5 → 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
@@ -0,0 +1,165 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+
3
+ export const launchFields = ["command", "args", "cwd", "url", "type"] as const;
4
+ type Entry = Record<string, unknown>;
5
+ export interface LaunchReceipt {
6
+ before: Entry | null;
7
+ installed: Entry;
8
+ }
9
+ export function launchSettings(entry: Entry): Entry {
10
+ return Object.fromEntries(
11
+ launchFields.filter((key) => key in entry).map((key) => [key, entry[key]]),
12
+ );
13
+ }
14
+ export function launchReceipt(
15
+ existing: Entry,
16
+ installed: Entry,
17
+ previous?: LaunchReceipt,
18
+ ownsTools = false,
19
+ ): LaunchReceipt {
20
+ previous = parseLaunchReceipt(previous);
21
+ const sameLaunch =
22
+ previous &&
23
+ isDeepStrictEqual(
24
+ launchSettings(existing),
25
+ launchSettings(previous.installed),
26
+ );
27
+ const toolsChanged =
28
+ previous &&
29
+ sameLaunch &&
30
+ Object.hasOwn(previous.installed, "tools") &&
31
+ !isDeepStrictEqual(existing.tools, previous.installed.tools);
32
+ const existingOwned = {
33
+ ...launchSettings(existing),
34
+ ...(ownsTools && existing.tools !== undefined
35
+ ? { tools: existing.tools }
36
+ : {}),
37
+ };
38
+ let before =
39
+ previous && sameLaunch
40
+ ? previous.before === null
41
+ ? null
42
+ : { ...previous.before }
43
+ : validLaunch(existingOwned)
44
+ ? existingOwned
45
+ : null;
46
+ if (toolsChanged) {
47
+ before ??= launchSettings(existing);
48
+ delete before.tools;
49
+ if (existing.tools !== undefined) before.tools = existing.tools;
50
+ }
51
+ return {
52
+ before,
53
+ installed: {
54
+ ...launchSettings(installed),
55
+ ...(ownsTools && installed.tools !== undefined
56
+ ? { tools: installed.tools }
57
+ : {}),
58
+ },
59
+ };
60
+ }
61
+ export function removeManagedEntry(
62
+ existing: Entry,
63
+ receipt?: LaunchReceipt,
64
+ ): Entry | undefined {
65
+ receipt = parseLaunchReceipt(receipt);
66
+ if (
67
+ !receipt ||
68
+ !isDeepStrictEqual(
69
+ launchSettings(existing),
70
+ launchSettings(receipt.installed),
71
+ )
72
+ )
73
+ return existing;
74
+ const extras = { ...existing };
75
+ for (const key of launchFields) delete extras[key];
76
+ const before = receipt.before === null ? null : { ...receipt.before };
77
+ const ownsTools = Object.hasOwn(receipt.installed, "tools");
78
+ if (
79
+ before &&
80
+ ownsTools &&
81
+ !isDeepStrictEqual(existing.tools, receipt.installed.tools)
82
+ ) {
83
+ delete before.tools;
84
+ if (existing.tools !== undefined) before.tools = existing.tools;
85
+ }
86
+ if (
87
+ ownsTools &&
88
+ before?.tools === undefined &&
89
+ isDeepStrictEqual(extras.tools, receipt.installed.tools)
90
+ )
91
+ delete extras.tools;
92
+ if (before !== null) return { ...before, ...extras };
93
+ return Object.keys(extras).length ? existing : undefined;
94
+ }
95
+
96
+ function validLaunch(value: unknown): value is Entry {
97
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
98
+ const entry = value as Entry;
99
+ if (
100
+ !Object.keys(entry).every((key) => [...launchFields, "tools"].includes(key))
101
+ )
102
+ return false;
103
+ for (const key of ["command", "cwd", "url", "type"])
104
+ if (
105
+ key in entry &&
106
+ (typeof entry[key] !== "string" || !(entry[key] as string).trim())
107
+ )
108
+ return false;
109
+ for (const key of ["args", "tools"])
110
+ if (
111
+ key in entry &&
112
+ (!Array.isArray(entry[key]) ||
113
+ !(entry[key] as unknown[]).every(
114
+ (item: unknown) => typeof item === "string",
115
+ ))
116
+ )
117
+ return false;
118
+ const command = typeof entry.command === "string";
119
+ const remote = typeof entry.url === "string";
120
+ if (command === remote) return false;
121
+ if (command)
122
+ return (
123
+ entry.type === undefined ||
124
+ entry.type === "local" ||
125
+ entry.type === "stdio"
126
+ );
127
+ if (
128
+ "args" in entry ||
129
+ "cwd" in entry ||
130
+ (entry.type !== undefined && entry.type !== "http" && entry.type !== "sse")
131
+ )
132
+ return false;
133
+ try {
134
+ return ["http:", "https:"].includes(new URL(entry.url as string).protocol);
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+
140
+ export function parseLaunchReceipt(value: unknown): LaunchReceipt | undefined {
141
+ if (!value || typeof value !== "object" || Array.isArray(value))
142
+ return undefined;
143
+ const receipt = value as Record<string, unknown>;
144
+ if (
145
+ !Object.keys(receipt).every(
146
+ (key) => key === "before" || key === "installed",
147
+ )
148
+ )
149
+ return undefined;
150
+ return (receipt.before === null || validLaunch(receipt.before)) &&
151
+ validLaunch(receipt.installed)
152
+ ? (receipt as unknown as LaunchReceipt)
153
+ : undefined;
154
+ }
155
+
156
+ /** Apply the first-install default without overriding a recorded user deletion. */
157
+ export function managedToolSelection(
158
+ existing: Entry,
159
+ previous?: LaunchReceipt,
160
+ ): Entry {
161
+ if (Object.hasOwn(existing, "tools")) return { tools: existing.tools };
162
+ return parseLaunchReceipt(previous) || Object.keys(existing).length
163
+ ? {}
164
+ : { tools: ["*"] };
165
+ }
@@ -0,0 +1,151 @@
1
+ import {
2
+ readSubprocessOutput,
3
+ terminateProcessTree,
4
+ } from "../runtime/subprocess";
5
+
6
+ export type ServiceStateQuery = (command: string[]) => Promise<{
7
+ exitCode: number;
8
+ stdout: string;
9
+ stderr: string;
10
+ }>;
11
+ export type ServiceState =
12
+ | { platform: "linux"; loaded: boolean; enabled: boolean; active: boolean }
13
+ | {
14
+ platform: "darwin";
15
+ loaded: boolean;
16
+ disabled: boolean;
17
+ running: boolean;
18
+ };
19
+
20
+ export async function queryServiceCommand(command: string[], timeoutMs = 5000) {
21
+ const child = Bun.spawn(command, {
22
+ detached: process.platform !== "win32",
23
+ stdin: "ignore",
24
+ stdout: "pipe",
25
+ stderr: "pipe",
26
+ });
27
+ const controller = new AbortController();
28
+ const deadline = setTimeout(
29
+ () => controller.abort(new Error("Service state query timed out")),
30
+ timeoutMs,
31
+ );
32
+ const interrupted = Promise.withResolvers<never>();
33
+ const onAbort = () => interrupted.reject(controller.signal.reason);
34
+ controller.signal.addEventListener("abort", onAbort, { once: true });
35
+ try {
36
+ const stop = () => terminateProcessTree(child, { force: true });
37
+ const [exitCode, stdout, stderr] = await Promise.all([
38
+ Promise.race([child.exited, interrupted.promise]),
39
+ readSubprocessOutput(child.stdout, controller.signal, stop),
40
+ readSubprocessOutput(child.stderr, controller.signal, stop),
41
+ ]);
42
+ if (child.signalCode) throw new Error("Service state query interrupted");
43
+ return { exitCode, stdout, stderr };
44
+ } catch (error) {
45
+ await terminateProcessTree(child, { force: true });
46
+ throw error;
47
+ } finally {
48
+ clearTimeout(deadline);
49
+ controller.signal.removeEventListener("abort", onAbort);
50
+ }
51
+ }
52
+
53
+ export function launchdTarget(id: string) {
54
+ const domain = `gui/${typeof process.getuid === "function" ? process.getuid() : 501}`;
55
+ return {
56
+ domain,
57
+ target: `${domain}/com.mwillbanks.${id}`,
58
+ label: `com.mwillbanks.${id}`,
59
+ };
60
+ }
61
+
62
+ export async function captureServiceState(
63
+ platform: NodeJS.Platform,
64
+ id: string,
65
+ query: ServiceStateQuery,
66
+ ): Promise<ServiceState> {
67
+ const unknown = () =>
68
+ new Error(
69
+ "Cannot safely restore the observed service state; no service changes were made",
70
+ );
71
+ if (platform === "linux") {
72
+ const result = await query([
73
+ "systemctl",
74
+ "--user",
75
+ "show",
76
+ "--all",
77
+ "--property=LoadState,ActiveState,UnitFileState",
78
+ id + ".service",
79
+ ]);
80
+ const lines = result.stdout.trim().split("\n");
81
+ if (
82
+ lines.length !== 3 ||
83
+ lines.some(
84
+ (line) => !/^(LoadState|ActiveState|UnitFileState)=[a-z-]*$/.test(line),
85
+ )
86
+ )
87
+ throw unknown();
88
+ const fields = Object.fromEntries(lines.map((line) => line.split("=", 2)));
89
+ if (Object.keys(fields).length !== 3) throw unknown();
90
+ if (
91
+ [0, 4].includes(result.exitCode) &&
92
+ fields.LoadState === "not-found" &&
93
+ fields.ActiveState === "inactive" &&
94
+ fields.UnitFileState === ""
95
+ )
96
+ return {
97
+ platform: "linux",
98
+ loaded: false,
99
+ enabled: false,
100
+ active: false,
101
+ };
102
+ if (
103
+ result.exitCode !== 0 ||
104
+ fields.LoadState !== "loaded" ||
105
+ !["enabled", "disabled"].includes(fields.UnitFileState) ||
106
+ !["active", "inactive"].includes(fields.ActiveState)
107
+ )
108
+ throw unknown();
109
+ return {
110
+ platform: "linux",
111
+ loaded: true,
112
+ enabled: fields.UnitFileState === "enabled",
113
+ active: fields.ActiveState === "active",
114
+ };
115
+ }
116
+ const { domain, target, label } = launchdTarget(id);
117
+ const disabled = await query(["launchctl", "print-disabled", domain]);
118
+ if (
119
+ disabled.exitCode !== 0 ||
120
+ !/^disabled services = \{[\s\S]*\}\s*$/.test(disabled.stdout.trim())
121
+ )
122
+ throw unknown();
123
+ const overridePattern = /"([^"]+)"\s*=>\s*(true|false|enabled|disabled)/g;
124
+ const body = disabled.stdout
125
+ .trim()
126
+ .replace(/^disabled services = \{/, "")
127
+ .replace(/\}\s*$/, "");
128
+ const overrides = [...body.matchAll(overridePattern)];
129
+ if (body.replace(overridePattern, "").trim()) throw unknown();
130
+ const entries = overrides.filter((match) => match[1] === label);
131
+ if (entries.length > 1) throw unknown();
132
+ const isDisabled = ["true", "disabled"].includes(entries[0]?.[2] ?? "false");
133
+ const job = await query(["launchctl", "print", target]);
134
+ if (job.exitCode !== 0) {
135
+ if (
136
+ job.exitCode !== 113 ||
137
+ !/Could not find (?:specified )?service/i.test(job.stderr)
138
+ )
139
+ throw unknown();
140
+ return {
141
+ platform: "darwin",
142
+ loaded: false,
143
+ running: false,
144
+ disabled: isDisabled,
145
+ };
146
+ }
147
+ // bootstrap can launch RunAtLoad/KeepAlive jobs. A loaded stopped job cannot be safely reconstructed.
148
+ if (!/^\s*state = running\s*$/m.test(job.stdout) || isDisabled)
149
+ throw unknown();
150
+ return { platform: "darwin", loaded: true, running: true, disabled: false };
151
+ }
@@ -1,5 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
- import { lstat, mkdir, rm } from "node:fs/promises";
2
+ import { lstat } from "node:fs/promises";
3
3
  import { createServer } from "node:net";
4
4
  import path from "node:path";
5
5
 
@@ -7,6 +7,21 @@ import {
7
7
  readSubprocessOutput,
8
8
  terminateProcessTree,
9
9
  } from "../runtime/subprocess";
10
+ import {
11
+ captureServiceState,
12
+ queryServiceCommand,
13
+ type ServiceState,
14
+ type ServiceStateQuery,
15
+ } from "./service-state";
16
+ import {
17
+ mkdirInstallerDirectory as mkdir,
18
+ assertInstallerRestored,
19
+ readInstallerText,
20
+ onInstallerRollback,
21
+ removeInstallerFile,
22
+ withInstallerFileTransaction,
23
+ writeInstallerFile,
24
+ } from "./transaction";
10
25
  import type { HttpEndpoint } from "./transport";
11
26
 
12
27
  export type ServiceScope = "local" | "global";
@@ -15,16 +30,26 @@ export type ServiceCommandRunner = (
15
30
  ignoreFailure?: boolean,
16
31
  ) => Promise<void>;
17
32
 
18
- export interface ServiceOptions {
33
+ export type ServiceExecutionOptions<
34
+ RunnerKey extends string,
35
+ QueryKey extends string,
36
+ > =
37
+ | ({ [Key in RunnerKey]?: undefined } & {
38
+ [Key in QueryKey]?: ServiceStateQuery;
39
+ })
40
+ | ({ [Key in RunnerKey]: ServiceCommandRunner } & {
41
+ [Key in QueryKey]: ServiceStateQuery;
42
+ });
43
+
44
+ export type ServiceOptions = ServiceExecutionOptions<"runner", "stateQuery"> & {
19
45
  cliEntry: string;
20
46
  cliArgs?: string[];
21
47
  endpoint: HttpEndpoint;
22
48
  home: string;
23
49
  platform?: NodeJS.Platform;
24
50
  root: string;
25
- runner?: ServiceCommandRunner;
26
51
  scope: ServiceScope;
27
- }
52
+ };
28
53
 
29
54
  export interface ServicePlan {
30
55
  content: string;
@@ -113,7 +138,7 @@ export function createServicePlan(options: ServiceOptions): ServicePlan {
113
138
  ["launchctl", "bootstrap", domain, file],
114
139
  ["launchctl", "kickstart", "-k", `${domain}/${label}`],
115
140
  ],
116
- removeCommands: [["launchctl", "bootout", domain, file]],
141
+ removeCommands: [["launchctl", "bootout", `${domain}/${label}`]],
117
142
  };
118
143
  }
119
144
  const file = path.join(options.home, ".config/systemd/user", `${id}.service`);
@@ -236,14 +261,101 @@ export async function preflightService(options: ServiceOptions) {
236
261
  }
237
262
 
238
263
  export async function installService(options: ServiceOptions) {
264
+ return withInstallerFileTransaction(() => installServiceFiles(options));
265
+ }
266
+
267
+ async function compensateService(
268
+ options: ServiceOptions,
269
+ plan: ServicePlan,
270
+ prior: ServiceState,
271
+ existed: boolean,
272
+ ) {
273
+ // Each compensation validates its own restored dependency, even if another file conflicted.
274
+ assertInstallerRestored(plan.file);
275
+ const runner: ServiceCommandRunner = async (command, ignoreFailure) => {
276
+ assertInstallerRestored(plan.file);
277
+ await (options.runner ?? defaultRunner)(command, ignoreFailure);
278
+ };
279
+ if (prior.platform === "linux") {
280
+ const unit = plan.id + ".service";
281
+ const restore = async (command: string[]) => {
282
+ try {
283
+ await runner(command);
284
+ } catch (error) {
285
+ // A removed fresh unit may already be absent. Verify absence instead of ignoring manager errors.
286
+ assertInstallerRestored(plan.file);
287
+ const current = await priorServiceState(options, plan);
288
+ assertInstallerRestored(plan.file);
289
+ if (existed || current.platform !== "linux" || current.loaded)
290
+ throw error;
291
+ }
292
+ };
293
+ await restore(["systemctl", "--user", "stop", unit]);
294
+ await runner(["systemctl", "--user", "daemon-reload"]);
295
+ await restore([
296
+ "systemctl",
297
+ "--user",
298
+ prior.enabled ? "enable" : "disable",
299
+ unit,
300
+ ]);
301
+ if (prior.active) await runner(["systemctl", "--user", "start", unit]);
302
+ return;
303
+ }
304
+ for (const command of plan.removeCommands) {
305
+ try {
306
+ await runner(command);
307
+ } catch (error) {
308
+ assertInstallerRestored(plan.file);
309
+ const current = await priorServiceState(options, plan);
310
+ assertInstallerRestored(plan.file);
311
+ if (current.loaded) throw error;
312
+ }
313
+ }
314
+ // bootout/bootstrap do not change disabled overrides; never invent an enable override.
315
+ if (prior.loaded) {
316
+ await runner(plan.installCommands[1]);
317
+ await runner(plan.installCommands[2]);
318
+ }
319
+ }
320
+
321
+ async function priorServiceState(
322
+ options: ServiceOptions,
323
+ plan: ServicePlan,
324
+ existed = true,
325
+ ) {
326
+ if (options.runner && !options.stateQuery)
327
+ throw new Error(
328
+ "A custom service runner requires a read-only service state query",
329
+ );
330
+ const prior = await captureServiceState(
331
+ options.platform ?? process.platform,
332
+ plan.id,
333
+ options.stateQuery ?? queryServiceCommand,
334
+ );
335
+ if (!existed && prior.loaded)
336
+ throw new Error(
337
+ "Cannot restore a loaded service without its original managed service file",
338
+ );
339
+ return prior;
340
+ }
341
+
342
+ async function installServiceFiles(options: ServiceOptions) {
239
343
  const plan = await preflightService(options);
344
+ const existed = await readInstallerText(plan.file)
345
+ .then(() => true)
346
+ .catch((error) => {
347
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
348
+ throw error;
349
+ });
350
+ const prior = await priorServiceState(options, plan, existed);
240
351
  const runner = options.runner ?? defaultRunner;
241
352
  await mkdir(path.dirname(plan.file), { recursive: true });
242
353
  if ((options.platform ?? process.platform) === "darwin")
243
354
  await mkdir(path.join(options.home, ".local/state/ast-mcp"), {
244
355
  recursive: true,
245
356
  });
246
- await Bun.write(plan.file, plan.content);
357
+ await writeInstallerFile(plan.file, plan.content);
358
+ onInstallerRollback(() => compensateService(options, plan, prior, existed));
247
359
  for (let index = 0; index < plan.installCommands.length; index += 1)
248
360
  await runner(
249
361
  plan.installCommands[index],
@@ -254,10 +366,22 @@ export async function installService(options: ServiceOptions) {
254
366
  }
255
367
 
256
368
  export async function removeService(options: ServiceOptions) {
369
+ return withInstallerFileTransaction(() => removeServiceFiles(options));
370
+ }
371
+
372
+ async function removeServiceFiles(options: ServiceOptions) {
257
373
  const plan = createServicePlan(options);
374
+ const existed = await readInstallerText(plan.file)
375
+ .then(() => true)
376
+ .catch((error) => {
377
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
378
+ throw error;
379
+ });
380
+ const prior = await priorServiceState(options, plan, existed);
381
+ onInstallerRollback(() => compensateService(options, plan, prior, existed));
258
382
  const runner = options.runner ?? defaultRunner;
259
383
  for (const command of plan.removeCommands) await runner(command, true);
260
- await rm(plan.file, { force: true });
384
+ await removeInstallerFile(plan.file);
261
385
  if ((options.platform ?? process.platform) === "linux")
262
386
  await runner(["systemctl", "--user", "daemon-reload"], true);
263
387
  return plan;