1
0

installer-targets.test.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. /**
  2. * Multi-target installer tests.
  3. *
  4. * Each `AgentTarget` is exercised against the same contract:
  5. * - `install` writes the expected files
  6. * - re-running `install` is byte-identical (idempotent)
  7. * - sibling MCP servers / unrelated config is preserved
  8. * - `uninstall` reverses `install`
  9. * - `printConfig` returns parseable, non-empty content
  10. *
  11. * For agent-config destinations we redirect HOME to a tmpdir via
  12. * `os.homedir` spying, and CWD via `process.chdir` — same pattern as
  13. * the legacy `installer.test.ts`. No real `~/.claude/` etc. ever
  14. * touched.
  15. */
  16. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  17. import * as fs from 'fs';
  18. import * as path from 'path';
  19. import * as os from 'os';
  20. import { ALL_TARGETS, getTarget, resolveTargetFlag } from '../src/installer/targets/registry';
  21. import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  22. import { cleanupLegacyHooks } from '../src/installer/targets/claude';
  23. function mkTmpDir(label: string): string {
  24. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
  25. }
  26. // `os.homedir` is non-configurable on Node, so we redirect it via the
  27. // `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
  28. // `os.homedir()` reads first. Same trick the rest of the suite uses
  29. // when it needs a mock home.
  30. function setHome(dir: string): { restore: () => void } {
  31. const prev = {
  32. HOME: process.env.HOME,
  33. USERPROFILE: process.env.USERPROFILE,
  34. APPDATA: process.env.APPDATA,
  35. XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
  36. HERMES_HOME: process.env.HERMES_HOME,
  37. };
  38. process.env.HOME = dir;
  39. process.env.USERPROFILE = dir;
  40. process.env.APPDATA = path.join(dir, '.config');
  41. process.env.XDG_CONFIG_HOME = path.join(dir, '.config');
  42. delete process.env.HERMES_HOME;
  43. return {
  44. restore() {
  45. if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
  46. if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
  47. if (prev.APPDATA === undefined) delete process.env.APPDATA; else process.env.APPDATA = prev.APPDATA;
  48. if (prev.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = prev.XDG_CONFIG_HOME;
  49. if (prev.HERMES_HOME === undefined) delete process.env.HERMES_HOME; else process.env.HERMES_HOME = prev.HERMES_HOME;
  50. },
  51. };
  52. }
  53. describe('Installer targets — contract', () => {
  54. let tmpHome: string;
  55. let tmpCwd: string;
  56. let origCwd: string;
  57. let homeRestore: { restore: () => void };
  58. beforeEach(() => {
  59. tmpHome = mkTmpDir('home');
  60. tmpCwd = mkTmpDir('cwd');
  61. origCwd = process.cwd();
  62. process.chdir(tmpCwd);
  63. homeRestore = setHome(tmpHome);
  64. });
  65. afterEach(() => {
  66. homeRestore.restore();
  67. process.chdir(origCwd);
  68. fs.rmSync(tmpHome, { recursive: true, force: true });
  69. fs.rmSync(tmpCwd, { recursive: true, force: true });
  70. });
  71. for (const target of ALL_TARGETS) {
  72. describe(target.id, () => {
  73. const supportedLocations = (['global', 'local'] as const).filter((l) =>
  74. target.supportsLocation(l),
  75. );
  76. for (const location of supportedLocations) {
  77. describe(`location=${location}`, () => {
  78. it('install writes files; detect.alreadyConfigured becomes true', () => {
  79. expect(target.detect(location).alreadyConfigured).toBe(false);
  80. const result = target.install(location, { autoAllow: true });
  81. expect(result.files.length).toBeGreaterThan(0);
  82. for (const file of result.files) {
  83. if (file.action !== 'unchanged') {
  84. expect(fs.existsSync(file.path)).toBe(true);
  85. }
  86. }
  87. expect(target.detect(location).alreadyConfigured).toBe(true);
  88. });
  89. it('re-running install is idempotent (no actions other than unchanged)', () => {
  90. target.install(location, { autoAllow: true });
  91. const second = target.install(location, { autoAllow: true });
  92. for (const file of second.files) {
  93. expect(file.action).toBe('unchanged');
  94. }
  95. });
  96. it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
  97. // Plant a sibling entry in the same JSON config, install,
  98. // and verify the sibling survives. Skip for Codex (TOML)
  99. // and any target with no JSON config — they get covered
  100. // by their own dedicated tests below.
  101. const paths = target.describePaths(location);
  102. // Match .json or .jsonc — opencode prefers .jsonc.
  103. const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
  104. if (!jsonPath) return;
  105. // Seed pre-existing config.
  106. fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
  107. const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
  108. // opencode uses `mcp` not `mcpServers`. Match its shape too.
  109. if (target.id === 'opencode') {
  110. delete seed.mcpServers;
  111. seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
  112. }
  113. fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
  114. target.install(location, { autoAllow: true });
  115. const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
  116. if (target.id === 'opencode') {
  117. expect(after.mcp.other).toBeDefined();
  118. expect(after.mcp.codegraph).toBeDefined();
  119. } else {
  120. expect(after.mcpServers.other).toBeDefined();
  121. expect(after.mcpServers.codegraph).toBeDefined();
  122. }
  123. });
  124. it('uninstall reverses install (alreadyConfigured returns to false)', () => {
  125. target.install(location, { autoAllow: true });
  126. expect(target.detect(location).alreadyConfigured).toBe(true);
  127. target.uninstall(location);
  128. expect(target.detect(location).alreadyConfigured).toBe(false);
  129. });
  130. it('printConfig returns non-empty output without writing anything', () => {
  131. const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  132. const out = target.printConfig(location);
  133. expect(out.length).toBeGreaterThan(0);
  134. const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  135. expect(after.sort()).toEqual(before.sort());
  136. });
  137. });
  138. }
  139. });
  140. }
  141. });
  142. describe('Installer targets — partial-state idempotency', () => {
  143. let tmpHome: string;
  144. let tmpCwd: string;
  145. let origCwd: string;
  146. let homeRestore: { restore: () => void };
  147. beforeEach(() => {
  148. tmpHome = mkTmpDir('home');
  149. tmpCwd = mkTmpDir('cwd');
  150. origCwd = process.cwd();
  151. process.chdir(tmpCwd);
  152. homeRestore = setHome(tmpHome);
  153. });
  154. afterEach(() => {
  155. homeRestore.restore();
  156. process.chdir(origCwd);
  157. fs.rmSync(tmpHome, { recursive: true, force: true });
  158. fs.rmSync(tmpCwd, { recursive: true, force: true });
  159. });
  160. it('codex: install after only config.toml exists — second pass is fully unchanged', () => {
  161. const codex = getTarget('codex')!;
  162. // First install creates both files.
  163. codex.install('global', { autoAllow: false });
  164. // Delete the AGENTS.md to simulate partial state (user wiped one file).
  165. const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
  166. expect(fs.existsSync(agentsMd)).toBe(true);
  167. fs.unlinkSync(agentsMd);
  168. // Reinstall — TOML stays unchanged, AGENTS.md is recreated.
  169. const second = codex.install('global', { autoAllow: false });
  170. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  171. const mdEntry = second.files.find((f) => f.path.endsWith('AGENTS.md'))!;
  172. expect(tomlEntry.action).toBe('unchanged');
  173. expect(mdEntry.action).toBe('created');
  174. // Third install — both unchanged (full idempotency restored).
  175. const third = codex.install('global', { autoAllow: false });
  176. for (const f of third.files) expect(f.action).toBe('unchanged');
  177. });
  178. it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
  179. const opencode = getTarget('opencode')!;
  180. const dir = path.join(tmpHome, '.config', 'opencode');
  181. fs.mkdirSync(dir, { recursive: true });
  182. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  183. fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  184. const result = opencode.install('global', { autoAllow: true });
  185. const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
  186. expect(written).toBeDefined();
  187. expect(written.action).not.toBe('not-found');
  188. // The .json file is left alone.
  189. const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
  190. expect(jsonText).not.toContain('codegraph');
  191. });
  192. it('opencode: uses .json when only .json exists (no .jsonc)', () => {
  193. const opencode = getTarget('opencode')!;
  194. const dir = path.join(tmpHome, '.config', 'opencode');
  195. fs.mkdirSync(dir, { recursive: true });
  196. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  197. const result = opencode.install('global', { autoAllow: true });
  198. expect(result.files[0].path).toMatch(/opencode\.json$/);
  199. expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
  200. });
  201. it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
  202. const opencode = getTarget('opencode')!;
  203. const result = opencode.install('global', { autoAllow: true });
  204. expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
  205. expect(result.files[0].action).toBe('created');
  206. });
  207. it('opencode: preserves line and block comments through install + idempotent re-run', () => {
  208. const opencode = getTarget('opencode')!;
  209. const dir = path.join(tmpHome, '.config', 'opencode');
  210. fs.mkdirSync(dir, { recursive: true });
  211. const file = path.join(dir, 'opencode.jsonc');
  212. const original = [
  213. '{',
  214. ' // top-level note about my opencode setup',
  215. ' "$schema": "https://opencode.ai/config.json",',
  216. ' /* multi-line block comment',
  217. ' describing the providers section */',
  218. ' "providers": {',
  219. ' "anthropic": { "model": "claude-opus-4-7" } // pinned',
  220. ' }',
  221. '}',
  222. '',
  223. ].join('\n');
  224. fs.writeFileSync(file, original);
  225. opencode.install('global', { autoAllow: true });
  226. const afterInstall = fs.readFileSync(file, 'utf-8');
  227. expect(afterInstall).toContain('// top-level note about my opencode setup');
  228. expect(afterInstall).toContain('/* multi-line block comment');
  229. expect(afterInstall).toContain('// pinned');
  230. expect(afterInstall).toContain('"codegraph"');
  231. expect(afterInstall).toContain('"providers"');
  232. // Idempotent re-run reports unchanged, file is byte-identical.
  233. const second = opencode.install('global', { autoAllow: true });
  234. expect(second.files[0].action).toBe('unchanged');
  235. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  236. });
  237. it('opencode: install writes AGENTS.md with the marker-delimited codegraph block', () => {
  238. const opencode = getTarget('opencode')!;
  239. opencode.install('global', { autoAllow: true });
  240. const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
  241. expect(fs.existsSync(agentsMd)).toBe(true);
  242. const body = fs.readFileSync(agentsMd, 'utf-8');
  243. expect(body).toContain('<!-- CODEGRAPH_START -->');
  244. expect(body).toContain('<!-- CODEGRAPH_END -->');
  245. expect(body).toContain('codegraph_callers');
  246. });
  247. it('opencode: AGENTS.md install preserves pre-existing user content outside markers', () => {
  248. const opencode = getTarget('opencode')!;
  249. const dir = path.join(tmpHome, '.config', 'opencode');
  250. fs.mkdirSync(dir, { recursive: true });
  251. const agentsMd = path.join(dir, 'AGENTS.md');
  252. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  253. opencode.install('global', { autoAllow: true });
  254. const body = fs.readFileSync(agentsMd, 'utf-8');
  255. expect(body).toContain('# My personal opencode instructions');
  256. expect(body).toContain('Always respond in pirate.');
  257. expect(body).toContain('<!-- CODEGRAPH_START -->');
  258. });
  259. it('opencode: uninstall strips only the codegraph block from AGENTS.md', () => {
  260. const opencode = getTarget('opencode')!;
  261. const dir = path.join(tmpHome, '.config', 'opencode');
  262. fs.mkdirSync(dir, { recursive: true });
  263. const agentsMd = path.join(dir, 'AGENTS.md');
  264. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  265. opencode.install('global', { autoAllow: true });
  266. opencode.uninstall('global');
  267. const body = fs.readFileSync(agentsMd, 'utf-8');
  268. expect(body).toContain('# My personal opencode instructions');
  269. expect(body).toContain('Always respond in pirate.');
  270. expect(body).not.toContain('CODEGRAPH_START');
  271. expect(body).not.toContain('codegraph_callers');
  272. });
  273. it('opencode: local install writes ./opencode.jsonc and ./AGENTS.md in cwd', () => {
  274. const opencode = getTarget('opencode')!;
  275. const result = opencode.install('local', { autoAllow: true });
  276. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  277. // macOS realpath shenanigans (/var vs /private/var) — suffix match.
  278. expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
  279. expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
  280. });
  281. it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
  282. const hermes = getTarget('hermes')!;
  283. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  284. fs.mkdirSync(path.dirname(config), { recursive: true });
  285. fs.writeFileSync(config, [
  286. 'model:',
  287. ' default: qwen-3.7',
  288. 'mcp_servers:',
  289. ' other:',
  290. ' command: other',
  291. 'platform_toolsets:',
  292. ' cli:',
  293. ' - hermes-cli',
  294. ' discord:',
  295. ' - hermes-discord',
  296. '',
  297. ].join('\n'));
  298. const result = hermes.install('global', { autoAllow: true });
  299. expect(result.files[0].action).toBe('updated');
  300. const body = fs.readFileSync(config, 'utf-8');
  301. expect(body).toContain('model:\n default: qwen-3.7');
  302. expect(body).toContain('mcp_servers:\n other:\n command: other');
  303. expect(body).toContain(' codegraph:\n command: codegraph');
  304. expect(body).toContain(' - hermes-cli');
  305. expect(body).toContain(' - mcp-codegraph');
  306. expect(body).toContain(' discord:\n - hermes-discord');
  307. const second = hermes.install('global', { autoAllow: true });
  308. expect(second.files[0].action).toBe('unchanged');
  309. });
  310. it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
  311. const hermes = getTarget('hermes')!;
  312. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  313. fs.mkdirSync(path.dirname(config), { recursive: true });
  314. hermes.install('global', { autoAllow: true });
  315. fs.appendFileSync(config, 'custom:\n keep: true\n');
  316. hermes.uninstall('global');
  317. const body = fs.readFileSync(config, 'utf-8');
  318. expect(body).not.toContain('codegraph:');
  319. expect(body).not.toContain('mcp-codegraph');
  320. expect(body).toContain('custom:\n keep: true');
  321. });
  322. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  323. const opencode = getTarget('opencode')!;
  324. const dir = path.join(tmpHome, '.config', 'opencode');
  325. fs.mkdirSync(dir, { recursive: true });
  326. const file = path.join(dir, 'opencode.jsonc');
  327. fs.writeFileSync(file, [
  328. '{',
  329. ' // important comment',
  330. ' "$schema": "https://opencode.ai/config.json",',
  331. ' "mcp": {',
  332. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  333. ' }',
  334. '}',
  335. '',
  336. ].join('\n'));
  337. opencode.install('global', { autoAllow: true });
  338. const afterInstall = fs.readFileSync(file, 'utf-8');
  339. expect(afterInstall).toContain('"codegraph"');
  340. expect(afterInstall).toContain('"other"');
  341. opencode.uninstall('global');
  342. const afterUninstall = fs.readFileSync(file, 'utf-8');
  343. expect(afterUninstall).not.toContain('codegraph');
  344. expect(afterUninstall).toContain('// important comment');
  345. expect(afterUninstall).toContain('"other"');
  346. });
  347. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  348. const codex = getTarget('codex')!;
  349. codex.install('global', { autoAllow: false });
  350. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  351. const original = fs.readFileSync(tomlPath, 'utf-8');
  352. // User edits the block to add a custom key.
  353. const edited = original.replace(
  354. 'args = ["serve", "--mcp"]',
  355. 'args = ["serve", "--mcp"]\nenabled = true',
  356. );
  357. fs.writeFileSync(tomlPath, edited);
  358. // Re-install: our serializer doesn't know `enabled = true`, so
  359. // the block no longer matches the canonical form — we'll
  360. // overwrite it. This is the documented contract: we own the
  361. // codegraph block exclusively.
  362. const second = codex.install('global', { autoAllow: false });
  363. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  364. expect(tomlEntry.action).toBe('updated');
  365. const after = fs.readFileSync(tomlPath, 'utf-8');
  366. expect(after).not.toContain('enabled = true');
  367. });
  368. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  369. const claude = getTarget('claude')!;
  370. const result = claude.install('local', { autoAllow: false });
  371. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  372. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  373. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  374. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  375. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  376. expect(cfg.mcpServers.codegraph).toBeDefined();
  377. });
  378. it('claude: global install targets ~/.claude.json (user scope)', () => {
  379. const claude = getTarget('claude')!;
  380. claude.install('global', { autoAllow: false });
  381. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  382. expect(cfg.mcpServers.codegraph).toBeDefined();
  383. });
  384. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  385. const claude = getTarget('claude')!;
  386. const legacy = path.join(tmpCwd, '.claude.json');
  387. fs.writeFileSync(
  388. legacy,
  389. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  390. );
  391. claude.install('local', { autoAllow: false });
  392. // codegraph now lives in .mcp.json; the legacy file (which held only
  393. // codegraph) is gone.
  394. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  395. expect(mcp.mcpServers.codegraph).toBeDefined();
  396. expect(fs.existsSync(legacy)).toBe(false);
  397. });
  398. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  399. const claude = getTarget('claude')!;
  400. const legacy = path.join(tmpCwd, '.claude.json');
  401. fs.writeFileSync(
  402. legacy,
  403. JSON.stringify({
  404. mcpServers: {
  405. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  406. other: { command: 'x' },
  407. },
  408. somethingElse: true,
  409. }, null, 2),
  410. );
  411. claude.install('local', { autoAllow: false });
  412. // Only codegraph is stripped from the legacy file; siblings survive.
  413. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  414. expect(after.mcpServers.codegraph).toBeUndefined();
  415. expect(after.mcpServers.other).toBeDefined();
  416. expect(after.somethingElse).toBe(true);
  417. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  418. expect(mcp.mcpServers.codegraph).toBeDefined();
  419. });
  420. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  421. const claude = getTarget('claude')!;
  422. // A user left with both the working .mcp.json and a stale .claude.json.
  423. fs.writeFileSync(
  424. path.join(tmpCwd, '.mcp.json'),
  425. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  426. );
  427. fs.writeFileSync(
  428. path.join(tmpCwd, '.claude.json'),
  429. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  430. );
  431. claude.uninstall('local');
  432. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  433. expect(mcp.mcpServers).toBeUndefined();
  434. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  435. expect(legacy.mcpServers.codegraph).toBeUndefined();
  436. expect(legacy.mcpServers.other).toBeDefined();
  437. });
  438. // ---- Legacy auto-sync hook cleanup ----
  439. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  440. // hooks to settings.json. Both subcommands were removed from the CLI,
  441. // so the Stop hook fails every turn ("unknown command
  442. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  443. // uninstall — without touching the user's unrelated hooks.
  444. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  445. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  446. fs.mkdirSync(dir, { recursive: true });
  447. const file = path.join(dir, 'settings.json');
  448. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  449. return file;
  450. }
  451. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  452. // unrelated GitKraken Stop hook the user added (matches the report).
  453. function legacyHookSettings(): Record<string, any> {
  454. return {
  455. hooks: {
  456. PostToolUse: [
  457. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  458. ],
  459. Stop: [
  460. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  461. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  462. ],
  463. },
  464. };
  465. }
  466. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  467. const claude = getTarget('claude')!;
  468. const file = seedSettings('global', legacyHookSettings());
  469. claude.install('global', { autoAllow: true });
  470. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  471. // The only PostToolUse group held mark-dirty → the event is gone.
  472. expect(after.hooks?.PostToolUse).toBeUndefined();
  473. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  474. (g.hooks ?? []).map((h: any) => h.command),
  475. );
  476. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  477. // The unrelated GitKraken hook survives untouched.
  478. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  479. // Permissions still written as normal alongside the cleanup.
  480. expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
  481. });
  482. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  483. const file = seedSettings('global', {
  484. hooks: {
  485. Stop: [
  486. {
  487. hooks: [
  488. { type: 'command', command: 'codegraph sync-if-dirty' },
  489. { type: 'command', command: 'gk ai hook run --host claude-code' },
  490. ],
  491. },
  492. ],
  493. },
  494. });
  495. expect(cleanupLegacyHooks('global').action).toBe('removed');
  496. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  497. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  498. 'gk ai hook run --host claude-code',
  499. ]);
  500. });
  501. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  502. const original =
  503. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  504. const file = seedSettings('global', JSON.parse(original));
  505. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  506. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  507. });
  508. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  509. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  510. });
  511. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  512. const claude = getTarget('claude')!;
  513. const file = seedSettings('global', legacyHookSettings());
  514. claude.install('global', { autoAllow: true });
  515. const firstPass = fs.readFileSync(file, 'utf-8');
  516. claude.install('global', { autoAllow: true });
  517. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  518. });
  519. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  520. const claude = getTarget('claude')!;
  521. const file = seedSettings('local', {
  522. hooks: {
  523. PostToolUse: [
  524. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  525. ],
  526. Stop: [
  527. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  528. ],
  529. },
  530. });
  531. claude.uninstall('local');
  532. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  533. // Both events emptied → the whole `hooks` object is removed.
  534. expect(after.hooks).toBeUndefined();
  535. });
  536. });
  537. describe('Installer targets — registry', () => {
  538. it('getTarget returns the right target for each id', () => {
  539. expect(getTarget('claude')?.id).toBe('claude');
  540. expect(getTarget('cursor')?.id).toBe('cursor');
  541. expect(getTarget('codex')?.id).toBe('codex');
  542. expect(getTarget('opencode')?.id).toBe('opencode');
  543. expect(getTarget('hermes')?.id).toBe('hermes');
  544. expect(getTarget('not-a-real-target')).toBeUndefined();
  545. });
  546. it('resolveTargetFlag handles auto/all/none/csv', () => {
  547. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  548. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  549. const csv = resolveTargetFlag('claude,cursor', 'global');
  550. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  551. });
  552. it('resolveTargetFlag throws on unknown id', () => {
  553. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  554. });
  555. });
  556. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  557. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  558. const block = buildTomlTable('mcp_servers.codegraph', {
  559. command: 'codegraph',
  560. args: ['serve', '--mcp'],
  561. });
  562. expect(block).toContain('[mcp_servers.codegraph]');
  563. expect(block).toContain('command = "codegraph"');
  564. expect(block).toContain('args = ["serve", "--mcp"]');
  565. });
  566. it('upsert inserts into empty content', () => {
  567. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  568. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  569. expect(action).toBe('inserted');
  570. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  571. });
  572. it('upsert is idempotent — second call returns unchanged', () => {
  573. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  574. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  575. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  576. expect(second.action).toBe('unchanged');
  577. expect(second.content).toBe(first.content);
  578. });
  579. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  580. const existing = [
  581. '[other_table]',
  582. 'foo = "bar"',
  583. '',
  584. '[mcp_servers.codegraph]',
  585. 'command = "old-codegraph"',
  586. 'args = ["old"]',
  587. '',
  588. '[zzz]',
  589. 'baz = "qux"',
  590. '',
  591. ].join('\n');
  592. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  593. command: 'codegraph',
  594. args: ['serve', '--mcp'],
  595. });
  596. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  597. expect(action).toBe('replaced');
  598. expect(content).toContain('[other_table]');
  599. expect(content).toContain('foo = "bar"');
  600. expect(content).toContain('[zzz]');
  601. expect(content).toContain('baz = "qux"');
  602. expect(content).toContain('command = "codegraph"');
  603. expect(content).not.toContain('old-codegraph');
  604. });
  605. it('removeTomlTable strips the block and preserves siblings', () => {
  606. const existing = [
  607. '[other_table]',
  608. 'foo = "bar"',
  609. '',
  610. '[mcp_servers.codegraph]',
  611. 'command = "codegraph"',
  612. 'args = ["serve"]',
  613. ].join('\n');
  614. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  615. expect(action).toBe('removed');
  616. expect(content).toContain('[other_table]');
  617. expect(content).toContain('foo = "bar"');
  618. expect(content).not.toContain('mcp_servers.codegraph');
  619. });
  620. it('removeTomlTable on missing table returns not-found, no content change', () => {
  621. const existing = '[other]\nfoo = "bar"\n';
  622. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  623. expect(action).toBe('not-found');
  624. expect(content).toBe(existing);
  625. });
  626. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  627. const existing = [
  628. '[[foo]]',
  629. 'name = "a"',
  630. '',
  631. '[[foo]]',
  632. 'name = "b"',
  633. '',
  634. ].join('\n');
  635. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  636. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  637. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  638. expect(content).toContain('[mcp_servers.codegraph]');
  639. });
  640. });
  641. function listAllFiles(dir: string): string[] {
  642. if (!fs.existsSync(dir)) return [];
  643. const out: string[] = [];
  644. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  645. const full = path.join(dir, entry.name);
  646. if (entry.isDirectory()) out.push(...listAllFiles(full));
  647. else out.push(full);
  648. }
  649. return out;
  650. }