installer-targets.test.ts 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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 { uninstallTargets } from '../src/installer';
  22. import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  23. import { cleanupLegacyHooks } from '../src/installer/targets/claude';
  24. function mkTmpDir(label: string): string {
  25. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
  26. }
  27. // `os.homedir` is non-configurable on Node, so we redirect it via the
  28. // `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
  29. // `os.homedir()` reads first. Same trick the rest of the suite uses
  30. // when it needs a mock home.
  31. function setHome(dir: string): { restore: () => void } {
  32. const prev = {
  33. HOME: process.env.HOME,
  34. USERPROFILE: process.env.USERPROFILE,
  35. APPDATA: process.env.APPDATA,
  36. XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
  37. HERMES_HOME: process.env.HERMES_HOME,
  38. };
  39. process.env.HOME = dir;
  40. process.env.USERPROFILE = dir;
  41. process.env.APPDATA = path.join(dir, '.config');
  42. process.env.XDG_CONFIG_HOME = path.join(dir, '.config');
  43. delete process.env.HERMES_HOME;
  44. return {
  45. restore() {
  46. if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
  47. if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
  48. if (prev.APPDATA === undefined) delete process.env.APPDATA; else process.env.APPDATA = prev.APPDATA;
  49. if (prev.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = prev.XDG_CONFIG_HOME;
  50. if (prev.HERMES_HOME === undefined) delete process.env.HERMES_HOME; else process.env.HERMES_HOME = prev.HERMES_HOME;
  51. },
  52. };
  53. }
  54. describe('Installer targets — contract', () => {
  55. let tmpHome: string;
  56. let tmpCwd: string;
  57. let origCwd: string;
  58. let homeRestore: { restore: () => void };
  59. beforeEach(() => {
  60. tmpHome = mkTmpDir('home');
  61. tmpCwd = mkTmpDir('cwd');
  62. origCwd = process.cwd();
  63. process.chdir(tmpCwd);
  64. homeRestore = setHome(tmpHome);
  65. });
  66. afterEach(() => {
  67. homeRestore.restore();
  68. process.chdir(origCwd);
  69. fs.rmSync(tmpHome, { recursive: true, force: true });
  70. fs.rmSync(tmpCwd, { recursive: true, force: true });
  71. });
  72. for (const target of ALL_TARGETS) {
  73. describe(target.id, () => {
  74. const supportedLocations = (['global', 'local'] as const).filter((l) =>
  75. target.supportsLocation(l),
  76. );
  77. for (const location of supportedLocations) {
  78. describe(`location=${location}`, () => {
  79. it('install writes files; detect.alreadyConfigured becomes true', () => {
  80. expect(target.detect(location).alreadyConfigured).toBe(false);
  81. const result = target.install(location, { autoAllow: true });
  82. expect(result.files.length).toBeGreaterThan(0);
  83. for (const file of result.files) {
  84. if (file.action !== 'unchanged') {
  85. expect(fs.existsSync(file.path)).toBe(true);
  86. }
  87. }
  88. expect(target.detect(location).alreadyConfigured).toBe(true);
  89. });
  90. it('re-running install is idempotent (no actions other than unchanged)', () => {
  91. target.install(location, { autoAllow: true });
  92. const second = target.install(location, { autoAllow: true });
  93. for (const file of second.files) {
  94. expect(file.action).toBe('unchanged');
  95. }
  96. });
  97. it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
  98. // Plant a sibling entry in the same JSON config, install,
  99. // and verify the sibling survives. Skip for Codex (TOML)
  100. // and any target with no JSON config — they get covered
  101. // by their own dedicated tests below.
  102. const paths = target.describePaths(location);
  103. // Match .json or .jsonc — opencode prefers .jsonc.
  104. const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
  105. if (!jsonPath) return;
  106. // Seed pre-existing config.
  107. fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
  108. const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
  109. // opencode uses `mcp` not `mcpServers`. Match its shape too.
  110. if (target.id === 'opencode') {
  111. delete seed.mcpServers;
  112. seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
  113. }
  114. fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
  115. target.install(location, { autoAllow: true });
  116. const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
  117. if (target.id === 'opencode') {
  118. expect(after.mcp.other).toBeDefined();
  119. expect(after.mcp.codegraph).toBeDefined();
  120. } else {
  121. expect(after.mcpServers.other).toBeDefined();
  122. expect(after.mcpServers.codegraph).toBeDefined();
  123. }
  124. });
  125. it('uninstall reverses install (alreadyConfigured returns to false)', () => {
  126. target.install(location, { autoAllow: true });
  127. expect(target.detect(location).alreadyConfigured).toBe(true);
  128. target.uninstall(location);
  129. expect(target.detect(location).alreadyConfigured).toBe(false);
  130. });
  131. it('printConfig returns non-empty output without writing anything', () => {
  132. const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  133. const out = target.printConfig(location);
  134. expect(out.length).toBeGreaterThan(0);
  135. const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  136. expect(after.sort()).toEqual(before.sort());
  137. });
  138. });
  139. }
  140. });
  141. }
  142. });
  143. describe('Installer targets — partial-state idempotency', () => {
  144. let tmpHome: string;
  145. let tmpCwd: string;
  146. let origCwd: string;
  147. let homeRestore: { restore: () => void };
  148. beforeEach(() => {
  149. tmpHome = mkTmpDir('home');
  150. tmpCwd = mkTmpDir('cwd');
  151. origCwd = process.cwd();
  152. process.chdir(tmpCwd);
  153. homeRestore = setHome(tmpHome);
  154. });
  155. afterEach(() => {
  156. homeRestore.restore();
  157. process.chdir(origCwd);
  158. fs.rmSync(tmpHome, { recursive: true, force: true });
  159. fs.rmSync(tmpCwd, { recursive: true, force: true });
  160. });
  161. it('codex: install after only config.toml exists — second pass is fully unchanged', () => {
  162. const codex = getTarget('codex')!;
  163. // First install creates both files.
  164. codex.install('global', { autoAllow: false });
  165. // Delete the AGENTS.md to simulate partial state (user wiped one file).
  166. const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
  167. expect(fs.existsSync(agentsMd)).toBe(true);
  168. fs.unlinkSync(agentsMd);
  169. // Reinstall — TOML stays unchanged, AGENTS.md is recreated.
  170. const second = codex.install('global', { autoAllow: false });
  171. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  172. const mdEntry = second.files.find((f) => f.path.endsWith('AGENTS.md'))!;
  173. expect(tomlEntry.action).toBe('unchanged');
  174. expect(mdEntry.action).toBe('created');
  175. // Third install — both unchanged (full idempotency restored).
  176. const third = codex.install('global', { autoAllow: false });
  177. for (const f of third.files) expect(f.action).toBe('unchanged');
  178. });
  179. it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
  180. const opencode = getTarget('opencode')!;
  181. const dir = path.join(tmpHome, '.config', 'opencode');
  182. fs.mkdirSync(dir, { recursive: true });
  183. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  184. fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  185. const result = opencode.install('global', { autoAllow: true });
  186. const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
  187. expect(written).toBeDefined();
  188. expect(written.action).not.toBe('not-found');
  189. // The .json file is left alone.
  190. const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
  191. expect(jsonText).not.toContain('codegraph');
  192. });
  193. it('opencode: uses .json when only .json exists (no .jsonc)', () => {
  194. const opencode = getTarget('opencode')!;
  195. const dir = path.join(tmpHome, '.config', 'opencode');
  196. fs.mkdirSync(dir, { recursive: true });
  197. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  198. const result = opencode.install('global', { autoAllow: true });
  199. expect(result.files[0].path).toMatch(/opencode\.json$/);
  200. expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
  201. });
  202. it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
  203. const opencode = getTarget('opencode')!;
  204. const result = opencode.install('global', { autoAllow: true });
  205. expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
  206. expect(result.files[0].action).toBe('created');
  207. });
  208. it('opencode: preserves line and block comments through install + idempotent re-run', () => {
  209. const opencode = getTarget('opencode')!;
  210. const dir = path.join(tmpHome, '.config', 'opencode');
  211. fs.mkdirSync(dir, { recursive: true });
  212. const file = path.join(dir, 'opencode.jsonc');
  213. const original = [
  214. '{',
  215. ' // top-level note about my opencode setup',
  216. ' "$schema": "https://opencode.ai/config.json",',
  217. ' /* multi-line block comment',
  218. ' describing the providers section */',
  219. ' "providers": {',
  220. ' "anthropic": { "model": "claude-opus-4-7" } // pinned',
  221. ' }',
  222. '}',
  223. '',
  224. ].join('\n');
  225. fs.writeFileSync(file, original);
  226. opencode.install('global', { autoAllow: true });
  227. const afterInstall = fs.readFileSync(file, 'utf-8');
  228. expect(afterInstall).toContain('// top-level note about my opencode setup');
  229. expect(afterInstall).toContain('/* multi-line block comment');
  230. expect(afterInstall).toContain('// pinned');
  231. expect(afterInstall).toContain('"codegraph"');
  232. expect(afterInstall).toContain('"providers"');
  233. // Idempotent re-run reports unchanged, file is byte-identical.
  234. const second = opencode.install('global', { autoAllow: true });
  235. expect(second.files[0].action).toBe('unchanged');
  236. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  237. });
  238. it('opencode: install writes AGENTS.md with the marker-delimited codegraph block', () => {
  239. const opencode = getTarget('opencode')!;
  240. opencode.install('global', { autoAllow: true });
  241. const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
  242. expect(fs.existsSync(agentsMd)).toBe(true);
  243. const body = fs.readFileSync(agentsMd, 'utf-8');
  244. expect(body).toContain('<!-- CODEGRAPH_START -->');
  245. expect(body).toContain('<!-- CODEGRAPH_END -->');
  246. expect(body).toContain('codegraph_callers');
  247. });
  248. it('opencode: AGENTS.md install preserves pre-existing user content outside markers', () => {
  249. const opencode = getTarget('opencode')!;
  250. const dir = path.join(tmpHome, '.config', 'opencode');
  251. fs.mkdirSync(dir, { recursive: true });
  252. const agentsMd = path.join(dir, 'AGENTS.md');
  253. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  254. opencode.install('global', { autoAllow: true });
  255. const body = fs.readFileSync(agentsMd, 'utf-8');
  256. expect(body).toContain('# My personal opencode instructions');
  257. expect(body).toContain('Always respond in pirate.');
  258. expect(body).toContain('<!-- CODEGRAPH_START -->');
  259. });
  260. it('opencode: uninstall strips only the codegraph block from AGENTS.md', () => {
  261. const opencode = getTarget('opencode')!;
  262. const dir = path.join(tmpHome, '.config', 'opencode');
  263. fs.mkdirSync(dir, { recursive: true });
  264. const agentsMd = path.join(dir, 'AGENTS.md');
  265. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  266. opencode.install('global', { autoAllow: true });
  267. opencode.uninstall('global');
  268. const body = fs.readFileSync(agentsMd, 'utf-8');
  269. expect(body).toContain('# My personal opencode instructions');
  270. expect(body).toContain('Always respond in pirate.');
  271. expect(body).not.toContain('CODEGRAPH_START');
  272. expect(body).not.toContain('codegraph_callers');
  273. });
  274. it('opencode: local install writes ./opencode.jsonc and ./AGENTS.md in cwd', () => {
  275. const opencode = getTarget('opencode')!;
  276. const result = opencode.install('local', { autoAllow: true });
  277. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  278. // macOS realpath shenanigans (/var vs /private/var) — suffix match.
  279. expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
  280. expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
  281. });
  282. it('gemini: install writes settings.json (mcpServers.codegraph) and GEMINI.md with marker block', () => {
  283. const gemini = getTarget('gemini')!;
  284. const result = gemini.install('global', { autoAllow: true });
  285. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  286. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  287. expect(result.files.some((f) => f.path === settings)).toBe(true);
  288. expect(result.files.some((f) => f.path === geminiMd)).toBe(true);
  289. const cfg = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  290. expect(cfg.mcpServers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  291. const md = fs.readFileSync(geminiMd, 'utf-8');
  292. expect(md).toContain('<!-- CODEGRAPH_START -->');
  293. expect(md).toContain('<!-- CODEGRAPH_END -->');
  294. expect(md).toContain('codegraph_callers');
  295. });
  296. it('gemini: install preserves pre-existing settings (security.auth survives)', () => {
  297. const gemini = getTarget('gemini')!;
  298. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  299. fs.mkdirSync(path.dirname(settings), { recursive: true });
  300. fs.writeFileSync(settings, JSON.stringify({
  301. security: { auth: { selectedType: 'oauth-personal' } },
  302. }, null, 2) + '\n');
  303. gemini.install('global', { autoAllow: true });
  304. const after = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  305. expect(after.security?.auth?.selectedType).toBe('oauth-personal');
  306. expect(after.mcpServers?.codegraph).toBeDefined();
  307. });
  308. it('gemini: uninstall strips codegraph but leaves pre-existing settings (security.auth) intact', () => {
  309. const gemini = getTarget('gemini')!;
  310. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  311. fs.mkdirSync(path.dirname(settings), { recursive: true });
  312. fs.writeFileSync(settings, JSON.stringify({
  313. security: { auth: { selectedType: 'oauth-personal' } },
  314. }, null, 2) + '\n');
  315. gemini.install('global', { autoAllow: true });
  316. gemini.uninstall('global');
  317. const after = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  318. expect(after.security?.auth?.selectedType).toBe('oauth-personal');
  319. expect(after.mcpServers).toBeUndefined();
  320. });
  321. it('gemini: local install writes ./.gemini/settings.json and ./GEMINI.md (project root)', () => {
  322. const gemini = getTarget('gemini')!;
  323. const result = gemini.install('local', { autoAllow: true });
  324. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  325. expect(paths.some((p) => p.endsWith('/.gemini/settings.json'))).toBe(true);
  326. // Local GEMINI.md sits at the project root, NOT under .gemini/.
  327. expect(paths.some((p) => p.endsWith('/GEMINI.md') && !p.endsWith('/.gemini/GEMINI.md'))).toBe(true);
  328. });
  329. it('gemini: GEMINI.md uninstall preserves user content outside the codegraph markers', () => {
  330. const gemini = getTarget('gemini')!;
  331. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  332. fs.mkdirSync(path.dirname(geminiMd), { recursive: true });
  333. fs.writeFileSync(geminiMd, '# My personal Gemini context\n\nAlways respond concisely.\n');
  334. gemini.install('global', { autoAllow: true });
  335. gemini.uninstall('global');
  336. const body = fs.readFileSync(geminiMd, 'utf-8');
  337. expect(body).toContain('# My personal Gemini context');
  338. expect(body).toContain('Always respond concisely.');
  339. expect(body).not.toContain('CODEGRAPH_START');
  340. expect(body).not.toContain('codegraph_callers');
  341. });
  342. it('antigravity: install writes to LEGACY ~/.gemini/antigravity/mcp_config.json when no migration marker', () => {
  343. const antigravity = getTarget('antigravity')!;
  344. antigravity.install('global', { autoAllow: true });
  345. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  346. expect(fs.existsSync(legacyFile)).toBe(true);
  347. const cfg = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  348. expect(cfg.mcpServers.codegraph).toBeDefined();
  349. // Crucially: does NOT touch the Gemini CLI's settings.json.
  350. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'settings.json'))).toBe(false);
  351. });
  352. it('antigravity: install writes to UNIFIED ~/.gemini/config/mcp_config.json when .migrated marker present', () => {
  353. const antigravity = getTarget('antigravity')!;
  354. // Plant the migration marker — same signal Antigravity itself drops
  355. // when it migrates a user's config.
  356. const unifiedDir = path.join(tmpHome, '.gemini', 'config');
  357. fs.mkdirSync(unifiedDir, { recursive: true });
  358. fs.writeFileSync(path.join(unifiedDir, '.migrated'), '');
  359. antigravity.install('global', { autoAllow: true });
  360. const unifiedFile = path.join(unifiedDir, 'mcp_config.json');
  361. expect(fs.existsSync(unifiedFile)).toBe(true);
  362. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  363. expect(cfg.mcpServers.codegraph).toBeDefined();
  364. // Legacy path is NOT touched when the marker tells us migration happened.
  365. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'))).toBe(false);
  366. });
  367. it('antigravity: install writes to UNIFIED path when ~/.gemini/config/mcp_config.json already exists (even without marker)', () => {
  368. const antigravity = getTarget('antigravity')!;
  369. // Antigravity creates this file on first launch post-migration — its
  370. // presence is the second signal we accept, in case the .migrated
  371. // marker semantics change across Antigravity versions.
  372. const unifiedFile = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  373. fs.mkdirSync(path.dirname(unifiedFile), { recursive: true });
  374. fs.writeFileSync(unifiedFile, JSON.stringify({ mcpServers: {} }, null, 2) + '\n');
  375. antigravity.install('global', { autoAllow: true });
  376. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  377. expect(cfg.mcpServers.codegraph).toBeDefined();
  378. });
  379. it('antigravity: entry has NO `type` field (Antigravity rejects entries with it)', () => {
  380. const antigravity = getTarget('antigravity')!;
  381. // Marker → unified path; doesn't matter which path, just inspect the entry shape.
  382. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  383. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  384. antigravity.install('global', { autoAllow: true });
  385. const cfg = JSON.parse(fs.readFileSync(
  386. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  387. ));
  388. expect(cfg.mcpServers.codegraph.type).toBeUndefined();
  389. expect(cfg.mcpServers.codegraph.command).toBeDefined();
  390. expect(cfg.mcpServers.codegraph.args).toEqual(['serve', '--mcp']);
  391. });
  392. it('antigravity: install migrates a legacy codegraph entry to the unified path when marker appears', () => {
  393. const antigravity = getTarget('antigravity')!;
  394. // Simulate: user installed on the legacy path, then Antigravity
  395. // migrated their config (dropped the `.migrated` marker + created
  396. // the unified file). Re-running codegraph install should land
  397. // codegraph in the new file AND strip the stale legacy entry.
  398. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  399. fs.mkdirSync(path.dirname(legacyFile), { recursive: true });
  400. fs.writeFileSync(legacyFile, JSON.stringify({
  401. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  402. }, null, 2) + '\n');
  403. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  404. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  405. antigravity.install('global', { autoAllow: true });
  406. const unified = JSON.parse(fs.readFileSync(
  407. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  408. ));
  409. expect(unified.mcpServers.codegraph).toBeDefined();
  410. // Legacy file's codegraph entry got stripped.
  411. const legacy = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  412. expect(legacy.mcpServers).toBeUndefined();
  413. });
  414. it('antigravity: install preserves a sibling MCP server in mcp_config.json (legacy path)', () => {
  415. const antigravity = getTarget('antigravity')!;
  416. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  417. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  418. fs.writeFileSync(mcpFile, JSON.stringify({
  419. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  420. }, null, 2) + '\n');
  421. antigravity.install('global', { autoAllow: true });
  422. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  423. expect(after.mcpServers.other).toBeDefined();
  424. expect(after.mcpServers.codegraph).toBeDefined();
  425. });
  426. it('antigravity: install preserves Antigravity-managed fields on sibling servers (e.g. disabled flag)', () => {
  427. const antigravity = getTarget('antigravity')!;
  428. // Antigravity adds `"disabled": true` to entries the user disables via
  429. // the IDE. Install must not clobber that on sibling entries.
  430. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  431. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  432. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  433. fs.writeFileSync(unified, JSON.stringify({
  434. mcpServers: {
  435. 'code-review-graph': {
  436. command: 'uvx', args: ['code-review-graph', 'serve'], disabled: true,
  437. },
  438. },
  439. }, null, 2) + '\n');
  440. antigravity.install('global', { autoAllow: true });
  441. const after = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  442. expect(after.mcpServers['code-review-graph'].disabled).toBe(true);
  443. expect(after.mcpServers.codegraph).toBeDefined();
  444. });
  445. it('antigravity: uninstall removes only codegraph, sibling MCP server survives', () => {
  446. const antigravity = getTarget('antigravity')!;
  447. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  448. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  449. fs.writeFileSync(mcpFile, JSON.stringify({
  450. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  451. }, null, 2) + '\n');
  452. antigravity.install('global', { autoAllow: true });
  453. antigravity.uninstall('global');
  454. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  455. expect(after.mcpServers.other).toBeDefined();
  456. expect(after.mcpServers.codegraph).toBeUndefined();
  457. });
  458. it('antigravity: uninstall sweeps BOTH legacy and unified paths (handles migration half-state)', () => {
  459. const antigravity = getTarget('antigravity')!;
  460. // User had codegraph in BOTH files (e.g. legacy install + post-migration
  461. // re-install before our migration cleanup landed). Uninstall must clean
  462. // both so a "fresh slate" really is fresh.
  463. const legacy = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  464. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  465. fs.mkdirSync(path.dirname(legacy), { recursive: true });
  466. fs.mkdirSync(path.dirname(unified), { recursive: true });
  467. fs.writeFileSync(legacy, JSON.stringify({
  468. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  469. }, null, 2) + '\n');
  470. fs.writeFileSync(unified, JSON.stringify({
  471. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  472. }, null, 2) + '\n');
  473. fs.writeFileSync(path.join(path.dirname(unified), '.migrated'), '');
  474. antigravity.uninstall('global');
  475. const legacyAfter = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  476. const unifiedAfter = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  477. expect(legacyAfter.mcpServers).toBeUndefined();
  478. expect(unifiedAfter.mcpServers).toBeUndefined();
  479. });
  480. it('antigravity: rejects --location=local with a clear note (global-only IDE)', () => {
  481. const antigravity = getTarget('antigravity')!;
  482. expect(antigravity.supportsLocation('local')).toBe(false);
  483. const result = antigravity.install('local', { autoAllow: true });
  484. expect(result.files).toEqual([]);
  485. expect(result.notes?.join(' ')).toMatch(/no project-local config/);
  486. });
  487. it('antigravity: does not write GEMINI.md (only gemini target owns instructions)', () => {
  488. const antigravity = getTarget('antigravity')!;
  489. antigravity.install('global', { autoAllow: true });
  490. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  491. expect(fs.existsSync(geminiMd)).toBe(false);
  492. });
  493. it('gemini + antigravity: both installed coexist (separate MCP files, shared GEMINI.md)', () => {
  494. const gemini = getTarget('gemini')!;
  495. const antigravity = getTarget('antigravity')!;
  496. gemini.install('global', { autoAllow: true });
  497. antigravity.install('global', { autoAllow: true });
  498. const cliCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  499. // Antigravity lands on the LEGACY path here since no .migrated marker
  500. // was planted — same end-to-end check either way.
  501. const ideCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'), 'utf-8'));
  502. expect(cliCfg.mcpServers.codegraph).toBeDefined();
  503. expect(ideCfg.mcpServers.codegraph).toBeDefined();
  504. // Uninstall one — the other's MCP entry must survive.
  505. antigravity.uninstall('global');
  506. const cliAfter = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  507. expect(cliAfter.mcpServers.codegraph).toBeDefined();
  508. });
  509. it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
  510. const hermes = getTarget('hermes')!;
  511. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  512. fs.mkdirSync(path.dirname(config), { recursive: true });
  513. fs.writeFileSync(config, [
  514. 'model:',
  515. ' default: qwen-3.7',
  516. 'mcp_servers:',
  517. ' other:',
  518. ' command: other',
  519. 'platform_toolsets:',
  520. ' cli:',
  521. ' - hermes-cli',
  522. ' discord:',
  523. ' - hermes-discord',
  524. '',
  525. ].join('\n'));
  526. const result = hermes.install('global', { autoAllow: true });
  527. expect(result.files[0].action).toBe('updated');
  528. const body = fs.readFileSync(config, 'utf-8');
  529. expect(body).toContain('model:\n default: qwen-3.7');
  530. expect(body).toContain('mcp_servers:\n other:\n command: other');
  531. expect(body).toContain(' codegraph:\n command: codegraph');
  532. expect(body).toContain(' - hermes-cli');
  533. expect(body).toContain(' - mcp-codegraph');
  534. expect(body).toContain(' discord:\n - hermes-discord');
  535. const second = hermes.install('global', { autoAllow: true });
  536. expect(second.files[0].action).toBe('unchanged');
  537. });
  538. it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
  539. const hermes = getTarget('hermes')!;
  540. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  541. fs.mkdirSync(path.dirname(config), { recursive: true });
  542. hermes.install('global', { autoAllow: true });
  543. fs.appendFileSync(config, 'custom:\n keep: true\n');
  544. hermes.uninstall('global');
  545. const body = fs.readFileSync(config, 'utf-8');
  546. expect(body).not.toContain('codegraph:');
  547. expect(body).not.toContain('mcp-codegraph');
  548. expect(body).toContain('custom:\n keep: true');
  549. });
  550. // Regression for #456: PyYAML's default block style writes list items at the
  551. // SAME indent as the parent key (`cli:` and its `- hermes-cli` are both at
  552. // indent 2). The pre-fix line-based patcher mistook that first list item for
  553. // the next sibling key, truncated the cli block, and spliced `- mcp-codegraph`
  554. // at indent 4 BEFORE the existing items — producing unparseable YAML.
  555. it('hermes: install preserves PyYAML-default list-at-same-indent style (issue #456)', () => {
  556. const hermes = getTarget('hermes')!;
  557. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  558. fs.mkdirSync(path.dirname(config), { recursive: true });
  559. const original = [
  560. 'model:',
  561. ' default: gpt-4o',
  562. 'platform_toolsets:',
  563. ' cli:',
  564. ' - hermes-cli',
  565. ' - browser',
  566. ' - clarify',
  567. ' - terminal',
  568. ' - web',
  569. ' telegram:',
  570. ' - hermes-telegram',
  571. ' discord:',
  572. ' - hermes-discord',
  573. '',
  574. ].join('\n');
  575. fs.writeFileSync(config, original);
  576. hermes.install('global', { autoAllow: true });
  577. const body = fs.readFileSync(config, 'utf-8');
  578. // mcp-codegraph appended at the same 2-space indent as existing items
  579. expect(body).toContain('\n - mcp-codegraph\n');
  580. // hermes-cli preserved
  581. expect(body).toContain('\n - hermes-cli\n');
  582. // Sibling sections kept their indent — `telegram:` is still a key under
  583. // platform_toolsets, not promoted up.
  584. expect(body).toContain('\n telegram:\n - hermes-telegram\n');
  585. expect(body).toContain('\n discord:\n - hermes-discord\n');
  586. // No list items leaked to the platform_toolsets level (indent 0).
  587. expect(body).not.toMatch(/^- browser/m);
  588. expect(body).not.toMatch(/^- hermes-telegram/m);
  589. // The whole platform_toolsets block extracted by line search should
  590. // start with `cli:` and not contain a stray 4-space `mcp-codegraph`
  591. // appearing before the rest of the existing items.
  592. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  593. // Idempotent
  594. const second = hermes.install('global', { autoAllow: true });
  595. expect(second.files[0]?.action).toBe('unchanged');
  596. });
  597. it('hermes: uninstall reverses the install on a PyYAML-default config', () => {
  598. const hermes = getTarget('hermes')!;
  599. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  600. fs.mkdirSync(path.dirname(config), { recursive: true });
  601. const original = [
  602. 'platform_toolsets:',
  603. ' cli:',
  604. ' - hermes-cli',
  605. ' - browser',
  606. ' telegram:',
  607. ' - hermes-telegram',
  608. '',
  609. ].join('\n');
  610. fs.writeFileSync(config, original);
  611. hermes.install('global', { autoAllow: true });
  612. const installed = fs.readFileSync(config, 'utf-8');
  613. expect(installed).toContain('- mcp-codegraph');
  614. expect(installed).toContain('codegraph:');
  615. hermes.uninstall('global');
  616. const body = fs.readFileSync(config, 'utf-8');
  617. expect(body).not.toContain('mcp-codegraph');
  618. expect(body).not.toContain('command: codegraph');
  619. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  620. expect(body).toContain(' telegram:\n - hermes-telegram');
  621. });
  622. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  623. const opencode = getTarget('opencode')!;
  624. const dir = path.join(tmpHome, '.config', 'opencode');
  625. fs.mkdirSync(dir, { recursive: true });
  626. const file = path.join(dir, 'opencode.jsonc');
  627. fs.writeFileSync(file, [
  628. '{',
  629. ' // important comment',
  630. ' "$schema": "https://opencode.ai/config.json",',
  631. ' "mcp": {',
  632. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  633. ' }',
  634. '}',
  635. '',
  636. ].join('\n'));
  637. opencode.install('global', { autoAllow: true });
  638. const afterInstall = fs.readFileSync(file, 'utf-8');
  639. expect(afterInstall).toContain('"codegraph"');
  640. expect(afterInstall).toContain('"other"');
  641. opencode.uninstall('global');
  642. const afterUninstall = fs.readFileSync(file, 'utf-8');
  643. expect(afterUninstall).not.toContain('codegraph');
  644. expect(afterUninstall).toContain('// important comment');
  645. expect(afterUninstall).toContain('"other"');
  646. });
  647. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  648. const codex = getTarget('codex')!;
  649. codex.install('global', { autoAllow: false });
  650. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  651. const original = fs.readFileSync(tomlPath, 'utf-8');
  652. // User edits the block to add a custom key.
  653. const edited = original.replace(
  654. 'args = ["serve", "--mcp"]',
  655. 'args = ["serve", "--mcp"]\nenabled = true',
  656. );
  657. fs.writeFileSync(tomlPath, edited);
  658. // Re-install: our serializer doesn't know `enabled = true`, so
  659. // the block no longer matches the canonical form — we'll
  660. // overwrite it. This is the documented contract: we own the
  661. // codegraph block exclusively.
  662. const second = codex.install('global', { autoAllow: false });
  663. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  664. expect(tomlEntry.action).toBe('updated');
  665. const after = fs.readFileSync(tomlPath, 'utf-8');
  666. expect(after).not.toContain('enabled = true');
  667. });
  668. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  669. const claude = getTarget('claude')!;
  670. const result = claude.install('local', { autoAllow: false });
  671. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  672. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  673. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  674. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  675. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  676. expect(cfg.mcpServers.codegraph).toBeDefined();
  677. });
  678. it('claude: global install targets ~/.claude.json (user scope)', () => {
  679. const claude = getTarget('claude')!;
  680. claude.install('global', { autoAllow: false });
  681. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  682. expect(cfg.mcpServers.codegraph).toBeDefined();
  683. });
  684. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  685. const claude = getTarget('claude')!;
  686. const legacy = path.join(tmpCwd, '.claude.json');
  687. fs.writeFileSync(
  688. legacy,
  689. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  690. );
  691. claude.install('local', { autoAllow: false });
  692. // codegraph now lives in .mcp.json; the legacy file (which held only
  693. // codegraph) is gone.
  694. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  695. expect(mcp.mcpServers.codegraph).toBeDefined();
  696. expect(fs.existsSync(legacy)).toBe(false);
  697. });
  698. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  699. const claude = getTarget('claude')!;
  700. const legacy = path.join(tmpCwd, '.claude.json');
  701. fs.writeFileSync(
  702. legacy,
  703. JSON.stringify({
  704. mcpServers: {
  705. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  706. other: { command: 'x' },
  707. },
  708. somethingElse: true,
  709. }, null, 2),
  710. );
  711. claude.install('local', { autoAllow: false });
  712. // Only codegraph is stripped from the legacy file; siblings survive.
  713. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  714. expect(after.mcpServers.codegraph).toBeUndefined();
  715. expect(after.mcpServers.other).toBeDefined();
  716. expect(after.somethingElse).toBe(true);
  717. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  718. expect(mcp.mcpServers.codegraph).toBeDefined();
  719. });
  720. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  721. const claude = getTarget('claude')!;
  722. // A user left with both the working .mcp.json and a stale .claude.json.
  723. fs.writeFileSync(
  724. path.join(tmpCwd, '.mcp.json'),
  725. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  726. );
  727. fs.writeFileSync(
  728. path.join(tmpCwd, '.claude.json'),
  729. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  730. );
  731. claude.uninstall('local');
  732. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  733. expect(mcp.mcpServers).toBeUndefined();
  734. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  735. expect(legacy.mcpServers.codegraph).toBeUndefined();
  736. expect(legacy.mcpServers.other).toBeDefined();
  737. });
  738. // ---- Legacy auto-sync hook cleanup ----
  739. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  740. // hooks to settings.json. Both subcommands were removed from the CLI,
  741. // so the Stop hook fails every turn ("unknown command
  742. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  743. // uninstall — without touching the user's unrelated hooks.
  744. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  745. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  746. fs.mkdirSync(dir, { recursive: true });
  747. const file = path.join(dir, 'settings.json');
  748. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  749. return file;
  750. }
  751. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  752. // unrelated GitKraken Stop hook the user added (matches the report).
  753. function legacyHookSettings(): Record<string, any> {
  754. return {
  755. hooks: {
  756. PostToolUse: [
  757. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  758. ],
  759. Stop: [
  760. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  761. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  762. ],
  763. },
  764. };
  765. }
  766. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  767. const claude = getTarget('claude')!;
  768. const file = seedSettings('global', legacyHookSettings());
  769. claude.install('global', { autoAllow: true });
  770. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  771. // The only PostToolUse group held mark-dirty → the event is gone.
  772. expect(after.hooks?.PostToolUse).toBeUndefined();
  773. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  774. (g.hooks ?? []).map((h: any) => h.command),
  775. );
  776. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  777. // The unrelated GitKraken hook survives untouched.
  778. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  779. // Permissions still written as normal alongside the cleanup.
  780. expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
  781. });
  782. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  783. const file = seedSettings('global', {
  784. hooks: {
  785. Stop: [
  786. {
  787. hooks: [
  788. { type: 'command', command: 'codegraph sync-if-dirty' },
  789. { type: 'command', command: 'gk ai hook run --host claude-code' },
  790. ],
  791. },
  792. ],
  793. },
  794. });
  795. expect(cleanupLegacyHooks('global').action).toBe('removed');
  796. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  797. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  798. 'gk ai hook run --host claude-code',
  799. ]);
  800. });
  801. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  802. const original =
  803. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  804. const file = seedSettings('global', JSON.parse(original));
  805. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  806. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  807. });
  808. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  809. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  810. });
  811. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  812. const claude = getTarget('claude')!;
  813. const file = seedSettings('global', legacyHookSettings());
  814. claude.install('global', { autoAllow: true });
  815. const firstPass = fs.readFileSync(file, 'utf-8');
  816. claude.install('global', { autoAllow: true });
  817. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  818. });
  819. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  820. const claude = getTarget('claude')!;
  821. const file = seedSettings('local', {
  822. hooks: {
  823. PostToolUse: [
  824. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  825. ],
  826. Stop: [
  827. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  828. ],
  829. },
  830. });
  831. claude.uninstall('local');
  832. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  833. // Both events emptied → the whole `hooks` object is removed.
  834. expect(after.hooks).toBeUndefined();
  835. });
  836. });
  837. describe('Installer targets — registry', () => {
  838. it('getTarget returns the right target for each id', () => {
  839. expect(getTarget('claude')?.id).toBe('claude');
  840. expect(getTarget('cursor')?.id).toBe('cursor');
  841. expect(getTarget('codex')?.id).toBe('codex');
  842. expect(getTarget('opencode')?.id).toBe('opencode');
  843. expect(getTarget('hermes')?.id).toBe('hermes');
  844. expect(getTarget('gemini')?.id).toBe('gemini');
  845. expect(getTarget('antigravity')?.id).toBe('antigravity');
  846. expect(getTarget('not-a-real-target')).toBeUndefined();
  847. });
  848. it('resolveTargetFlag handles auto/all/none/csv', () => {
  849. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  850. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  851. const csv = resolveTargetFlag('claude,cursor', 'global');
  852. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  853. });
  854. it('resolveTargetFlag throws on unknown id', () => {
  855. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  856. });
  857. });
  858. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  859. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  860. const block = buildTomlTable('mcp_servers.codegraph', {
  861. command: 'codegraph',
  862. args: ['serve', '--mcp'],
  863. });
  864. expect(block).toContain('[mcp_servers.codegraph]');
  865. expect(block).toContain('command = "codegraph"');
  866. expect(block).toContain('args = ["serve", "--mcp"]');
  867. });
  868. it('upsert inserts into empty content', () => {
  869. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  870. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  871. expect(action).toBe('inserted');
  872. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  873. });
  874. it('upsert is idempotent — second call returns unchanged', () => {
  875. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  876. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  877. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  878. expect(second.action).toBe('unchanged');
  879. expect(second.content).toBe(first.content);
  880. });
  881. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  882. const existing = [
  883. '[other_table]',
  884. 'foo = "bar"',
  885. '',
  886. '[mcp_servers.codegraph]',
  887. 'command = "old-codegraph"',
  888. 'args = ["old"]',
  889. '',
  890. '[zzz]',
  891. 'baz = "qux"',
  892. '',
  893. ].join('\n');
  894. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  895. command: 'codegraph',
  896. args: ['serve', '--mcp'],
  897. });
  898. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  899. expect(action).toBe('replaced');
  900. expect(content).toContain('[other_table]');
  901. expect(content).toContain('foo = "bar"');
  902. expect(content).toContain('[zzz]');
  903. expect(content).toContain('baz = "qux"');
  904. expect(content).toContain('command = "codegraph"');
  905. expect(content).not.toContain('old-codegraph');
  906. });
  907. it('removeTomlTable strips the block and preserves siblings', () => {
  908. const existing = [
  909. '[other_table]',
  910. 'foo = "bar"',
  911. '',
  912. '[mcp_servers.codegraph]',
  913. 'command = "codegraph"',
  914. 'args = ["serve"]',
  915. ].join('\n');
  916. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  917. expect(action).toBe('removed');
  918. expect(content).toContain('[other_table]');
  919. expect(content).toContain('foo = "bar"');
  920. expect(content).not.toContain('mcp_servers.codegraph');
  921. });
  922. it('removeTomlTable on missing table returns not-found, no content change', () => {
  923. const existing = '[other]\nfoo = "bar"\n';
  924. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  925. expect(action).toBe('not-found');
  926. expect(content).toBe(existing);
  927. });
  928. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  929. const existing = [
  930. '[[foo]]',
  931. 'name = "a"',
  932. '',
  933. '[[foo]]',
  934. 'name = "b"',
  935. '',
  936. ].join('\n');
  937. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  938. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  939. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  940. expect(content).toContain('[mcp_servers.codegraph]');
  941. });
  942. });
  943. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  944. let tmpHome: string;
  945. let tmpCwd: string;
  946. let origCwd: string;
  947. let homeRestore: { restore: () => void };
  948. beforeEach(() => {
  949. tmpHome = mkTmpDir('un-home');
  950. tmpCwd = mkTmpDir('un-cwd');
  951. origCwd = process.cwd();
  952. process.chdir(tmpCwd);
  953. homeRestore = setHome(tmpHome);
  954. });
  955. afterEach(() => {
  956. homeRestore.restore();
  957. process.chdir(origCwd);
  958. fs.rmSync(tmpHome, { recursive: true, force: true });
  959. fs.rmSync(tmpCwd, { recursive: true, force: true });
  960. });
  961. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  962. for (const t of ALL_TARGETS) {
  963. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  964. }
  965. const reports = uninstallTargets(ALL_TARGETS, 'global');
  966. for (const t of ALL_TARGETS) {
  967. const r = reports.find((x) => x.id === t.id)!;
  968. expect(r.status).toBe('removed');
  969. expect(r.removedPaths.length).toBeGreaterThan(0);
  970. // The actual config is gone afterward.
  971. expect(t.detect('global').alreadyConfigured).toBe(false);
  972. }
  973. });
  974. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  975. const reports = uninstallTargets(ALL_TARGETS, 'global');
  976. for (const r of reports) {
  977. expect(r.status).toBe('not-configured');
  978. expect(r.removedPaths).toEqual([]);
  979. }
  980. });
  981. it('reports removed only for agents that were actually configured', () => {
  982. // Install on Claude only; the rest stay untouched.
  983. getTarget('claude')!.install('global', { autoAllow: true });
  984. const reports = uninstallTargets(ALL_TARGETS, 'global');
  985. const claude = reports.find((r) => r.id === 'claude')!;
  986. expect(claude.status).toBe('removed');
  987. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  988. for (const r of reports.filter((x) => x.id !== 'claude')) {
  989. expect(r.status).toBe('not-configured');
  990. }
  991. });
  992. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  993. const reports = uninstallTargets(ALL_TARGETS, 'local');
  994. for (const t of ALL_TARGETS) {
  995. const r = reports.find((x) => x.id === t.id)!;
  996. if (t.supportsLocation('local')) {
  997. expect(r.status).toBe('not-configured');
  998. } else {
  999. expect(r.status).toBe('unsupported');
  1000. expect(r.removedPaths).toEqual([]);
  1001. expect(r.notes[0]).toMatch(/global-only/);
  1002. }
  1003. }
  1004. });
  1005. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1006. for (const t of ALL_TARGETS) {
  1007. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1008. }
  1009. const first = uninstallTargets(ALL_TARGETS, 'global');
  1010. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1011. const second = uninstallTargets(ALL_TARGETS, 'global');
  1012. for (const r of second) {
  1013. expect(r.status).toBe('not-configured');
  1014. expect(r.removedPaths).toEqual([]);
  1015. }
  1016. });
  1017. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1018. getTarget('claude')!.install('global', { autoAllow: true });
  1019. getTarget('cursor')!.install('global', { autoAllow: true });
  1020. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1021. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1022. expect(reports[0].status).toBe('removed');
  1023. // Cursor was not in the subset — still configured.
  1024. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1025. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1026. });
  1027. });
  1028. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1029. let tmpHome: string;
  1030. let tmpCwd: string;
  1031. let origCwd: string;
  1032. let homeRestore: { restore: () => void };
  1033. const cursor = getTarget('cursor')!;
  1034. beforeEach(() => {
  1035. tmpHome = mkTmpDir('cur-home');
  1036. tmpCwd = mkTmpDir('cur-cwd');
  1037. origCwd = process.cwd();
  1038. process.chdir(tmpCwd);
  1039. homeRestore = setHome(tmpHome);
  1040. });
  1041. afterEach(() => {
  1042. homeRestore.restore();
  1043. process.chdir(origCwd);
  1044. fs.rmSync(tmpHome, { recursive: true, force: true });
  1045. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1046. });
  1047. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1048. it('deletes the dedicated codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1049. cursor.install('local', { autoAllow: true });
  1050. expect(fs.existsSync(rulesFile())).toBe(true);
  1051. cursor.uninstall('local');
  1052. // The whole file — frontmatter included — is gone, not just the block.
  1053. expect(fs.existsSync(rulesFile())).toBe(false);
  1054. expect(cursor.detect('local').alreadyConfigured).toBe(false);
  1055. });
  1056. it('preserves user content added outside the codegraph markers (strips only our block)', () => {
  1057. cursor.install('local', { autoAllow: true });
  1058. const withUserContent =
  1059. fs.readFileSync(rulesFile(), 'utf-8') + '\n## My own rule\nkeep me\n';
  1060. fs.writeFileSync(rulesFile(), withUserContent);
  1061. cursor.uninstall('local');
  1062. expect(fs.existsSync(rulesFile())).toBe(true);
  1063. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1064. expect(after).toContain('keep me');
  1065. // Our tool-usage block is gone.
  1066. expect(after).not.toContain('codegraph_search');
  1067. expect(after).not.toContain('CODEGRAPH_START');
  1068. });
  1069. });
  1070. function listAllFiles(dir: string): string[] {
  1071. if (!fs.existsSync(dir)) return [];
  1072. const out: string[] = [];
  1073. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1074. const full = path.join(dir, entry.name);
  1075. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1076. else out.push(full);
  1077. }
  1078. return out;
  1079. }