installer-targets.test.ts 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  551. const opencode = getTarget('opencode')!;
  552. const dir = path.join(tmpHome, '.config', 'opencode');
  553. fs.mkdirSync(dir, { recursive: true });
  554. const file = path.join(dir, 'opencode.jsonc');
  555. fs.writeFileSync(file, [
  556. '{',
  557. ' // important comment',
  558. ' "$schema": "https://opencode.ai/config.json",',
  559. ' "mcp": {',
  560. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  561. ' }',
  562. '}',
  563. '',
  564. ].join('\n'));
  565. opencode.install('global', { autoAllow: true });
  566. const afterInstall = fs.readFileSync(file, 'utf-8');
  567. expect(afterInstall).toContain('"codegraph"');
  568. expect(afterInstall).toContain('"other"');
  569. opencode.uninstall('global');
  570. const afterUninstall = fs.readFileSync(file, 'utf-8');
  571. expect(afterUninstall).not.toContain('codegraph');
  572. expect(afterUninstall).toContain('// important comment');
  573. expect(afterUninstall).toContain('"other"');
  574. });
  575. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  576. const codex = getTarget('codex')!;
  577. codex.install('global', { autoAllow: false });
  578. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  579. const original = fs.readFileSync(tomlPath, 'utf-8');
  580. // User edits the block to add a custom key.
  581. const edited = original.replace(
  582. 'args = ["serve", "--mcp"]',
  583. 'args = ["serve", "--mcp"]\nenabled = true',
  584. );
  585. fs.writeFileSync(tomlPath, edited);
  586. // Re-install: our serializer doesn't know `enabled = true`, so
  587. // the block no longer matches the canonical form — we'll
  588. // overwrite it. This is the documented contract: we own the
  589. // codegraph block exclusively.
  590. const second = codex.install('global', { autoAllow: false });
  591. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  592. expect(tomlEntry.action).toBe('updated');
  593. const after = fs.readFileSync(tomlPath, 'utf-8');
  594. expect(after).not.toContain('enabled = true');
  595. });
  596. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  597. const claude = getTarget('claude')!;
  598. const result = claude.install('local', { autoAllow: false });
  599. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  600. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  601. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  602. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  603. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  604. expect(cfg.mcpServers.codegraph).toBeDefined();
  605. });
  606. it('claude: global install targets ~/.claude.json (user scope)', () => {
  607. const claude = getTarget('claude')!;
  608. claude.install('global', { autoAllow: false });
  609. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  610. expect(cfg.mcpServers.codegraph).toBeDefined();
  611. });
  612. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  613. const claude = getTarget('claude')!;
  614. const legacy = path.join(tmpCwd, '.claude.json');
  615. fs.writeFileSync(
  616. legacy,
  617. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  618. );
  619. claude.install('local', { autoAllow: false });
  620. // codegraph now lives in .mcp.json; the legacy file (which held only
  621. // codegraph) is gone.
  622. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  623. expect(mcp.mcpServers.codegraph).toBeDefined();
  624. expect(fs.existsSync(legacy)).toBe(false);
  625. });
  626. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  627. const claude = getTarget('claude')!;
  628. const legacy = path.join(tmpCwd, '.claude.json');
  629. fs.writeFileSync(
  630. legacy,
  631. JSON.stringify({
  632. mcpServers: {
  633. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  634. other: { command: 'x' },
  635. },
  636. somethingElse: true,
  637. }, null, 2),
  638. );
  639. claude.install('local', { autoAllow: false });
  640. // Only codegraph is stripped from the legacy file; siblings survive.
  641. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  642. expect(after.mcpServers.codegraph).toBeUndefined();
  643. expect(after.mcpServers.other).toBeDefined();
  644. expect(after.somethingElse).toBe(true);
  645. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  646. expect(mcp.mcpServers.codegraph).toBeDefined();
  647. });
  648. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  649. const claude = getTarget('claude')!;
  650. // A user left with both the working .mcp.json and a stale .claude.json.
  651. fs.writeFileSync(
  652. path.join(tmpCwd, '.mcp.json'),
  653. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  654. );
  655. fs.writeFileSync(
  656. path.join(tmpCwd, '.claude.json'),
  657. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  658. );
  659. claude.uninstall('local');
  660. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  661. expect(mcp.mcpServers).toBeUndefined();
  662. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  663. expect(legacy.mcpServers.codegraph).toBeUndefined();
  664. expect(legacy.mcpServers.other).toBeDefined();
  665. });
  666. // ---- Legacy auto-sync hook cleanup ----
  667. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  668. // hooks to settings.json. Both subcommands were removed from the CLI,
  669. // so the Stop hook fails every turn ("unknown command
  670. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  671. // uninstall — without touching the user's unrelated hooks.
  672. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  673. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  674. fs.mkdirSync(dir, { recursive: true });
  675. const file = path.join(dir, 'settings.json');
  676. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  677. return file;
  678. }
  679. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  680. // unrelated GitKraken Stop hook the user added (matches the report).
  681. function legacyHookSettings(): Record<string, any> {
  682. return {
  683. hooks: {
  684. PostToolUse: [
  685. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  686. ],
  687. Stop: [
  688. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  689. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  690. ],
  691. },
  692. };
  693. }
  694. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  695. const claude = getTarget('claude')!;
  696. const file = seedSettings('global', legacyHookSettings());
  697. claude.install('global', { autoAllow: true });
  698. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  699. // The only PostToolUse group held mark-dirty → the event is gone.
  700. expect(after.hooks?.PostToolUse).toBeUndefined();
  701. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  702. (g.hooks ?? []).map((h: any) => h.command),
  703. );
  704. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  705. // The unrelated GitKraken hook survives untouched.
  706. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  707. // Permissions still written as normal alongside the cleanup.
  708. expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
  709. });
  710. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  711. const file = seedSettings('global', {
  712. hooks: {
  713. Stop: [
  714. {
  715. hooks: [
  716. { type: 'command', command: 'codegraph sync-if-dirty' },
  717. { type: 'command', command: 'gk ai hook run --host claude-code' },
  718. ],
  719. },
  720. ],
  721. },
  722. });
  723. expect(cleanupLegacyHooks('global').action).toBe('removed');
  724. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  725. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  726. 'gk ai hook run --host claude-code',
  727. ]);
  728. });
  729. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  730. const original =
  731. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  732. const file = seedSettings('global', JSON.parse(original));
  733. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  734. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  735. });
  736. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  737. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  738. });
  739. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  740. const claude = getTarget('claude')!;
  741. const file = seedSettings('global', legacyHookSettings());
  742. claude.install('global', { autoAllow: true });
  743. const firstPass = fs.readFileSync(file, 'utf-8');
  744. claude.install('global', { autoAllow: true });
  745. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  746. });
  747. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  748. const claude = getTarget('claude')!;
  749. const file = seedSettings('local', {
  750. hooks: {
  751. PostToolUse: [
  752. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  753. ],
  754. Stop: [
  755. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  756. ],
  757. },
  758. });
  759. claude.uninstall('local');
  760. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  761. // Both events emptied → the whole `hooks` object is removed.
  762. expect(after.hooks).toBeUndefined();
  763. });
  764. });
  765. describe('Installer targets — registry', () => {
  766. it('getTarget returns the right target for each id', () => {
  767. expect(getTarget('claude')?.id).toBe('claude');
  768. expect(getTarget('cursor')?.id).toBe('cursor');
  769. expect(getTarget('codex')?.id).toBe('codex');
  770. expect(getTarget('opencode')?.id).toBe('opencode');
  771. expect(getTarget('hermes')?.id).toBe('hermes');
  772. expect(getTarget('gemini')?.id).toBe('gemini');
  773. expect(getTarget('antigravity')?.id).toBe('antigravity');
  774. expect(getTarget('not-a-real-target')).toBeUndefined();
  775. });
  776. it('resolveTargetFlag handles auto/all/none/csv', () => {
  777. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  778. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  779. const csv = resolveTargetFlag('claude,cursor', 'global');
  780. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  781. });
  782. it('resolveTargetFlag throws on unknown id', () => {
  783. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  784. });
  785. });
  786. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  787. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  788. const block = buildTomlTable('mcp_servers.codegraph', {
  789. command: 'codegraph',
  790. args: ['serve', '--mcp'],
  791. });
  792. expect(block).toContain('[mcp_servers.codegraph]');
  793. expect(block).toContain('command = "codegraph"');
  794. expect(block).toContain('args = ["serve", "--mcp"]');
  795. });
  796. it('upsert inserts into empty content', () => {
  797. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  798. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  799. expect(action).toBe('inserted');
  800. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  801. });
  802. it('upsert is idempotent — second call returns unchanged', () => {
  803. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  804. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  805. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  806. expect(second.action).toBe('unchanged');
  807. expect(second.content).toBe(first.content);
  808. });
  809. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  810. const existing = [
  811. '[other_table]',
  812. 'foo = "bar"',
  813. '',
  814. '[mcp_servers.codegraph]',
  815. 'command = "old-codegraph"',
  816. 'args = ["old"]',
  817. '',
  818. '[zzz]',
  819. 'baz = "qux"',
  820. '',
  821. ].join('\n');
  822. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  823. command: 'codegraph',
  824. args: ['serve', '--mcp'],
  825. });
  826. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  827. expect(action).toBe('replaced');
  828. expect(content).toContain('[other_table]');
  829. expect(content).toContain('foo = "bar"');
  830. expect(content).toContain('[zzz]');
  831. expect(content).toContain('baz = "qux"');
  832. expect(content).toContain('command = "codegraph"');
  833. expect(content).not.toContain('old-codegraph');
  834. });
  835. it('removeTomlTable strips the block and preserves siblings', () => {
  836. const existing = [
  837. '[other_table]',
  838. 'foo = "bar"',
  839. '',
  840. '[mcp_servers.codegraph]',
  841. 'command = "codegraph"',
  842. 'args = ["serve"]',
  843. ].join('\n');
  844. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  845. expect(action).toBe('removed');
  846. expect(content).toContain('[other_table]');
  847. expect(content).toContain('foo = "bar"');
  848. expect(content).not.toContain('mcp_servers.codegraph');
  849. });
  850. it('removeTomlTable on missing table returns not-found, no content change', () => {
  851. const existing = '[other]\nfoo = "bar"\n';
  852. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  853. expect(action).toBe('not-found');
  854. expect(content).toBe(existing);
  855. });
  856. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  857. const existing = [
  858. '[[foo]]',
  859. 'name = "a"',
  860. '',
  861. '[[foo]]',
  862. 'name = "b"',
  863. '',
  864. ].join('\n');
  865. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  866. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  867. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  868. expect(content).toContain('[mcp_servers.codegraph]');
  869. });
  870. });
  871. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  872. let tmpHome: string;
  873. let tmpCwd: string;
  874. let origCwd: string;
  875. let homeRestore: { restore: () => void };
  876. beforeEach(() => {
  877. tmpHome = mkTmpDir('un-home');
  878. tmpCwd = mkTmpDir('un-cwd');
  879. origCwd = process.cwd();
  880. process.chdir(tmpCwd);
  881. homeRestore = setHome(tmpHome);
  882. });
  883. afterEach(() => {
  884. homeRestore.restore();
  885. process.chdir(origCwd);
  886. fs.rmSync(tmpHome, { recursive: true, force: true });
  887. fs.rmSync(tmpCwd, { recursive: true, force: true });
  888. });
  889. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  890. for (const t of ALL_TARGETS) {
  891. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  892. }
  893. const reports = uninstallTargets(ALL_TARGETS, 'global');
  894. for (const t of ALL_TARGETS) {
  895. const r = reports.find((x) => x.id === t.id)!;
  896. expect(r.status).toBe('removed');
  897. expect(r.removedPaths.length).toBeGreaterThan(0);
  898. // The actual config is gone afterward.
  899. expect(t.detect('global').alreadyConfigured).toBe(false);
  900. }
  901. });
  902. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  903. const reports = uninstallTargets(ALL_TARGETS, 'global');
  904. for (const r of reports) {
  905. expect(r.status).toBe('not-configured');
  906. expect(r.removedPaths).toEqual([]);
  907. }
  908. });
  909. it('reports removed only for agents that were actually configured', () => {
  910. // Install on Claude only; the rest stay untouched.
  911. getTarget('claude')!.install('global', { autoAllow: true });
  912. const reports = uninstallTargets(ALL_TARGETS, 'global');
  913. const claude = reports.find((r) => r.id === 'claude')!;
  914. expect(claude.status).toBe('removed');
  915. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  916. for (const r of reports.filter((x) => x.id !== 'claude')) {
  917. expect(r.status).toBe('not-configured');
  918. }
  919. });
  920. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  921. const reports = uninstallTargets(ALL_TARGETS, 'local');
  922. for (const t of ALL_TARGETS) {
  923. const r = reports.find((x) => x.id === t.id)!;
  924. if (t.supportsLocation('local')) {
  925. expect(r.status).toBe('not-configured');
  926. } else {
  927. expect(r.status).toBe('unsupported');
  928. expect(r.removedPaths).toEqual([]);
  929. expect(r.notes[0]).toMatch(/global-only/);
  930. }
  931. }
  932. });
  933. it('is idempotent — a second sweep finds nothing left to remove', () => {
  934. for (const t of ALL_TARGETS) {
  935. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  936. }
  937. const first = uninstallTargets(ALL_TARGETS, 'global');
  938. expect(first.some((r) => r.status === 'removed')).toBe(true);
  939. const second = uninstallTargets(ALL_TARGETS, 'global');
  940. for (const r of second) {
  941. expect(r.status).toBe('not-configured');
  942. expect(r.removedPaths).toEqual([]);
  943. }
  944. });
  945. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  946. getTarget('claude')!.install('global', { autoAllow: true });
  947. getTarget('cursor')!.install('global', { autoAllow: true });
  948. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  949. expect(reports.map((r) => r.id)).toEqual(['claude']);
  950. expect(reports[0].status).toBe('removed');
  951. // Cursor was not in the subset — still configured.
  952. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  953. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  954. });
  955. });
  956. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  957. let tmpHome: string;
  958. let tmpCwd: string;
  959. let origCwd: string;
  960. let homeRestore: { restore: () => void };
  961. const cursor = getTarget('cursor')!;
  962. beforeEach(() => {
  963. tmpHome = mkTmpDir('cur-home');
  964. tmpCwd = mkTmpDir('cur-cwd');
  965. origCwd = process.cwd();
  966. process.chdir(tmpCwd);
  967. homeRestore = setHome(tmpHome);
  968. });
  969. afterEach(() => {
  970. homeRestore.restore();
  971. process.chdir(origCwd);
  972. fs.rmSync(tmpHome, { recursive: true, force: true });
  973. fs.rmSync(tmpCwd, { recursive: true, force: true });
  974. });
  975. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  976. it('deletes the dedicated codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  977. cursor.install('local', { autoAllow: true });
  978. expect(fs.existsSync(rulesFile())).toBe(true);
  979. cursor.uninstall('local');
  980. // The whole file — frontmatter included — is gone, not just the block.
  981. expect(fs.existsSync(rulesFile())).toBe(false);
  982. expect(cursor.detect('local').alreadyConfigured).toBe(false);
  983. });
  984. it('preserves user content added outside the codegraph markers (strips only our block)', () => {
  985. cursor.install('local', { autoAllow: true });
  986. const withUserContent =
  987. fs.readFileSync(rulesFile(), 'utf-8') + '\n## My own rule\nkeep me\n';
  988. fs.writeFileSync(rulesFile(), withUserContent);
  989. cursor.uninstall('local');
  990. expect(fs.existsSync(rulesFile())).toBe(true);
  991. const after = fs.readFileSync(rulesFile(), 'utf-8');
  992. expect(after).toContain('keep me');
  993. // Our tool-usage block is gone.
  994. expect(after).not.toContain('codegraph_search');
  995. expect(after).not.toContain('CODEGRAPH_START');
  996. });
  997. });
  998. function listAllFiles(dir: string): string[] {
  999. if (!fs.existsSync(dir)) return [];
  1000. const out: string[] = [];
  1001. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1002. const full = path.join(dir, entry.name);
  1003. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1004. else out.push(full);
  1005. }
  1006. return out;
  1007. }