claude.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /**
  2. * Claude Code target. Writes:
  3. *
  4. * - MCP server entry to `~/.claude.json` (global = user scope, loads
  5. * in every project) or `./.mcp.json` (local = project scope, the
  6. * file Claude Code actually reads for a single project). See the
  7. * scope table at https://code.claude.com/docs/en/mcp.
  8. * - Permissions to `~/.claude/settings.json` (global) or
  9. * `./.claude/settings.json` (local), gated on `autoAllow`.
  10. * - Instructions to `~/.claude/CLAUDE.md` (global) or
  11. * `./.claude/CLAUDE.md` (local).
  12. *
  13. * Earlier versions wrote the local MCP entry to `./.claude.json` — a
  14. * file Claude Code never reads — so the server silently never loaded
  15. * until the user manually renamed it to `.mcp.json` (issue #207). We
  16. * now write `./.mcp.json` and migrate any stale `./.claude.json` entry
  17. * out of the way on install and uninstall.
  18. */
  19. import * as fs from 'fs';
  20. import * as path from 'path';
  21. import * as os from 'os';
  22. import {
  23. AgentTarget,
  24. DetectionResult,
  25. InstallOptions,
  26. Location,
  27. WriteResult,
  28. } from './types';
  29. import {
  30. getCodeGraphPermissions,
  31. getMcpServerConfig,
  32. jsonDeepEqual,
  33. readJsonFile,
  34. removeMarkedSection,
  35. writeJsonFile,
  36. upsertInstructionsEntry,
  37. } from './shared';
  38. import {
  39. CODEGRAPH_SECTION_END,
  40. CODEGRAPH_SECTION_START,
  41. } from '../instructions-template';
  42. function configDir(loc: Location): string {
  43. return loc === 'global'
  44. ? path.join(os.homedir(), '.claude')
  45. : path.join(process.cwd(), '.claude');
  46. }
  47. function mcpJsonPath(loc: Location): string {
  48. // global → ~/.claude.json (user scope: visible in every project).
  49. // local → ./.mcp.json (project scope: the ONLY project-level MCP
  50. // file Claude Code reads — NOT ./.claude.json, which it ignores).
  51. return loc === 'global'
  52. ? path.join(os.homedir(), '.claude.json')
  53. : path.join(process.cwd(), '.mcp.json');
  54. }
  55. /**
  56. * Where pre-#207 installers wrote the local MCP entry. Claude Code
  57. * never reads a project-level `./.claude.json`, so we migrate the
  58. * codegraph entry out of it on install and strip it on uninstall.
  59. * Only the project-local path is legacy — global `~/.claude.json` is
  60. * the correct user-scope location and is left untouched.
  61. */
  62. function legacyLocalMcpPath(): string {
  63. return path.join(process.cwd(), '.claude.json');
  64. }
  65. function settingsJsonPath(loc: Location): string {
  66. return path.join(configDir(loc), 'settings.json');
  67. }
  68. function instructionsPath(loc: Location): string {
  69. return path.join(configDir(loc), 'CLAUDE.md');
  70. }
  71. class ClaudeCodeTarget implements AgentTarget {
  72. readonly id = 'claude' as const;
  73. readonly displayName = 'Claude Code';
  74. readonly docsUrl = 'https://docs.claude.com/en/docs/claude-code';
  75. supportsLocation(_loc: Location): boolean {
  76. return true;
  77. }
  78. detect(loc: Location): DetectionResult {
  79. const mcpPath = mcpJsonPath(loc);
  80. const config = readJsonFile(mcpPath);
  81. const alreadyConfigured = !!config.mcpServers?.codegraph;
  82. // For "installed" we infer from the existence of either the dir
  83. // (global) or the project marker file (local). Cheap and avoids
  84. // shelling out to `claude --version`.
  85. const installed = loc === 'global'
  86. ? fs.existsSync(configDir(loc)) || fs.existsSync(mcpPath)
  87. : fs.existsSync(mcpPath) || fs.existsSync(configDir(loc));
  88. return { installed, alreadyConfigured, configPath: mcpPath };
  89. }
  90. install(loc: Location, opts: InstallOptions): WriteResult {
  91. const files: WriteResult['files'] = [];
  92. // 1. MCP server entry
  93. files.push(writeMcpEntry(loc));
  94. // 1b. Migrate away any stale ./.claude.json left by a pre-#207
  95. // local install, so the project isn't left with two competing
  96. // (one dead) MCP configs.
  97. if (loc === 'local') {
  98. const migrated = cleanupLegacyLocalMcp();
  99. if (migrated) files.push(migrated);
  100. }
  101. // 2. Permissions (only when autoAllow)
  102. if (opts.autoAllow) {
  103. files.push(writePermissionsEntry(loc));
  104. }
  105. // 2b. Strip stale auto-sync hooks left by a pre-0.8 install. Those
  106. // versions wrote `codegraph mark-dirty` / `sync-if-dirty` hooks to
  107. // settings.json; both subcommands are gone from the CLI, so the
  108. // Stop hook now fails every turn with "unknown command
  109. // 'sync-if-dirty'". Cleaning up on install makes an upgrade
  110. // self-healing. Only surfaced when something was actually removed.
  111. const hookCleanup = cleanupLegacyHooks(loc);
  112. if (hookCleanup.action === 'removed') files.push(hookCleanup);
  113. // 2c. Front-load prompt hook (Claude UserPromptSubmit). Opt-in via the
  114. // installer prompt (default-yes): `promptHook === true` writes it;
  115. // `=== false` strips any a prior install wrote so opting out round-trips
  116. // (and an upgrade re-run honors the new choice); `undefined` leaves it
  117. // untouched for callers that don't manage it.
  118. if (opts.promptHook === true) {
  119. files.push(writePromptHookEntry(loc));
  120. } else if (opts.promptHook === false) {
  121. const removed = removePromptHookEntry(loc);
  122. if (removed.action === 'removed') files.push(removed);
  123. }
  124. // 3. CLAUDE.md instructions — the short marker-fenced CodeGraph
  125. // block (#704). The MCP initialize instructions reach only the main
  126. // agent; CLAUDE.md is what Task-tool subagents (and non-MCP
  127. // harnesses) actually see, so the block carries the codegraph
  128. // pointers there. Upsert self-heals a stale pre-#529 long block.
  129. files.push(upsertInstructionsEntry(instructionsPath(loc)));
  130. return { files };
  131. }
  132. uninstall(loc: Location): WriteResult {
  133. const files: WriteResult['files'] = [];
  134. // 1. MCP server entry
  135. const mcpPath = mcpJsonPath(loc);
  136. const config = readJsonFile(mcpPath);
  137. if (config.mcpServers?.codegraph) {
  138. delete config.mcpServers.codegraph;
  139. if (Object.keys(config.mcpServers).length === 0) {
  140. delete config.mcpServers;
  141. }
  142. writeJsonFile(mcpPath, config);
  143. files.push({ path: mcpPath, action: 'removed' });
  144. } else {
  145. files.push({ path: mcpPath, action: 'not-found' });
  146. }
  147. // 1b. Also strip the codegraph entry from a legacy ./.claude.json
  148. // so uninstall fully reverses a pre-#207 local install.
  149. if (loc === 'local') {
  150. const migrated = cleanupLegacyLocalMcp();
  151. if (migrated) files.push(migrated);
  152. }
  153. // 2. Permissions
  154. const settingsPath = settingsJsonPath(loc);
  155. const settings = readJsonFile(settingsPath);
  156. if (Array.isArray(settings.permissions?.allow)) {
  157. const before = settings.permissions.allow.length;
  158. settings.permissions.allow = settings.permissions.allow.filter(
  159. (p: string) => !p.startsWith('mcp__codegraph__'),
  160. );
  161. if (settings.permissions.allow.length !== before) {
  162. if (settings.permissions.allow.length === 0) {
  163. delete settings.permissions.allow;
  164. }
  165. if (Object.keys(settings.permissions).length === 0) {
  166. delete settings.permissions;
  167. }
  168. writeJsonFile(settingsPath, settings);
  169. files.push({ path: settingsPath, action: 'removed' });
  170. } else {
  171. files.push({ path: settingsPath, action: 'not-found' });
  172. }
  173. } else {
  174. files.push({ path: settingsPath, action: 'not-found' });
  175. }
  176. // 2b. Strip any stale auto-sync hooks a pre-0.8 install left in
  177. // settings.json. The hook-cleanup step was lost when the installer
  178. // moved to the per-target architecture; restoring it here means
  179. // uninstall — and the npm `preuninstall` hook that drives it — fully
  180. // reverses a legacy install.
  181. const hookCleanup = cleanupLegacyHooks(loc);
  182. if (hookCleanup.action === 'removed') files.push(hookCleanup);
  183. // 2c. Remove the front-load prompt hook this installer may have written.
  184. const promptHookCleanup = removePromptHookEntry(loc);
  185. if (promptHookCleanup.action === 'removed') files.push(promptHookCleanup);
  186. // 3. Instructions — strip the legacy CodeGraph block if present.
  187. files.push(removeInstructionsEntry(loc));
  188. return { files };
  189. }
  190. printConfig(loc: Location): string {
  191. const target = mcpJsonPath(loc);
  192. const snippet = JSON.stringify({ mcpServers: { codegraph: getMcpServerConfig() } }, null, 2);
  193. return `# Add to ${target}\n\n${snippet}\n`;
  194. }
  195. describePaths(loc: Location): string[] {
  196. return [mcpJsonPath(loc), settingsJsonPath(loc), instructionsPath(loc)];
  197. }
  198. }
  199. /**
  200. * Per-file write helpers, exported so the legacy `config-writer.ts`
  201. * shim can call only the named operation (writeMcpConfig writes ONLY
  202. * the MCP entry, etc.) instead of `claudeTarget.install()` which
  203. * writes all three files. Without this split the shims silently
  204. * cause side effects callers don't expect.
  205. */
  206. export function writeMcpEntry(loc: Location): WriteResult['files'][number] {
  207. const file = mcpJsonPath(loc);
  208. const existing = readJsonFile(file);
  209. const before = existing.mcpServers?.codegraph;
  210. const after = getMcpServerConfig();
  211. if (jsonDeepEqual(before, after)) {
  212. // Already exactly what we'd write — preserve byte-identical file.
  213. return { path: file, action: 'unchanged' };
  214. }
  215. // 'created' here means: the file itself did not exist before this
  216. // write. A pre-existing MCP JSON file (`~/.claude.json` globally,
  217. // `./.mcp.json` locally) containing other MCP servers (no
  218. // `codegraph` key) is 'updated', not 'created' — we're adding an
  219. // entry to a file that was already there. Codex uses a different
  220. // idiom (empty-content => 'created') because its config.toml is
  221. // ours alone to manage.
  222. const action: 'created' | 'updated' = before ? 'updated' : (fs.existsSync(file) ? 'updated' : 'created');
  223. if (!existing.mcpServers) existing.mcpServers = {};
  224. existing.mcpServers.codegraph = after;
  225. writeJsonFile(file, existing);
  226. return { path: file, action };
  227. }
  228. /**
  229. * Strip the codegraph entry from a legacy project-local
  230. * `./.claude.json` (written by pre-#207 installers, which Claude Code
  231. * never read). Surgical: only our `codegraph` key is removed; sibling
  232. * MCP servers and any unrelated keys are preserved, and the file is
  233. * deleted only when removal leaves it completely empty. Returns the
  234. * file action for reporting, or `null` when there's nothing to migrate.
  235. */
  236. function cleanupLegacyLocalMcp(): WriteResult['files'][number] | null {
  237. const file = legacyLocalMcpPath();
  238. if (!fs.existsSync(file)) return null;
  239. const config = readJsonFile(file);
  240. if (!config.mcpServers?.codegraph) return null;
  241. delete config.mcpServers.codegraph;
  242. if (Object.keys(config.mcpServers).length === 0) delete config.mcpServers;
  243. if (Object.keys(config).length === 0) {
  244. try { fs.unlinkSync(file); } catch { /* ignore */ }
  245. } else {
  246. writeJsonFile(file, config);
  247. }
  248. return { path: file, action: 'removed' };
  249. }
  250. /**
  251. * True when a Claude Code hook `command` is one of the auto-sync hooks
  252. * a pre-0.8 install wrote. Those installers added
  253. * `PostToolUse(Edit|Write) → codegraph mark-dirty` and
  254. * `Stop → codegraph sync-if-dirty` (local builds used the
  255. * `npx @colbymchenry/codegraph …` form, which still contains the
  256. * `codegraph <subcommand>` substring). Both subcommands were later
  257. * removed from the CLI, so the Stop hook fails every turn with
  258. * "unknown command 'sync-if-dirty'". Matching on the codegraph-scoped
  259. * subcommand keeps unrelated user hooks (e.g. GitKraken's
  260. * `gk ai hook run`) untouched.
  261. */
  262. function isLegacyCodegraphHookCommand(command: unknown): boolean {
  263. if (typeof command !== 'string') return false;
  264. return (
  265. command.includes('codegraph mark-dirty') ||
  266. command.includes('codegraph sync-if-dirty')
  267. );
  268. }
  269. /**
  270. * The front-load prompt-hook command the installer writes into Claude's
  271. * `UserPromptSubmit` (see writePromptHookEntry). Matched by substring so an
  272. * `npx @colbymchenry/codegraph prompt-hook` form is recognized too.
  273. */
  274. const PROMPT_HOOK_COMMAND = 'codegraph prompt-hook';
  275. function isPromptHookCommand(command: unknown): boolean {
  276. return typeof command === 'string' && command.includes(PROMPT_HOOK_COMMAND);
  277. }
  278. /**
  279. * Remove stale codegraph auto-sync hooks from Claude `settings.json`.
  280. *
  281. * Surgical at the individual-command level: only entries matching
  282. * `isLegacyCodegraphHookCommand` are dropped, so a sibling hook sharing
  283. * a matcher group (or the Stop event) with ours survives. We prune a
  284. * matcher group only once its `hooks` array is empty, an event only
  285. * once it has no groups left, and `hooks` itself only once every event
  286. * is gone — and none of that runs unless we actually removed a
  287. * codegraph command, so a settings.json with no legacy hooks is left
  288. * byte-for-byte untouched and reported `unchanged`.
  289. *
  290. * Exported so it can be unit-tested directly and reused by both
  291. * `install` (an upgrade self-heals) and `uninstall`.
  292. */
  293. function removeHookCommandsMatching(
  294. loc: Location,
  295. match: (command: unknown) => boolean,
  296. ): WriteResult['files'][number] {
  297. const file = settingsJsonPath(loc);
  298. if (!fs.existsSync(file)) return { path: file, action: 'not-found' };
  299. const settings = readJsonFile(file);
  300. const hooks = settings.hooks;
  301. if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) {
  302. return { path: file, action: 'unchanged' };
  303. }
  304. // Pass 1: drop matching command(s) from inside every matcher group.
  305. let removedAny = false;
  306. for (const event of Object.keys(hooks)) {
  307. const groups = hooks[event];
  308. if (!Array.isArray(groups)) continue;
  309. for (const group of groups) {
  310. if (!group || !Array.isArray(group.hooks)) continue;
  311. const before = group.hooks.length;
  312. group.hooks = group.hooks.filter((h: any) => !match(h?.command));
  313. if (group.hooks.length !== before) removedAny = true;
  314. }
  315. }
  316. if (!removedAny) return { path: file, action: 'unchanged' };
  317. // Pass 2: prune empty matcher groups, then events with no groups left,
  318. // then an empty top-level `hooks`. Guarded by `removedAny` so we never
  319. // restructure a settings.json that had no matching hooks. Sibling hooks
  320. // (a different command in the group, or a different event) survive.
  321. for (const event of Object.keys(hooks)) {
  322. const groups = hooks[event];
  323. if (!Array.isArray(groups)) continue;
  324. hooks[event] = groups.filter(
  325. (g: any) => !(g && Array.isArray(g.hooks) && g.hooks.length === 0),
  326. );
  327. if (hooks[event].length === 0) delete hooks[event];
  328. }
  329. if (Object.keys(hooks).length === 0) delete settings.hooks;
  330. writeJsonFile(file, settings);
  331. return { path: file, action: 'removed' };
  332. }
  333. /**
  334. * Remove stale codegraph auto-sync hooks (`mark-dirty` / `sync-if-dirty`) that a
  335. * pre-0.8 install wrote. Exported for direct unit-testing; reused by both
  336. * `install` (an upgrade self-heals) and `uninstall`.
  337. */
  338. export function cleanupLegacyHooks(loc: Location): WriteResult['files'][number] {
  339. return removeHookCommandsMatching(loc, isLegacyCodegraphHookCommand);
  340. }
  341. /**
  342. * Remove the front-load `UserPromptSubmit` hook this installer writes (see
  343. * writePromptHookEntry). Used by `uninstall`, and by `install` when the user
  344. * opts out, so the choice round-trips.
  345. */
  346. export function removePromptHookEntry(loc: Location): WriteResult['files'][number] {
  347. return removeHookCommandsMatching(loc, isPromptHookCommand);
  348. }
  349. export function writePermissionsEntry(loc: Location): WriteResult['files'][number] {
  350. const file = settingsJsonPath(loc);
  351. const settings = readJsonFile(file);
  352. const created = !fs.existsSync(file);
  353. if (!settings.permissions) settings.permissions = {};
  354. if (!Array.isArray(settings.permissions.allow)) settings.permissions.allow = [];
  355. const want = getCodeGraphPermissions();
  356. const before = [...settings.permissions.allow];
  357. for (const perm of want) {
  358. if (!settings.permissions.allow.includes(perm)) {
  359. settings.permissions.allow.push(perm);
  360. }
  361. }
  362. if (jsonDeepEqual(before, settings.permissions.allow) && !created) {
  363. return { path: file, action: 'unchanged' };
  364. }
  365. writeJsonFile(file, settings);
  366. return { path: file, action: created ? 'created' : 'updated' };
  367. }
  368. /**
  369. * Write the front-load `UserPromptSubmit` hook into Claude `settings.json` —
  370. * a `command` hook that runs `codegraph prompt-hook`, which injects
  371. * codegraph_explore context for structural prompts so the agent reliably uses
  372. * the graph. Idempotent: if our command is already wired under UserPromptSubmit
  373. * the file is left byte-for-byte untouched and reported `unchanged`. Sibling
  374. * hooks (the user's own, or other events) are preserved. Opt-in — the installer
  375. * only calls this when the user accepts the prompt (default-yes).
  376. */
  377. export function writePromptHookEntry(loc: Location): WriteResult['files'][number] {
  378. const file = settingsJsonPath(loc);
  379. const created = !fs.existsSync(file);
  380. const settings = readJsonFile(file);
  381. if (!settings.hooks || typeof settings.hooks !== 'object' || Array.isArray(settings.hooks)) {
  382. settings.hooks = {};
  383. }
  384. if (!Array.isArray(settings.hooks.UserPromptSubmit)) settings.hooks.UserPromptSubmit = [];
  385. const already = settings.hooks.UserPromptSubmit.some(
  386. (g: any) => g && Array.isArray(g.hooks) && g.hooks.some((h: any) => isPromptHookCommand(h?.command)),
  387. );
  388. if (already) return { path: file, action: 'unchanged' };
  389. settings.hooks.UserPromptSubmit.push({
  390. hooks: [{ type: 'command', command: PROMPT_HOOK_COMMAND }],
  391. });
  392. writeJsonFile(file, settings);
  393. return { path: file, action: created ? 'created' : 'updated' };
  394. }
  395. /**
  396. * Strip the marker-delimited CodeGraph block from CLAUDE.md if a prior
  397. * install wrote one. Codegraph no longer maintains an instructions file
  398. * (issue #529) — the MCP server's `initialize` instructions are the
  399. * single source of truth — so both install (self-heal on upgrade) and
  400. * uninstall call this. `removeMarkedSection` returns `not-found`/`kept`
  401. * when there's nothing to strip; the install caller drops those from
  402. * the report so a fresh install stays quiet.
  403. */
  404. export function removeInstructionsEntry(loc: Location): WriteResult['files'][number] {
  405. const file = instructionsPath(loc);
  406. const action = removeMarkedSection(file, CODEGRAPH_SECTION_START, CODEGRAPH_SECTION_END);
  407. return { path: file, action };
  408. }
  409. export const claudeTarget: AgentTarget = new ClaudeCodeTarget();