@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
@@ -1,8 +1,9 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { existsSync } from "node:fs";
3
- import { lstat, mkdir, readdir, rm, writeFile } from "node:fs/promises";
3
+ import { lstat, readdir } from "node:fs/promises";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
+ import { isDeepStrictEqual } from "node:util";
6
7
 
7
8
  import {
8
9
  parseOutputArguments,
@@ -11,8 +12,10 @@ import {
11
12
  type CliOutputContext,
12
13
  } from "../cli/output";
13
14
  import { clearConfigCache, globalConfigPath, resolveConfig } from "../config";
14
- import { migrateConfigSource, writeMigratedConfig } from "../config/migrate";
15
+ import { migrateConfigSource } from "../config/migrate";
16
+ import { configWriteTarget } from "../config/transaction";
15
17
  import {
18
+ codexHome,
16
19
  codexTransport,
17
20
  installerTargetPaths,
18
21
  jsonTargetConfig,
@@ -28,15 +31,34 @@ import {
28
31
  import { withFencedFileLocks } from "../runtime/locks";
29
32
  import { pathWithin } from "../runtime/path-utils";
30
33
  import { commandForPlatform } from "../runtime/subprocess";
31
- import { enableCodexElicitation } from "./codex";
34
+ import {
35
+ enableCodexElicitation,
36
+ parseCodexConfig,
37
+ refreshCodexMcp,
38
+ removeCodexMcpConfiguration,
39
+ } from "./codex";
32
40
  import { type InstallerLaunch, verifyMcpLaunch } from "./health";
41
+ import {
42
+ launchFields,
43
+ launchReceipt,
44
+ managedToolSelection,
45
+ parseLaunchReceipt,
46
+ removeManagedEntry,
47
+ } from "./ownership";
33
48
  import {
34
49
  createServicePlan,
35
50
  installService,
36
51
  preflightService,
37
52
  removeService,
38
- type ServiceCommandRunner,
53
+ type ServiceExecutionOptions,
39
54
  } from "./service";
55
+ import {
56
+ mkdirInstallerDirectory as mkdir,
57
+ readInstallerText,
58
+ removeInstallerFile,
59
+ withInstallerFileTransaction,
60
+ writeInstallerFile,
61
+ } from "./transaction";
40
62
  import {
41
63
  type HttpEndpoint,
42
64
  httpEndpoint,
@@ -185,7 +207,7 @@ type Target = (typeof targets)[number];
185
207
 
186
208
  async function json(file: string): Promise<Record<string, any>> {
187
209
  try {
188
- const value = Bun.JSONC.parse(await Bun.file(file).text());
210
+ const value = Bun.JSONC.parse(await readInstallerText(file));
189
211
  return value as Record<string, any>;
190
212
  } catch (error) {
191
213
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
@@ -194,7 +216,37 @@ async function json(file: string): Promise<Record<string, any>> {
194
216
  }
195
217
  async function save(file: string, value: unknown) {
196
218
  await mkdir(path.dirname(file), { recursive: true });
197
- await Bun.write(file, `${JSON.stringify(value, null, 2)}\n`);
219
+ await writeInstallerFile(file, `${JSON.stringify(value, null, 2)}\n`);
220
+ }
221
+ async function readLaunchReceipt(file: string, strict = false) {
222
+ const info = await lstat(file).catch((error) => {
223
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
224
+ throw error;
225
+ });
226
+ if (!info) return undefined;
227
+ const receipt = info.isFile()
228
+ ? await json(file)
229
+ .then(parseLaunchReceipt)
230
+ .catch(() => undefined)
231
+ : undefined;
232
+ if (!receipt && strict)
233
+ throw new Error(
234
+ "Existing launch receipt is not owned by ast-mcp; preserve or relocate it before refresh",
235
+ );
236
+ return receipt;
237
+ }
238
+ async function saveLaunchReceipt(file: string, value: unknown) {
239
+ await readLaunchReceipt(file, true);
240
+ await mkdir(path.dirname(file), { recursive: true });
241
+ const previous = await lstat(file).catch((error) => {
242
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
243
+ throw error;
244
+ });
245
+ if (previous && !previous.isFile())
246
+ throw new Error("Launch receipt must be a regular file");
247
+ await writeInstallerFile(file, JSON.stringify(value, null, 2) + "\n", {
248
+ mode: previous ? previous.mode & 0o600 : 0o600,
249
+ });
198
250
  }
199
251
  function definition(
200
252
  root: string | undefined,
@@ -210,6 +262,38 @@ function definition(
210
262
  ...(root ? { cwd: root } : {}),
211
263
  };
212
264
  }
265
+ function retainedMcpSettings(
266
+ value: unknown,
267
+ ownsDefaultTools = false,
268
+ ): Record<string, unknown> {
269
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
270
+ const retained = { ...value } as Record<string, unknown>;
271
+ for (const key of launchFields) delete retained[key];
272
+ // Copilot's installer default is launch metadata, rather than customization.
273
+ if (
274
+ ownsDefaultTools &&
275
+ Array.isArray(retained.tools) &&
276
+ retained.tools.length === 1 &&
277
+ retained.tools[0] === "*"
278
+ )
279
+ delete retained.tools;
280
+ return retained;
281
+ }
282
+
283
+ async function codexProfileFiles(home: string): Promise<string[]> {
284
+ const base = codexHome(home);
285
+ const content = (await optionalText(path.join(base, "config.toml"))) ?? "";
286
+ const selected = parseCodexConfig(content).profile;
287
+ const names = [
288
+ ...content.matchAll(/^# ast-mcp:profile-file ([\w.-]{1,100})$/gm),
289
+ ].map((match) => match[1]!);
290
+ if (typeof selected === "string" && /^[\w.-]{1,100}$/.test(selected))
291
+ names.push(selected);
292
+ return [...new Set(names)].map((name) =>
293
+ path.join(base, name + ".config.toml"),
294
+ );
295
+ }
296
+
213
297
  async function codexMcp(
214
298
  file: string,
215
299
  root: string | undefined,
@@ -217,30 +301,67 @@ async function codexMcp(
217
301
  transport: McpTransport,
218
302
  endpoint?: HttpEndpoint,
219
303
  ) {
220
- const old = await Bun.file(file)
221
- .text()
222
- .catch((error) => {
223
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
224
- throw error;
225
- });
226
- const inherited = root
227
- ? await Bun.file(path.join(home, ".codex/config.toml"))
304
+ const old = await readInstallerText(file).catch((error) => {
305
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
306
+ throw error;
307
+ });
308
+ let inherited = root
309
+ ? await Bun.file(path.join(codexHome(home), "config.toml"))
228
310
  .text()
229
311
  .catch((error) => {
230
312
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
231
313
  throw error;
232
314
  })
233
315
  : "";
234
- const clean = enableCodexElicitation(old, inherited)
235
- .replace(/# ast-mcp:begin[\s\S]*?# ast-mcp:end\n?/g, "")
236
- .trimEnd();
316
+ if (root && inherited) {
317
+ const inheritedDocument = parseCodexConfig(inherited);
318
+ const selected = inheritedDocument.profile;
319
+ if (typeof selected === "string" && /^[\w.-]{1,100}$/.test(selected)) {
320
+ const profileSource = await Bun.file(
321
+ path.join(codexHome(home), `${selected}.config.toml`),
322
+ )
323
+ .text()
324
+ .catch((error) => {
325
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
326
+ throw error;
327
+ });
328
+ if (profileSource) {
329
+ const profile = parseCodexConfig(profileSource);
330
+ if (profile.approval_policy !== undefined)
331
+ inherited = Bun.TOML.stringify({
332
+ ...inheritedDocument,
333
+ approval_policy: profile.approval_policy,
334
+ });
335
+ }
336
+ }
337
+ }
237
338
  const stdio = definition(root, home, "stdio") as InstallerLaunch;
238
- const block =
339
+ const launch =
239
340
  transport === "http"
240
- ? `# ast-mcp:begin\n[mcp_servers.ast-mcp]\nurl = ${JSON.stringify(endpoint?.url)}\n# ast-mcp:end`
241
- : `# ast-mcp:begin\n[mcp_servers.ast-mcp]\ncommand = ${JSON.stringify(stdio.command)}\nargs = ${JSON.stringify(stdio.args)}${root ? `\ncwd = ${JSON.stringify(root)}` : ""}\n# ast-mcp:end`;
341
+ ? { url: endpoint?.url }
342
+ : {
343
+ command: stdio.command,
344
+ args: stdio.args,
345
+ ...(root ? { cwd: root } : {}),
346
+ };
347
+ let next = refreshCodexMcp(enableCodexElicitation(old, inherited), launch);
348
+ if (!root) {
349
+ const selected = parseCodexConfig(old).profile;
350
+ if (typeof selected === "string" && /^[\w.-]{1,100}$/.test(selected)) {
351
+ const profileFile = path.join(codexHome(home), selected + ".config.toml");
352
+ const source = await optionalText(profileFile);
353
+ if (source !== undefined) {
354
+ const enabled = enableCodexElicitation(source);
355
+ if (enabled !== source) {
356
+ await writeText(profileFile, enabled);
357
+ const marker = "# ast-mcp:profile-file " + selected;
358
+ if (!next.split("\n").includes(marker)) next = marker + "\n" + next;
359
+ }
360
+ }
361
+ }
362
+ }
242
363
  await mkdir(path.dirname(file), { recursive: true });
243
- await Bun.write(file, `${clean ? `${clean}\n\n` : ""}${block}\n`);
364
+ await writeInstallerFile(file, next, { expected: old });
244
365
  }
245
366
  async function jsonMcp(
246
367
  file: string,
@@ -251,15 +372,29 @@ async function jsonMcp(
251
372
  endpoint?: HttpEndpoint,
252
373
  ) {
253
374
  const value = await json(file);
375
+ const previous = await readLaunchReceipt(file + ".ast-mcp.json", true);
376
+ const original = value.mcpServers?.["ast-mcp"] ?? {};
377
+ const tools = copilot ? managedToolSelection(original, previous) : {};
254
378
  const entry = definition(root, home, transport, endpoint);
255
379
  value.mcpServers = {
256
380
  ...(value.mcpServers ?? {}),
257
- "ast-mcp": copilot
258
- ? transport === "stdio"
259
- ? { type: "local", ...entry, tools: ["*"] }
260
- : { ...entry, tools: ["*"] }
261
- : entry,
381
+ "ast-mcp": {
382
+ ...retainedMcpSettings(value.mcpServers?.["ast-mcp"], copilot),
383
+ ...(copilot
384
+ ? transport === "stdio"
385
+ ? {
386
+ type: "local",
387
+ ...entry,
388
+ ...tools,
389
+ }
390
+ : { ...entry, ...tools }
391
+ : entry),
392
+ },
262
393
  };
394
+ await saveLaunchReceipt(
395
+ file + ".ast-mcp.json",
396
+ launchReceipt(original, value.mcpServers["ast-mcp"], previous, copilot),
397
+ );
263
398
  await save(file, value);
264
399
  }
265
400
  async function vscodeMcp(
@@ -273,48 +408,144 @@ async function vscodeMcp(
273
408
  const entry = definition(root, home, transport, endpoint);
274
409
  value.servers = {
275
410
  ...(value.servers ?? {}),
276
- "ast-mcp": transport === "stdio" ? { type: "stdio", ...entry } : entry,
411
+ "ast-mcp": {
412
+ ...retainedMcpSettings(value.servers?.["ast-mcp"]),
413
+ ...(transport === "stdio" ? { type: "stdio", ...entry } : entry),
414
+ },
277
415
  };
416
+ await saveLaunchReceipt(
417
+ file + ".ast-mcp.json",
418
+ launchReceipt(
419
+ (await json(file)).servers?.["ast-mcp"] ?? {},
420
+ value.servers["ast-mcp"],
421
+ await readLaunchReceipt(file + ".ast-mcp.json", true),
422
+ ),
423
+ );
278
424
  await save(file, value);
279
425
  }
280
426
 
427
+ function factoryHook(
428
+ event: "PreToolUse" | "preToolUse",
429
+ command: string,
430
+ ): Record<string, any> {
431
+ return event === "preToolUse"
432
+ ? {
433
+ command,
434
+ matcher: "bash|powershell|edit|create",
435
+ timeoutSec: 10,
436
+ type: "command",
437
+ }
438
+ : {
439
+ hooks: [
440
+ {
441
+ command,
442
+ statusMessage: "Enforcing ast-mcp writes",
443
+ timeout: 10,
444
+ type: "command",
445
+ },
446
+ ],
447
+ matcher: ".*",
448
+ };
449
+ }
450
+ function retainUnmanagedHooks(
451
+ prior: unknown[],
452
+ event: "PreToolUse" | "preToolUse",
453
+ commands: string[],
454
+ ): unknown[] {
455
+ const factory = factoryHook(event, commands[0]!);
456
+ return prior.flatMap((item) => {
457
+ if (!commands.some((command) => isManagedHook(item, event, command)))
458
+ return [item];
459
+ const group = item as Record<string, any>;
460
+ if (event === "preToolUse")
461
+ return commands.includes(group.command) &&
462
+ isDeepStrictEqual({ ...group, command: commands[0] }, factory)
463
+ ? []
464
+ : [item];
465
+ const { hooks, ...metadata } = group;
466
+ const { hooks: _factoryChildren, ...factoryMetadata } = factory;
467
+ if (!isDeepStrictEqual(metadata, factoryMetadata)) return [item];
468
+ const retained = (hooks as unknown[]).filter(
469
+ (child) =>
470
+ !commands.includes(
471
+ (child as Record<string, unknown>)?.command as string,
472
+ ) ||
473
+ !isDeepStrictEqual(
474
+ { ...(child as Record<string, unknown>), command: commands[0] },
475
+ factory.hooks[0],
476
+ ),
477
+ );
478
+ return retained.length ? [{ ...group, hooks: retained }] : [];
479
+ });
480
+ }
481
+ function refreshManagedHooks(
482
+ prior: unknown[],
483
+ event: "PreToolUse" | "preToolUse",
484
+ command: string,
485
+ ): unknown[] {
486
+ const factory = factoryHook(event, command);
487
+ let found = false;
488
+ const refreshed = prior.map((item) => {
489
+ if (!isManagedHook(item, event, command)) return item;
490
+ const group = item as Record<string, any>;
491
+ if (event === "preToolUse") {
492
+ if (group.command === command) {
493
+ found = true;
494
+ return item;
495
+ }
496
+ if (isDeepStrictEqual({ ...group, command }, factory)) {
497
+ found = true;
498
+ return { ...group, command };
499
+ }
500
+ return item;
501
+ }
502
+ const current = group.hooks.some(
503
+ (child: Record<string, unknown>) => child?.command === command,
504
+ );
505
+ if (current) {
506
+ found = true;
507
+ return item;
508
+ }
509
+ if (
510
+ group.hooks.length === 1 &&
511
+ isDeepStrictEqual(
512
+ {
513
+ ...group,
514
+ hooks: [{ ...group.hooks[0], command }],
515
+ },
516
+ factory,
517
+ )
518
+ ) {
519
+ found = true;
520
+ return { ...group, hooks: [{ ...group.hooks[0], command }] };
521
+ }
522
+ return item;
523
+ });
524
+ let keptFactory = false;
525
+ const unique = refreshed.filter((item) => {
526
+ if (!isDeepStrictEqual(item, factory)) return true;
527
+ if (keptFactory) return false;
528
+ keptFactory = true;
529
+ return true;
530
+ });
531
+ return found ? unique : [...unique, factory];
532
+ }
533
+ function hookCommand(commandPath: string): string {
534
+ return /\.[cm]?[jt]s$/u.test(commandPath)
535
+ ? `${JSON.stringify(process.execPath)} ${JSON.stringify(commandPath)} hook`
536
+ : `${JSON.stringify(commandPath)} hook`;
537
+ }
281
538
  async function hook(
282
539
  file: string,
283
540
  event: "PreToolUse" | "preToolUse",
284
- scriptFile: string,
285
541
  commandPath: string,
286
542
  ) {
287
- await rm(scriptFile, { force: true });
288
543
  const value = await json(file);
289
544
  if (event === "preToolUse") value.version ??= 1;
290
545
  value.hooks ??= {};
291
546
  const prior = Array.isArray(value.hooks[event]) ? value.hooks[event] : [];
292
- const command = /\.[cm]?[jt]s$/u.test(commandPath)
293
- ? `${JSON.stringify(process.execPath)} ${JSON.stringify(commandPath)} hook`
294
- : `${JSON.stringify(commandPath)} hook`;
295
- const kept = prior.filter(
296
- (item: unknown) => !isManagedHook(item, event, command),
297
- );
298
- const item =
299
- event === "preToolUse"
300
- ? {
301
- command,
302
- matcher: "bash|powershell|edit|create",
303
- timeoutSec: 10,
304
- type: "command",
305
- }
306
- : {
307
- hooks: [
308
- {
309
- command,
310
- statusMessage: "Enforcing ast-mcp writes",
311
- timeout: 10,
312
- type: "command",
313
- },
314
- ],
315
- matcher: ".*",
316
- };
317
- value.hooks[event] = [...kept, item];
547
+ const command = hookCommand(commandPath);
548
+ value.hooks[event] = refreshManagedHooks(prior, event, command);
318
549
  await save(file, value);
319
550
  }
320
551
  const instructionsBegin = "<!-- ast-mcp:begin -->";
@@ -325,16 +556,17 @@ const instructionsPattern =
325
556
  async function writeText(file: string, content: string) {
326
557
  const normalized = content.trimEnd();
327
558
  await mkdir(path.dirname(file), { recursive: true });
328
- await Bun.write(file, normalized ? `${normalized}\n` : "");
559
+ await writeInstallerFile(file, normalized ? `${normalized}\n` : "");
329
560
  }
330
561
 
331
562
  async function instructions(file: string) {
332
563
  const block = (
333
564
  await Bun.file(path.join(packageRoot, "templates/AGENTS.md")).text()
334
565
  ).trim();
335
- const old = await Bun.file(file)
336
- .text()
337
- .catch(() => "");
566
+ const old = await readInstallerText(file).catch((error) => {
567
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return "";
568
+ throw error;
569
+ });
338
570
  const clean = old.replace(instructionsPattern, "").trimEnd();
339
571
  await writeText(
340
572
  file,
@@ -343,12 +575,10 @@ async function instructions(file: string) {
343
575
  }
344
576
 
345
577
  async function optionalText(file: string) {
346
- return Bun.file(file)
347
- .text()
348
- .catch((error) => {
349
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
350
- throw error;
351
- });
578
+ return readInstallerText(file).catch((error) => {
579
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
580
+ throw error;
581
+ });
352
582
  }
353
583
 
354
584
  async function removeInstructions(file: string) {
@@ -366,38 +596,36 @@ async function removeJsonMcp(file: string, section = "mcpServers") {
366
596
  const entries = value[section];
367
597
  if (!entries || typeof entries !== "object" || !("ast-mcp" in entries))
368
598
  return;
369
- delete entries["ast-mcp"];
599
+ const receipt = await readLaunchReceipt(file + ".ast-mcp.json");
600
+ if (!receipt) return;
601
+ const retained = removeManagedEntry(entries["ast-mcp"], receipt);
602
+ if (retained) entries["ast-mcp"] = retained;
603
+ else delete entries["ast-mcp"];
370
604
  if (Object.keys(entries).length === 0) delete value[section];
371
605
  await saveRemainingJson(file, value);
606
+ await removeInstallerFile(file + ".ast-mcp.json");
372
607
  }
373
608
 
374
609
  async function removeCodexMcp(file: string) {
375
610
  const old = await optionalText(file);
376
611
  if (old === undefined) return;
377
- await writeText(
378
- file,
379
- old.replace(/# ast-mcp:begin[\s\S]*?# ast-mcp:end\n?/g, ""),
380
- );
612
+ await writeText(file, removeCodexMcpConfiguration(old));
381
613
  }
382
614
 
383
615
  async function removeHook(
384
616
  file: string,
385
617
  event: "PreToolUse" | "preToolUse",
386
- commandPath: string,
387
618
  cliAlias: string,
388
619
  ) {
389
620
  const value = await json(file);
390
621
  const hooks = value.hooks;
391
622
  if (!hooks || !Array.isArray(hooks[event])) return;
392
623
  const commands = [
393
- `bun ${JSON.stringify(commandPath)}`,
624
+ hookCommand(cliAlias),
394
625
  `bun ${JSON.stringify(cliEntry)} hook`,
395
626
  `${JSON.stringify(cliAlias)} hook`,
396
627
  ];
397
- hooks[event] = hooks[event].filter(
398
- (item: unknown) =>
399
- !commands.some((command) => isManagedHook(item, event, command)),
400
- );
628
+ hooks[event] = retainUnmanagedHooks(hooks[event], event, commands);
401
629
  if (hooks[event].length === 0) delete hooks[event];
402
630
  if (Object.keys(hooks).length === 0) delete value.hooks;
403
631
  await saveRemainingJson(file, value);
@@ -416,7 +644,10 @@ async function hasLocalInstallation(root: string) {
416
644
  );
417
645
  }
418
646
 
419
- export interface InstallOptions {
647
+ export type InstallOptions = ServiceExecutionOptions<
648
+ "serviceRunner",
649
+ "serviceStateQuery"
650
+ > & {
420
651
  cliEntry?: string;
421
652
  verifyLaunch?: (launch: InstallerLaunch) => Promise<void>;
422
653
  deprecatedRoot?: boolean;
@@ -428,10 +659,9 @@ export interface InstallOptions {
428
659
  root: string;
429
660
  scope: "local" | "global";
430
661
  service?: boolean;
431
- serviceRunner?: ServiceCommandRunner;
432
662
  targets: Target[];
433
663
  transport?: McpTransport;
434
- }
664
+ };
435
665
 
436
666
  class InstallerUsageError extends Error {
437
667
  override name = "InstallerUsageError";
@@ -444,7 +674,7 @@ async function targetTransport(
444
674
  home: string,
445
675
  ): Promise<McpTransport | undefined> {
446
676
  if (target === "codex") {
447
- const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
677
+ const base = global ? codexHome(home) : path.join(root, ".codex");
448
678
  const content = await Bun.file(path.join(base, "config.toml"))
449
679
  .text()
450
680
  .catch(() => "");
@@ -487,6 +717,9 @@ function serviceConfiguration(options: InstallOptions, endpoint: HttpEndpoint) {
487
717
  const home = options.home ?? os.homedir();
488
718
  const entry = cliEntryFor(options.scope === "local" ? root : undefined, home);
489
719
  const invocation = cliInvocation(path.resolve(root, entry), []);
720
+ const execution = options.serviceRunner
721
+ ? { runner: options.serviceRunner, stateQuery: options.serviceStateQuery }
722
+ : { stateQuery: options.serviceStateQuery };
490
723
  return {
491
724
  cliEntry: invocation.command,
492
725
  cliArgs: invocation.args,
@@ -494,7 +727,7 @@ function serviceConfiguration(options: InstallOptions, endpoint: HttpEndpoint) {
494
727
  home,
495
728
  platform: options.platform,
496
729
  root,
497
- runner: options.serviceRunner,
730
+ ...execution,
498
731
  scope: options.scope,
499
732
  };
500
733
  }
@@ -516,7 +749,17 @@ function targetPaths(
516
749
  root: string,
517
750
  home: string,
518
751
  ) {
519
- return installerTargetPaths(target, global, root, home);
752
+ const paths = installerTargetPaths(target, global, root, home);
753
+ const configs =
754
+ target === "codex"
755
+ ? []
756
+ : [
757
+ jsonTargetConfig(target, global, root, home),
758
+ ...(target === "copilot" && !global
759
+ ? [path.join(root, ".vscode/mcp.json")]
760
+ : []),
761
+ ];
762
+ return [...paths, ...configs.map((file) => file + ".ast-mcp.json")];
520
763
  }
521
764
 
522
765
  async function snapshot(paths: string[]) {
@@ -556,7 +799,7 @@ async function installCodexTarget(
556
799
  transport: McpTransport,
557
800
  endpoint?: HttpEndpoint,
558
801
  ) {
559
- const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
802
+ const base = global ? codexHome(home) : path.join(root, ".codex");
560
803
  await codexMcp(
561
804
  path.join(base, "config.toml"),
562
805
  global ? undefined : root,
@@ -567,7 +810,6 @@ async function installCodexTarget(
567
810
  await hook(
568
811
  path.join(base, "hooks.json"),
569
812
  "PreToolUse",
570
- path.join(base, "hooks/ast-mcp.ts"),
571
813
  cliEntryFor(global ? undefined : root, home),
572
814
  );
573
815
  await installTargetAssets(
@@ -595,7 +837,6 @@ async function installClaudeTarget(
595
837
  await hook(
596
838
  path.join(base, "settings.json"),
597
839
  "PreToolUse",
598
- path.join(base, "hooks/ast-mcp.ts"),
599
840
  cliEntryFor(global ? undefined : root, home),
600
841
  );
601
842
  await installTargetAssets(
@@ -643,7 +884,6 @@ async function installCopilotTarget(
643
884
  await hook(
644
885
  path.join(base, "hooks/ast-mcp.json"),
645
886
  "preToolUse",
646
- path.join(base, "hooks/ast-mcp.ts"),
647
887
  cliEntryFor(global ? undefined : root, home),
648
888
  );
649
889
  await installTargetAssets(
@@ -795,12 +1035,12 @@ async function ensureInstallerConfig(
795
1035
  home: string,
796
1036
  ) {
797
1037
  const file = installerConfigPath(options, root, home);
798
- const existing = await Bun.file(file)
799
- .text()
800
- .catch((error) => {
801
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
802
- throw error;
803
- });
1038
+ await mkdir(path.dirname(file), { recursive: true });
1039
+ const { target, mode } = await configWriteTarget(file, true);
1040
+ const existing = await readInstallerText(target).catch((error) => {
1041
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
1042
+ throw error;
1043
+ });
804
1044
  clearConfigCache();
805
1045
  await resolveConfig({
806
1046
  cwd: options.scope === "local" ? root : home,
@@ -809,9 +1049,15 @@ async function ensureInstallerConfig(
809
1049
  });
810
1050
  if (existing === undefined) {
811
1051
  await mkdir(path.dirname(file), { recursive: true });
812
- await writeFile(file, installerConfigSeed(options.scope === "local"), {
813
- flag: "wx",
814
- });
1052
+ await writeInstallerFile(
1053
+ target,
1054
+ installerConfigSeed(options.scope === "local"),
1055
+ {
1056
+ exclusive: true,
1057
+ mode,
1058
+ configuration: file,
1059
+ },
1060
+ );
815
1061
  } else {
816
1062
  let migration: ReturnType<typeof migrateConfigSource>;
817
1063
  try {
@@ -821,8 +1067,22 @@ async function ensureInstallerConfig(
821
1067
  `invalid configuration: ${error instanceof Error ? error.message : String(error)}`,
822
1068
  );
823
1069
  }
824
- if (migration.changed)
825
- await writeMigratedConfig(file, migration.source, true, existing);
1070
+ if (migration.changed) {
1071
+ const backup = file + ".v1.bak";
1072
+ const backupInfo = await lstat(backup).catch((error) => {
1073
+ if ((error as NodeJS.ErrnoException).code === "ENOENT")
1074
+ return undefined;
1075
+ throw error;
1076
+ });
1077
+ await writeInstallerFile(backup, existing, {
1078
+ mode: (backupInfo?.mode ?? mode) & 0o777,
1079
+ });
1080
+ await writeInstallerFile(target, migration.source, {
1081
+ expected: existing,
1082
+ mode: mode & 0o777,
1083
+ configuration: file,
1084
+ });
1085
+ }
826
1086
  }
827
1087
  clearConfigCache();
828
1088
  await resolveConfig({
@@ -893,7 +1153,7 @@ async function recordSourceLaunch(
893
1153
  });
894
1154
  }
895
1155
 
896
- function reconcilePaths(
1156
+ async function reconcilePaths(
897
1157
  options: InstallOptions,
898
1158
  global: boolean,
899
1159
  root: string,
@@ -904,6 +1164,8 @@ function reconcilePaths(
904
1164
  const paths = options.targets.flatMap((target) =>
905
1165
  targetPaths(target, global, root, home),
906
1166
  );
1167
+ if (global && options.targets.includes("codex"))
1168
+ paths.push(...(await codexProfileFiles(home)));
907
1169
  paths.push(installerConfigPath(options, root, home));
908
1170
  if (usesSourceLaunch(options))
909
1171
  paths.push(sourceLaunchReceiptPath(root, home));
@@ -947,7 +1209,7 @@ async function withInstallerLocks<T>(
947
1209
  path.join(root, ".ast-mcp-installation"),
948
1210
  path.join(home, ".ast-mcp-installation"),
949
1211
  ],
950
- operation,
1212
+ () => withInstallerFileTransaction(operation).finally(clearConfigCache),
951
1213
  { deadline: Date.now() + 10_000 },
952
1214
  );
953
1215
  }
@@ -973,7 +1235,7 @@ async function reconcile(
973
1235
  ...(!global ? { cwd: root } : {}),
974
1236
  };
975
1237
  await (options.verifyLaunch ?? verifyMcpLaunch)(launch);
976
- const paths = reconcilePaths(
1238
+ const paths = await reconcilePaths(
977
1239
  options,
978
1240
  global,
979
1241
  root,
@@ -981,6 +1243,10 @@ async function reconcile(
981
1243
  transport,
982
1244
  undefined,
983
1245
  );
1246
+ for (const file of paths.filter((candidate) =>
1247
+ candidate.endsWith(".ast-mcp.json"),
1248
+ ))
1249
+ await readLaunchReceipt(file, true);
984
1250
  const before = await snapshot(paths);
985
1251
  if (transport === "http" && options.service === true) {
986
1252
  const endpoint = await resolveInstallerEndpoint({
@@ -1013,8 +1279,7 @@ export async function update(options: InstallOptions) {
1013
1279
  return withInstallerLocks(options, () => reconcile(options, "update"));
1014
1280
  }
1015
1281
 
1016
- async function removeTargetAssets(base: string, instructionsPath?: string) {
1017
- await rm(path.join(base, "hooks/ast-mcp.ts"), { force: true });
1282
+ async function removeTargetAssets(instructionsPath?: string) {
1018
1283
  if (instructionsPath) await removeInstructions(instructionsPath);
1019
1284
  }
1020
1285
 
@@ -1023,18 +1288,25 @@ async function uninstallCodexTarget(
1023
1288
  root: string,
1024
1289
  home: string,
1025
1290
  ) {
1026
- const base = global ? path.join(home, ".codex") : path.join(root, ".codex");
1291
+ const base = global ? codexHome(home) : path.join(root, ".codex");
1292
+ if (global) {
1293
+ for (const profileFile of await codexProfileFiles(home))
1294
+ await removeCodexMcp(profileFile);
1295
+ const config = path.join(base, "config.toml");
1296
+ const old = await optionalText(config);
1297
+ if (old !== undefined)
1298
+ await writeText(
1299
+ config,
1300
+ old.replace(/^# ast-mcp:profile-file [\w.-]{1,100}\r?\n/gm, ""),
1301
+ );
1302
+ }
1027
1303
  await removeCodexMcp(path.join(base, "config.toml"));
1028
1304
  await removeHook(
1029
1305
  path.join(base, "hooks.json"),
1030
1306
  "PreToolUse",
1031
- global ? path.join(base, "hooks/ast-mcp.ts") : ".codex/hooks/ast-mcp.ts",
1032
1307
  cliEntryFor(global ? undefined : root, home),
1033
1308
  );
1034
- await removeTargetAssets(
1035
- base,
1036
- global ? path.join(base, "AGENTS.md") : undefined,
1037
- );
1309
+ await removeTargetAssets(global ? path.join(base, "AGENTS.md") : undefined);
1038
1310
  }
1039
1311
 
1040
1312
  async function uninstallClaudeTarget(
@@ -1049,15 +1321,9 @@ async function uninstallClaudeTarget(
1049
1321
  await removeHook(
1050
1322
  path.join(base, "settings.json"),
1051
1323
  "PreToolUse",
1052
- global
1053
- ? path.join(base, "hooks/ast-mcp.ts")
1054
- : `\${CLAUDE_PROJECT_DIR}/.claude/hooks/ast-mcp.ts`,
1055
1324
  cliEntryFor(global ? undefined : root, home),
1056
1325
  );
1057
- await removeTargetAssets(
1058
- base,
1059
- global ? path.join(base, "CLAUDE.md") : undefined,
1060
- );
1326
+ await removeTargetAssets(global ? path.join(base, "CLAUDE.md") : undefined);
1061
1327
  }
1062
1328
 
1063
1329
  async function uninstallCopilotTarget(
@@ -1068,19 +1334,18 @@ async function uninstallCopilotTarget(
1068
1334
  const base = global
1069
1335
  ? path.join(home, ".copilot")
1070
1336
  : path.join(root, ".github");
1071
- if (global) await removeJsonMcp(path.join(base, "mcp-config.json"));
1337
+ if (global)
1338
+ await removeJsonMcp(path.join(base, "mcp-config.json"), "mcpServers");
1072
1339
  else {
1073
- await removeJsonMcp(path.join(root, ".github/mcp.json"));
1340
+ await removeJsonMcp(path.join(root, ".github/mcp.json"), "mcpServers");
1074
1341
  await removeJsonMcp(path.join(root, ".vscode/mcp.json"), "servers");
1075
1342
  }
1076
1343
  await removeHook(
1077
1344
  path.join(base, "hooks/ast-mcp.json"),
1078
1345
  "preToolUse",
1079
- global ? path.join(base, "hooks/ast-mcp.ts") : ".github/hooks/ast-mcp.ts",
1080
1346
  cliEntryFor(global ? undefined : root, home),
1081
1347
  );
1082
1348
  await removeTargetAssets(
1083
- base,
1084
1349
  global ? path.join(base, "copilot-instructions.md") : undefined,
1085
1350
  );
1086
1351
  }
@@ -1128,6 +1393,8 @@ async function uninstallLocked(options: InstallOptions) {
1128
1393
  const paths = options.targets.flatMap((target) =>
1129
1394
  targetPaths(target, global, root, home),
1130
1395
  );
1396
+ if (global && options.targets.includes("codex"))
1397
+ paths.push(...(await codexProfileFiles(home)));
1131
1398
  const before = await snapshot(paths);
1132
1399
  for (const target of options.targets)
1133
1400
  await uninstallTarget(target, global, root, home);