installer-targets.test.ts 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322
  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('kiro: install writes settings/mcp.json (mcpServers.codegraph) and steering/codegraph.md', () => {
  343. const kiro = getTarget('kiro')!;
  344. const result = kiro.install('global', { autoAllow: true });
  345. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  346. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  347. expect(result.files.some((f) => f.path === mcp)).toBe(true);
  348. expect(result.files.some((f) => f.path === steering)).toBe(true);
  349. const cfg = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  350. expect(cfg.mcpServers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  351. const md = fs.readFileSync(steering, 'utf-8');
  352. expect(md).toContain('codegraph_callers');
  353. expect(md).toContain('CodeGraph MCP server');
  354. });
  355. it('kiro: install preserves a pre-existing sibling MCP server in mcp.json', () => {
  356. const kiro = getTarget('kiro')!;
  357. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  358. fs.mkdirSync(path.dirname(mcp), { recursive: true });
  359. fs.writeFileSync(mcp, JSON.stringify({
  360. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  361. }, null, 2) + '\n');
  362. kiro.install('global', { autoAllow: true });
  363. const after = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  364. expect(after.mcpServers.other).toBeDefined();
  365. expect(after.mcpServers.codegraph).toBeDefined();
  366. });
  367. it('kiro: uninstall strips codegraph but leaves sibling MCP servers intact', () => {
  368. const kiro = getTarget('kiro')!;
  369. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  370. fs.mkdirSync(path.dirname(mcp), { recursive: true });
  371. fs.writeFileSync(mcp, JSON.stringify({
  372. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  373. }, null, 2) + '\n');
  374. kiro.install('global', { autoAllow: true });
  375. kiro.uninstall('global');
  376. const after = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  377. expect(after.mcpServers.other).toBeDefined();
  378. expect(after.mcpServers.codegraph).toBeUndefined();
  379. });
  380. it('kiro: uninstall removes the steering codegraph.md file outright', () => {
  381. const kiro = getTarget('kiro')!;
  382. kiro.install('global', { autoAllow: true });
  383. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  384. expect(fs.existsSync(steering)).toBe(true);
  385. kiro.uninstall('global');
  386. expect(fs.existsSync(steering)).toBe(false);
  387. });
  388. it('kiro: uninstall leaves a sibling steering file (product.md) untouched', () => {
  389. const kiro = getTarget('kiro')!;
  390. const sibling = path.join(tmpHome, '.kiro', 'steering', 'product.md');
  391. fs.mkdirSync(path.dirname(sibling), { recursive: true });
  392. fs.writeFileSync(sibling, '# Product\n\nMy team practices.\n');
  393. kiro.install('global', { autoAllow: true });
  394. kiro.uninstall('global');
  395. expect(fs.existsSync(sibling)).toBe(true);
  396. expect(fs.readFileSync(sibling, 'utf-8')).toContain('My team practices.');
  397. });
  398. it('kiro: local install writes ./.kiro/settings/mcp.json and ./.kiro/steering/codegraph.md', () => {
  399. const kiro = getTarget('kiro')!;
  400. const result = kiro.install('local', { autoAllow: true });
  401. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  402. expect(paths.some((p) => p.endsWith('/.kiro/settings/mcp.json'))).toBe(true);
  403. expect(paths.some((p) => p.endsWith('/.kiro/steering/codegraph.md'))).toBe(true);
  404. });
  405. it('antigravity: install writes to LEGACY ~/.gemini/antigravity/mcp_config.json when no migration marker', () => {
  406. const antigravity = getTarget('antigravity')!;
  407. antigravity.install('global', { autoAllow: true });
  408. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  409. expect(fs.existsSync(legacyFile)).toBe(true);
  410. const cfg = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  411. expect(cfg.mcpServers.codegraph).toBeDefined();
  412. // Crucially: does NOT touch the Gemini CLI's settings.json.
  413. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'settings.json'))).toBe(false);
  414. });
  415. it('antigravity: install writes to UNIFIED ~/.gemini/config/mcp_config.json when .migrated marker present', () => {
  416. const antigravity = getTarget('antigravity')!;
  417. // Plant the migration marker — same signal Antigravity itself drops
  418. // when it migrates a user's config.
  419. const unifiedDir = path.join(tmpHome, '.gemini', 'config');
  420. fs.mkdirSync(unifiedDir, { recursive: true });
  421. fs.writeFileSync(path.join(unifiedDir, '.migrated'), '');
  422. antigravity.install('global', { autoAllow: true });
  423. const unifiedFile = path.join(unifiedDir, 'mcp_config.json');
  424. expect(fs.existsSync(unifiedFile)).toBe(true);
  425. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  426. expect(cfg.mcpServers.codegraph).toBeDefined();
  427. // Legacy path is NOT touched when the marker tells us migration happened.
  428. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'))).toBe(false);
  429. });
  430. it('antigravity: install writes to UNIFIED path when ~/.gemini/config/mcp_config.json already exists (even without marker)', () => {
  431. const antigravity = getTarget('antigravity')!;
  432. // Antigravity creates this file on first launch post-migration — its
  433. // presence is the second signal we accept, in case the .migrated
  434. // marker semantics change across Antigravity versions.
  435. const unifiedFile = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  436. fs.mkdirSync(path.dirname(unifiedFile), { recursive: true });
  437. fs.writeFileSync(unifiedFile, JSON.stringify({ mcpServers: {} }, null, 2) + '\n');
  438. antigravity.install('global', { autoAllow: true });
  439. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  440. expect(cfg.mcpServers.codegraph).toBeDefined();
  441. });
  442. it('antigravity: entry has NO `type` field (Antigravity rejects entries with it)', () => {
  443. const antigravity = getTarget('antigravity')!;
  444. // Marker → unified path; doesn't matter which path, just inspect the entry shape.
  445. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  446. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  447. antigravity.install('global', { autoAllow: true });
  448. const cfg = JSON.parse(fs.readFileSync(
  449. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  450. ));
  451. expect(cfg.mcpServers.codegraph.type).toBeUndefined();
  452. expect(cfg.mcpServers.codegraph.command).toBeDefined();
  453. expect(cfg.mcpServers.codegraph.args).toEqual(['serve', '--mcp']);
  454. });
  455. it('antigravity: install migrates a legacy codegraph entry to the unified path when marker appears', () => {
  456. const antigravity = getTarget('antigravity')!;
  457. // Simulate: user installed on the legacy path, then Antigravity
  458. // migrated their config (dropped the `.migrated` marker + created
  459. // the unified file). Re-running codegraph install should land
  460. // codegraph in the new file AND strip the stale legacy entry.
  461. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  462. fs.mkdirSync(path.dirname(legacyFile), { recursive: true });
  463. fs.writeFileSync(legacyFile, JSON.stringify({
  464. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  465. }, null, 2) + '\n');
  466. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  467. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  468. antigravity.install('global', { autoAllow: true });
  469. const unified = JSON.parse(fs.readFileSync(
  470. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  471. ));
  472. expect(unified.mcpServers.codegraph).toBeDefined();
  473. // Legacy file's codegraph entry got stripped.
  474. const legacy = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  475. expect(legacy.mcpServers).toBeUndefined();
  476. });
  477. it('antigravity: install preserves a sibling MCP server in mcp_config.json (legacy path)', () => {
  478. const antigravity = getTarget('antigravity')!;
  479. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  480. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  481. fs.writeFileSync(mcpFile, JSON.stringify({
  482. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  483. }, null, 2) + '\n');
  484. antigravity.install('global', { autoAllow: true });
  485. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  486. expect(after.mcpServers.other).toBeDefined();
  487. expect(after.mcpServers.codegraph).toBeDefined();
  488. });
  489. it('antigravity: install preserves Antigravity-managed fields on sibling servers (e.g. disabled flag)', () => {
  490. const antigravity = getTarget('antigravity')!;
  491. // Antigravity adds `"disabled": true` to entries the user disables via
  492. // the IDE. Install must not clobber that on sibling entries.
  493. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  494. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  495. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  496. fs.writeFileSync(unified, JSON.stringify({
  497. mcpServers: {
  498. 'code-review-graph': {
  499. command: 'uvx', args: ['code-review-graph', 'serve'], disabled: true,
  500. },
  501. },
  502. }, null, 2) + '\n');
  503. antigravity.install('global', { autoAllow: true });
  504. const after = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  505. expect(after.mcpServers['code-review-graph'].disabled).toBe(true);
  506. expect(after.mcpServers.codegraph).toBeDefined();
  507. });
  508. it('antigravity: uninstall removes only codegraph, sibling MCP server survives', () => {
  509. const antigravity = getTarget('antigravity')!;
  510. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  511. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  512. fs.writeFileSync(mcpFile, JSON.stringify({
  513. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  514. }, null, 2) + '\n');
  515. antigravity.install('global', { autoAllow: true });
  516. antigravity.uninstall('global');
  517. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  518. expect(after.mcpServers.other).toBeDefined();
  519. expect(after.mcpServers.codegraph).toBeUndefined();
  520. });
  521. it('antigravity: uninstall sweeps BOTH legacy and unified paths (handles migration half-state)', () => {
  522. const antigravity = getTarget('antigravity')!;
  523. // User had codegraph in BOTH files (e.g. legacy install + post-migration
  524. // re-install before our migration cleanup landed). Uninstall must clean
  525. // both so a "fresh slate" really is fresh.
  526. const legacy = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  527. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  528. fs.mkdirSync(path.dirname(legacy), { recursive: true });
  529. fs.mkdirSync(path.dirname(unified), { recursive: true });
  530. fs.writeFileSync(legacy, JSON.stringify({
  531. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  532. }, null, 2) + '\n');
  533. fs.writeFileSync(unified, JSON.stringify({
  534. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  535. }, null, 2) + '\n');
  536. fs.writeFileSync(path.join(path.dirname(unified), '.migrated'), '');
  537. antigravity.uninstall('global');
  538. const legacyAfter = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  539. const unifiedAfter = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  540. expect(legacyAfter.mcpServers).toBeUndefined();
  541. expect(unifiedAfter.mcpServers).toBeUndefined();
  542. });
  543. it('antigravity: rejects --location=local with a clear note (global-only IDE)', () => {
  544. const antigravity = getTarget('antigravity')!;
  545. expect(antigravity.supportsLocation('local')).toBe(false);
  546. const result = antigravity.install('local', { autoAllow: true });
  547. expect(result.files).toEqual([]);
  548. expect(result.notes?.join(' ')).toMatch(/no project-local config/);
  549. });
  550. it('antigravity: does not write GEMINI.md (only gemini target owns instructions)', () => {
  551. const antigravity = getTarget('antigravity')!;
  552. antigravity.install('global', { autoAllow: true });
  553. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  554. expect(fs.existsSync(geminiMd)).toBe(false);
  555. });
  556. it('gemini + antigravity: both installed coexist (separate MCP files, shared GEMINI.md)', () => {
  557. const gemini = getTarget('gemini')!;
  558. const antigravity = getTarget('antigravity')!;
  559. gemini.install('global', { autoAllow: true });
  560. antigravity.install('global', { autoAllow: true });
  561. const cliCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  562. // Antigravity lands on the LEGACY path here since no .migrated marker
  563. // was planted — same end-to-end check either way.
  564. const ideCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'), 'utf-8'));
  565. expect(cliCfg.mcpServers.codegraph).toBeDefined();
  566. expect(ideCfg.mcpServers.codegraph).toBeDefined();
  567. // Uninstall one — the other's MCP entry must survive.
  568. antigravity.uninstall('global');
  569. const cliAfter = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  570. expect(cliAfter.mcpServers.codegraph).toBeDefined();
  571. });
  572. it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
  573. const hermes = getTarget('hermes')!;
  574. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  575. fs.mkdirSync(path.dirname(config), { recursive: true });
  576. fs.writeFileSync(config, [
  577. 'model:',
  578. ' default: qwen-3.7',
  579. 'mcp_servers:',
  580. ' other:',
  581. ' command: other',
  582. 'platform_toolsets:',
  583. ' cli:',
  584. ' - hermes-cli',
  585. ' discord:',
  586. ' - hermes-discord',
  587. '',
  588. ].join('\n'));
  589. const result = hermes.install('global', { autoAllow: true });
  590. expect(result.files[0].action).toBe('updated');
  591. const body = fs.readFileSync(config, 'utf-8');
  592. expect(body).toContain('model:\n default: qwen-3.7');
  593. expect(body).toContain('mcp_servers:\n other:\n command: other');
  594. expect(body).toContain(' codegraph:\n command: codegraph');
  595. expect(body).toContain(' - hermes-cli');
  596. expect(body).toContain(' - mcp-codegraph');
  597. expect(body).toContain(' discord:\n - hermes-discord');
  598. const second = hermes.install('global', { autoAllow: true });
  599. expect(second.files[0].action).toBe('unchanged');
  600. });
  601. it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
  602. const hermes = getTarget('hermes')!;
  603. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  604. fs.mkdirSync(path.dirname(config), { recursive: true });
  605. hermes.install('global', { autoAllow: true });
  606. fs.appendFileSync(config, 'custom:\n keep: true\n');
  607. hermes.uninstall('global');
  608. const body = fs.readFileSync(config, 'utf-8');
  609. expect(body).not.toContain('codegraph:');
  610. expect(body).not.toContain('mcp-codegraph');
  611. expect(body).toContain('custom:\n keep: true');
  612. });
  613. // Regression for #456: PyYAML's default block style writes list items at the
  614. // SAME indent as the parent key (`cli:` and its `- hermes-cli` are both at
  615. // indent 2). The pre-fix line-based patcher mistook that first list item for
  616. // the next sibling key, truncated the cli block, and spliced `- mcp-codegraph`
  617. // at indent 4 BEFORE the existing items — producing unparseable YAML.
  618. it('hermes: install preserves PyYAML-default list-at-same-indent style (issue #456)', () => {
  619. const hermes = getTarget('hermes')!;
  620. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  621. fs.mkdirSync(path.dirname(config), { recursive: true });
  622. const original = [
  623. 'model:',
  624. ' default: gpt-4o',
  625. 'platform_toolsets:',
  626. ' cli:',
  627. ' - hermes-cli',
  628. ' - browser',
  629. ' - clarify',
  630. ' - terminal',
  631. ' - web',
  632. ' telegram:',
  633. ' - hermes-telegram',
  634. ' discord:',
  635. ' - hermes-discord',
  636. '',
  637. ].join('\n');
  638. fs.writeFileSync(config, original);
  639. hermes.install('global', { autoAllow: true });
  640. const body = fs.readFileSync(config, 'utf-8');
  641. // mcp-codegraph appended at the same 2-space indent as existing items
  642. expect(body).toContain('\n - mcp-codegraph\n');
  643. // hermes-cli preserved
  644. expect(body).toContain('\n - hermes-cli\n');
  645. // Sibling sections kept their indent — `telegram:` is still a key under
  646. // platform_toolsets, not promoted up.
  647. expect(body).toContain('\n telegram:\n - hermes-telegram\n');
  648. expect(body).toContain('\n discord:\n - hermes-discord\n');
  649. // No list items leaked to the platform_toolsets level (indent 0).
  650. expect(body).not.toMatch(/^- browser/m);
  651. expect(body).not.toMatch(/^- hermes-telegram/m);
  652. // The whole platform_toolsets block extracted by line search should
  653. // start with `cli:` and not contain a stray 4-space `mcp-codegraph`
  654. // appearing before the rest of the existing items.
  655. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  656. // Idempotent
  657. const second = hermes.install('global', { autoAllow: true });
  658. expect(second.files[0]?.action).toBe('unchanged');
  659. });
  660. it('hermes: uninstall reverses the install on a PyYAML-default config', () => {
  661. const hermes = getTarget('hermes')!;
  662. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  663. fs.mkdirSync(path.dirname(config), { recursive: true });
  664. const original = [
  665. 'platform_toolsets:',
  666. ' cli:',
  667. ' - hermes-cli',
  668. ' - browser',
  669. ' telegram:',
  670. ' - hermes-telegram',
  671. '',
  672. ].join('\n');
  673. fs.writeFileSync(config, original);
  674. hermes.install('global', { autoAllow: true });
  675. const installed = fs.readFileSync(config, 'utf-8');
  676. expect(installed).toContain('- mcp-codegraph');
  677. expect(installed).toContain('codegraph:');
  678. hermes.uninstall('global');
  679. const body = fs.readFileSync(config, 'utf-8');
  680. expect(body).not.toContain('mcp-codegraph');
  681. expect(body).not.toContain('command: codegraph');
  682. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  683. expect(body).toContain(' telegram:\n - hermes-telegram');
  684. });
  685. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  686. const opencode = getTarget('opencode')!;
  687. const dir = path.join(tmpHome, '.config', 'opencode');
  688. fs.mkdirSync(dir, { recursive: true });
  689. const file = path.join(dir, 'opencode.jsonc');
  690. fs.writeFileSync(file, [
  691. '{',
  692. ' // important comment',
  693. ' "$schema": "https://opencode.ai/config.json",',
  694. ' "mcp": {',
  695. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  696. ' }',
  697. '}',
  698. '',
  699. ].join('\n'));
  700. opencode.install('global', { autoAllow: true });
  701. const afterInstall = fs.readFileSync(file, 'utf-8');
  702. expect(afterInstall).toContain('"codegraph"');
  703. expect(afterInstall).toContain('"other"');
  704. opencode.uninstall('global');
  705. const afterUninstall = fs.readFileSync(file, 'utf-8');
  706. expect(afterUninstall).not.toContain('codegraph');
  707. expect(afterUninstall).toContain('// important comment');
  708. expect(afterUninstall).toContain('"other"');
  709. });
  710. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  711. const codex = getTarget('codex')!;
  712. codex.install('global', { autoAllow: false });
  713. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  714. const original = fs.readFileSync(tomlPath, 'utf-8');
  715. // User edits the block to add a custom key.
  716. const edited = original.replace(
  717. 'args = ["serve", "--mcp"]',
  718. 'args = ["serve", "--mcp"]\nenabled = true',
  719. );
  720. fs.writeFileSync(tomlPath, edited);
  721. // Re-install: our serializer doesn't know `enabled = true`, so
  722. // the block no longer matches the canonical form — we'll
  723. // overwrite it. This is the documented contract: we own the
  724. // codegraph block exclusively.
  725. const second = codex.install('global', { autoAllow: false });
  726. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  727. expect(tomlEntry.action).toBe('updated');
  728. const after = fs.readFileSync(tomlPath, 'utf-8');
  729. expect(after).not.toContain('enabled = true');
  730. });
  731. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  732. const claude = getTarget('claude')!;
  733. const result = claude.install('local', { autoAllow: false });
  734. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  735. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  736. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  737. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  738. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  739. expect(cfg.mcpServers.codegraph).toBeDefined();
  740. });
  741. it('claude: global install targets ~/.claude.json (user scope)', () => {
  742. const claude = getTarget('claude')!;
  743. claude.install('global', { autoAllow: false });
  744. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  745. expect(cfg.mcpServers.codegraph).toBeDefined();
  746. });
  747. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  748. const claude = getTarget('claude')!;
  749. const legacy = path.join(tmpCwd, '.claude.json');
  750. fs.writeFileSync(
  751. legacy,
  752. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  753. );
  754. claude.install('local', { autoAllow: false });
  755. // codegraph now lives in .mcp.json; the legacy file (which held only
  756. // codegraph) is gone.
  757. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  758. expect(mcp.mcpServers.codegraph).toBeDefined();
  759. expect(fs.existsSync(legacy)).toBe(false);
  760. });
  761. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  762. const claude = getTarget('claude')!;
  763. const legacy = path.join(tmpCwd, '.claude.json');
  764. fs.writeFileSync(
  765. legacy,
  766. JSON.stringify({
  767. mcpServers: {
  768. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  769. other: { command: 'x' },
  770. },
  771. somethingElse: true,
  772. }, null, 2),
  773. );
  774. claude.install('local', { autoAllow: false });
  775. // Only codegraph is stripped from the legacy file; siblings survive.
  776. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  777. expect(after.mcpServers.codegraph).toBeUndefined();
  778. expect(after.mcpServers.other).toBeDefined();
  779. expect(after.somethingElse).toBe(true);
  780. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  781. expect(mcp.mcpServers.codegraph).toBeDefined();
  782. });
  783. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  784. const claude = getTarget('claude')!;
  785. // A user left with both the working .mcp.json and a stale .claude.json.
  786. fs.writeFileSync(
  787. path.join(tmpCwd, '.mcp.json'),
  788. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  789. );
  790. fs.writeFileSync(
  791. path.join(tmpCwd, '.claude.json'),
  792. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  793. );
  794. claude.uninstall('local');
  795. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  796. expect(mcp.mcpServers).toBeUndefined();
  797. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  798. expect(legacy.mcpServers.codegraph).toBeUndefined();
  799. expect(legacy.mcpServers.other).toBeDefined();
  800. });
  801. // ---- Legacy auto-sync hook cleanup ----
  802. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  803. // hooks to settings.json. Both subcommands were removed from the CLI,
  804. // so the Stop hook fails every turn ("unknown command
  805. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  806. // uninstall — without touching the user's unrelated hooks.
  807. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  808. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  809. fs.mkdirSync(dir, { recursive: true });
  810. const file = path.join(dir, 'settings.json');
  811. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  812. return file;
  813. }
  814. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  815. // unrelated GitKraken Stop hook the user added (matches the report).
  816. function legacyHookSettings(): Record<string, any> {
  817. return {
  818. hooks: {
  819. PostToolUse: [
  820. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  821. ],
  822. Stop: [
  823. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  824. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  825. ],
  826. },
  827. };
  828. }
  829. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  830. const claude = getTarget('claude')!;
  831. const file = seedSettings('global', legacyHookSettings());
  832. claude.install('global', { autoAllow: true });
  833. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  834. // The only PostToolUse group held mark-dirty → the event is gone.
  835. expect(after.hooks?.PostToolUse).toBeUndefined();
  836. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  837. (g.hooks ?? []).map((h: any) => h.command),
  838. );
  839. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  840. // The unrelated GitKraken hook survives untouched.
  841. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  842. // Permissions still written as normal alongside the cleanup.
  843. expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
  844. });
  845. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  846. const file = seedSettings('global', {
  847. hooks: {
  848. Stop: [
  849. {
  850. hooks: [
  851. { type: 'command', command: 'codegraph sync-if-dirty' },
  852. { type: 'command', command: 'gk ai hook run --host claude-code' },
  853. ],
  854. },
  855. ],
  856. },
  857. });
  858. expect(cleanupLegacyHooks('global').action).toBe('removed');
  859. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  860. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  861. 'gk ai hook run --host claude-code',
  862. ]);
  863. });
  864. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  865. const original =
  866. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  867. const file = seedSettings('global', JSON.parse(original));
  868. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  869. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  870. });
  871. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  872. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  873. });
  874. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  875. const claude = getTarget('claude')!;
  876. const file = seedSettings('global', legacyHookSettings());
  877. claude.install('global', { autoAllow: true });
  878. const firstPass = fs.readFileSync(file, 'utf-8');
  879. claude.install('global', { autoAllow: true });
  880. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  881. });
  882. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  883. const claude = getTarget('claude')!;
  884. const file = seedSettings('local', {
  885. hooks: {
  886. PostToolUse: [
  887. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  888. ],
  889. Stop: [
  890. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  891. ],
  892. },
  893. });
  894. claude.uninstall('local');
  895. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  896. // Both events emptied → the whole `hooks` object is removed.
  897. expect(after.hooks).toBeUndefined();
  898. });
  899. });
  900. describe('Installer targets — registry', () => {
  901. it('getTarget returns the right target for each id', () => {
  902. expect(getTarget('claude')?.id).toBe('claude');
  903. expect(getTarget('cursor')?.id).toBe('cursor');
  904. expect(getTarget('codex')?.id).toBe('codex');
  905. expect(getTarget('opencode')?.id).toBe('opencode');
  906. expect(getTarget('hermes')?.id).toBe('hermes');
  907. expect(getTarget('gemini')?.id).toBe('gemini');
  908. expect(getTarget('antigravity')?.id).toBe('antigravity');
  909. expect(getTarget('kiro')?.id).toBe('kiro');
  910. expect(getTarget('not-a-real-target')).toBeUndefined();
  911. });
  912. it('resolveTargetFlag handles auto/all/none/csv', () => {
  913. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  914. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  915. const csv = resolveTargetFlag('claude,cursor', 'global');
  916. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  917. });
  918. it('resolveTargetFlag throws on unknown id', () => {
  919. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  920. });
  921. });
  922. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  923. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  924. const block = buildTomlTable('mcp_servers.codegraph', {
  925. command: 'codegraph',
  926. args: ['serve', '--mcp'],
  927. });
  928. expect(block).toContain('[mcp_servers.codegraph]');
  929. expect(block).toContain('command = "codegraph"');
  930. expect(block).toContain('args = ["serve", "--mcp"]');
  931. });
  932. it('upsert inserts into empty content', () => {
  933. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  934. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  935. expect(action).toBe('inserted');
  936. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  937. });
  938. it('upsert is idempotent — second call returns unchanged', () => {
  939. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  940. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  941. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  942. expect(second.action).toBe('unchanged');
  943. expect(second.content).toBe(first.content);
  944. });
  945. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  946. const existing = [
  947. '[other_table]',
  948. 'foo = "bar"',
  949. '',
  950. '[mcp_servers.codegraph]',
  951. 'command = "old-codegraph"',
  952. 'args = ["old"]',
  953. '',
  954. '[zzz]',
  955. 'baz = "qux"',
  956. '',
  957. ].join('\n');
  958. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  959. command: 'codegraph',
  960. args: ['serve', '--mcp'],
  961. });
  962. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  963. expect(action).toBe('replaced');
  964. expect(content).toContain('[other_table]');
  965. expect(content).toContain('foo = "bar"');
  966. expect(content).toContain('[zzz]');
  967. expect(content).toContain('baz = "qux"');
  968. expect(content).toContain('command = "codegraph"');
  969. expect(content).not.toContain('old-codegraph');
  970. });
  971. it('removeTomlTable strips the block and preserves siblings', () => {
  972. const existing = [
  973. '[other_table]',
  974. 'foo = "bar"',
  975. '',
  976. '[mcp_servers.codegraph]',
  977. 'command = "codegraph"',
  978. 'args = ["serve"]',
  979. ].join('\n');
  980. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  981. expect(action).toBe('removed');
  982. expect(content).toContain('[other_table]');
  983. expect(content).toContain('foo = "bar"');
  984. expect(content).not.toContain('mcp_servers.codegraph');
  985. });
  986. it('removeTomlTable on missing table returns not-found, no content change', () => {
  987. const existing = '[other]\nfoo = "bar"\n';
  988. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  989. expect(action).toBe('not-found');
  990. expect(content).toBe(existing);
  991. });
  992. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  993. const existing = [
  994. '[[foo]]',
  995. 'name = "a"',
  996. '',
  997. '[[foo]]',
  998. 'name = "b"',
  999. '',
  1000. ].join('\n');
  1001. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1002. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1003. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  1004. expect(content).toContain('[mcp_servers.codegraph]');
  1005. });
  1006. });
  1007. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  1008. let tmpHome: string;
  1009. let tmpCwd: string;
  1010. let origCwd: string;
  1011. let homeRestore: { restore: () => void };
  1012. beforeEach(() => {
  1013. tmpHome = mkTmpDir('un-home');
  1014. tmpCwd = mkTmpDir('un-cwd');
  1015. origCwd = process.cwd();
  1016. process.chdir(tmpCwd);
  1017. homeRestore = setHome(tmpHome);
  1018. });
  1019. afterEach(() => {
  1020. homeRestore.restore();
  1021. process.chdir(origCwd);
  1022. fs.rmSync(tmpHome, { recursive: true, force: true });
  1023. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1024. });
  1025. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  1026. for (const t of ALL_TARGETS) {
  1027. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1028. }
  1029. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1030. for (const t of ALL_TARGETS) {
  1031. const r = reports.find((x) => x.id === t.id)!;
  1032. expect(r.status).toBe('removed');
  1033. expect(r.removedPaths.length).toBeGreaterThan(0);
  1034. // The actual config is gone afterward.
  1035. expect(t.detect('global').alreadyConfigured).toBe(false);
  1036. }
  1037. });
  1038. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  1039. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1040. for (const r of reports) {
  1041. expect(r.status).toBe('not-configured');
  1042. expect(r.removedPaths).toEqual([]);
  1043. }
  1044. });
  1045. it('reports removed only for agents that were actually configured', () => {
  1046. // Install on Claude only; the rest stay untouched.
  1047. getTarget('claude')!.install('global', { autoAllow: true });
  1048. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1049. const claude = reports.find((r) => r.id === 'claude')!;
  1050. expect(claude.status).toBe('removed');
  1051. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  1052. for (const r of reports.filter((x) => x.id !== 'claude')) {
  1053. expect(r.status).toBe('not-configured');
  1054. }
  1055. });
  1056. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  1057. const reports = uninstallTargets(ALL_TARGETS, 'local');
  1058. for (const t of ALL_TARGETS) {
  1059. const r = reports.find((x) => x.id === t.id)!;
  1060. if (t.supportsLocation('local')) {
  1061. expect(r.status).toBe('not-configured');
  1062. } else {
  1063. expect(r.status).toBe('unsupported');
  1064. expect(r.removedPaths).toEqual([]);
  1065. expect(r.notes[0]).toMatch(/global-only/);
  1066. }
  1067. }
  1068. });
  1069. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1070. for (const t of ALL_TARGETS) {
  1071. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1072. }
  1073. const first = uninstallTargets(ALL_TARGETS, 'global');
  1074. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1075. const second = uninstallTargets(ALL_TARGETS, 'global');
  1076. for (const r of second) {
  1077. expect(r.status).toBe('not-configured');
  1078. expect(r.removedPaths).toEqual([]);
  1079. }
  1080. });
  1081. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1082. getTarget('claude')!.install('global', { autoAllow: true });
  1083. getTarget('cursor')!.install('global', { autoAllow: true });
  1084. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1085. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1086. expect(reports[0].status).toBe('removed');
  1087. // Cursor was not in the subset — still configured.
  1088. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1089. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1090. });
  1091. });
  1092. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1093. let tmpHome: string;
  1094. let tmpCwd: string;
  1095. let origCwd: string;
  1096. let homeRestore: { restore: () => void };
  1097. const cursor = getTarget('cursor')!;
  1098. beforeEach(() => {
  1099. tmpHome = mkTmpDir('cur-home');
  1100. tmpCwd = mkTmpDir('cur-cwd');
  1101. origCwd = process.cwd();
  1102. process.chdir(tmpCwd);
  1103. homeRestore = setHome(tmpHome);
  1104. });
  1105. afterEach(() => {
  1106. homeRestore.restore();
  1107. process.chdir(origCwd);
  1108. fs.rmSync(tmpHome, { recursive: true, force: true });
  1109. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1110. });
  1111. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1112. it('deletes the dedicated codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1113. cursor.install('local', { autoAllow: true });
  1114. expect(fs.existsSync(rulesFile())).toBe(true);
  1115. cursor.uninstall('local');
  1116. // The whole file — frontmatter included — is gone, not just the block.
  1117. expect(fs.existsSync(rulesFile())).toBe(false);
  1118. expect(cursor.detect('local').alreadyConfigured).toBe(false);
  1119. });
  1120. it('preserves user content added outside the codegraph markers (strips only our block)', () => {
  1121. cursor.install('local', { autoAllow: true });
  1122. const withUserContent =
  1123. fs.readFileSync(rulesFile(), 'utf-8') + '\n## My own rule\nkeep me\n';
  1124. fs.writeFileSync(rulesFile(), withUserContent);
  1125. cursor.uninstall('local');
  1126. expect(fs.existsSync(rulesFile())).toBe(true);
  1127. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1128. expect(after).toContain('keep me');
  1129. // Our tool-usage block is gone.
  1130. expect(after).not.toContain('codegraph_search');
  1131. expect(after).not.toContain('CODEGRAPH_START');
  1132. });
  1133. });
  1134. function listAllFiles(dir: string): string[] {
  1135. if (!fs.existsSync(dir)) return [];
  1136. const out: string[] = [];
  1137. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1138. const full = path.join(dir, entry.name);
  1139. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1140. else out.push(full);
  1141. }
  1142. return out;
  1143. }