installer-targets.test.ts 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  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 { parse as parseJsonc } from 'jsonc-parser';
  21. import { ALL_TARGETS, getTarget, resolveTargetFlag } from '../src/installer/targets/registry';
  22. import { uninstallTargets, refreshTargets } from '../src/installer';
  23. import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  24. import { cleanupLegacyHooks, writePromptHookEntry, removePromptHookEntry } from '../src/installer/targets/claude';
  25. function mkTmpDir(label: string): string {
  26. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
  27. }
  28. // `os.homedir` is non-configurable on Node, so we redirect it via the
  29. // `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
  30. // `os.homedir()` reads first. Same trick the rest of the suite uses
  31. // when it needs a mock home.
  32. function setHome(dir: string): { restore: () => void } {
  33. const prev = {
  34. HOME: process.env.HOME,
  35. USERPROFILE: process.env.USERPROFILE,
  36. APPDATA: process.env.APPDATA,
  37. XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
  38. HERMES_HOME: process.env.HERMES_HOME,
  39. COPILOT_HOME: process.env.COPILOT_HOME,
  40. };
  41. process.env.HOME = dir;
  42. process.env.USERPROFILE = dir;
  43. process.env.APPDATA = path.join(dir, '.config');
  44. process.env.XDG_CONFIG_HOME = path.join(dir, '.config');
  45. delete process.env.HERMES_HOME;
  46. delete process.env.COPILOT_HOME;
  47. return {
  48. restore() {
  49. if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
  50. if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
  51. if (prev.APPDATA === undefined) delete process.env.APPDATA; else process.env.APPDATA = prev.APPDATA;
  52. if (prev.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = prev.XDG_CONFIG_HOME;
  53. if (prev.HERMES_HOME === undefined) delete process.env.HERMES_HOME; else process.env.HERMES_HOME = prev.HERMES_HOME;
  54. if (prev.COPILOT_HOME === undefined) delete process.env.COPILOT_HOME; else process.env.COPILOT_HOME = prev.COPILOT_HOME;
  55. },
  56. };
  57. }
  58. // A marker-delimited CodeGraph block exactly as a previous installer
  59. // wrote it. Issue #529: the installer no longer writes an instructions
  60. // file, but install (self-heal on upgrade) and uninstall both still
  61. // strip a block a prior install left, so we plant this to exercise it.
  62. const LEGACY_BLOCK = [
  63. '<!-- CODEGRAPH_START -->',
  64. '## CodeGraph',
  65. '',
  66. 'Prefer `codegraph_search` / `codegraph_callers` over grep.',
  67. '<!-- CODEGRAPH_END -->',
  68. ].join('\n');
  69. describe('Installer targets — contract', () => {
  70. let tmpHome: string;
  71. let tmpCwd: string;
  72. let origCwd: string;
  73. let homeRestore: { restore: () => void };
  74. beforeEach(() => {
  75. tmpHome = mkTmpDir('home');
  76. tmpCwd = mkTmpDir('cwd');
  77. origCwd = process.cwd();
  78. process.chdir(tmpCwd);
  79. homeRestore = setHome(tmpHome);
  80. });
  81. afterEach(() => {
  82. homeRestore.restore();
  83. process.chdir(origCwd);
  84. fs.rmSync(tmpHome, { recursive: true, force: true });
  85. fs.rmSync(tmpCwd, { recursive: true, force: true });
  86. });
  87. for (const target of ALL_TARGETS) {
  88. describe(target.id, () => {
  89. const supportedLocations = (['global', 'local'] as const).filter((l) =>
  90. target.supportsLocation(l),
  91. );
  92. for (const location of supportedLocations) {
  93. describe(`location=${location}`, () => {
  94. it('install writes files; detect.alreadyConfigured becomes true', () => {
  95. expect(target.detect(location).alreadyConfigured).toBe(false);
  96. const result = target.install(location, { autoAllow: true });
  97. expect(result.files.length).toBeGreaterThan(0);
  98. for (const file of result.files) {
  99. if (file.action !== 'unchanged') {
  100. expect(fs.existsSync(file.path)).toBe(true);
  101. }
  102. }
  103. expect(target.detect(location).alreadyConfigured).toBe(true);
  104. });
  105. it('re-running install is idempotent (no actions other than unchanged)', () => {
  106. target.install(location, { autoAllow: true });
  107. const second = target.install(location, { autoAllow: true });
  108. for (const file of second.files) {
  109. expect(file.action).toBe('unchanged');
  110. }
  111. });
  112. it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
  113. // Plant a sibling entry in the same JSON config, install,
  114. // and verify the sibling survives. Skip for Codex (TOML)
  115. // and any target with no JSON config — they get covered
  116. // by their own dedicated tests below.
  117. const paths = target.describePaths(location);
  118. // Match .json or .jsonc — opencode prefers .jsonc.
  119. const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
  120. if (!jsonPath) return;
  121. // Seed pre-existing config.
  122. fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
  123. const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
  124. // opencode uses `mcp` not `mcpServers`. Match its shape too.
  125. if (target.id === 'opencode') {
  126. delete seed.mcpServers;
  127. seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
  128. }
  129. // VS Code's mcp.json uses `servers`; the JetBrains Copilot
  130. // plugin's mcp.json is schema-compatible with it.
  131. if (target.id === 'copilot-vscode' || target.id === 'copilot-jetbrains') {
  132. delete seed.mcpServers;
  133. seed.servers = { other: { command: 'x' } };
  134. }
  135. fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
  136. target.install(location, { autoAllow: true });
  137. const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
  138. if (target.id === 'opencode') {
  139. expect(after.mcp.other).toBeDefined();
  140. expect(after.mcp.codegraph).toBeDefined();
  141. } else if (target.id === 'copilot-vscode' || target.id === 'copilot-jetbrains') {
  142. expect(after.servers.other).toBeDefined();
  143. expect(after.servers.codegraph).toBeDefined();
  144. } else {
  145. expect(after.mcpServers.other).toBeDefined();
  146. expect(after.mcpServers.codegraph).toBeDefined();
  147. }
  148. });
  149. it('uninstall reverses install (alreadyConfigured returns to false)', () => {
  150. target.install(location, { autoAllow: true });
  151. expect(target.detect(location).alreadyConfigured).toBe(true);
  152. target.uninstall(location);
  153. expect(target.detect(location).alreadyConfigured).toBe(false);
  154. });
  155. it('printConfig returns non-empty output without writing anything', () => {
  156. const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  157. const out = target.printConfig(location);
  158. expect(out.length).toBeGreaterThan(0);
  159. const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  160. expect(after.sort()).toEqual(before.sort());
  161. });
  162. });
  163. }
  164. });
  165. }
  166. });
  167. describe('Installer targets — partial-state idempotency', () => {
  168. let tmpHome: string;
  169. let tmpCwd: string;
  170. let origCwd: string;
  171. let homeRestore: { restore: () => void };
  172. beforeEach(() => {
  173. tmpHome = mkTmpDir('home');
  174. tmpCwd = mkTmpDir('cwd');
  175. origCwd = process.cwd();
  176. process.chdir(tmpCwd);
  177. homeRestore = setHome(tmpHome);
  178. });
  179. afterEach(() => {
  180. homeRestore.restore();
  181. process.chdir(origCwd);
  182. fs.rmSync(tmpHome, { recursive: true, force: true });
  183. fs.rmSync(tmpCwd, { recursive: true, force: true });
  184. });
  185. it('codex: install writes config.toml AND the AGENTS.md codegraph block (#704)', () => {
  186. const codex = getTarget('codex')!;
  187. const first = codex.install('global', { autoAllow: false });
  188. const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
  189. expect(first.files.some((f) => f.path.endsWith('config.toml'))).toBe(true);
  190. // The short instructions block IS written (subagents / non-MCP
  191. // harnesses read AGENTS.md but never the MCP initialize instructions).
  192. expect(fs.existsSync(agentsMd)).toBe(true);
  193. const body = fs.readFileSync(agentsMd, 'utf-8');
  194. expect(body).toContain('## CodeGraph');
  195. expect(body).toContain('codegraph explore');
  196. // Re-install is fully unchanged (byte-equal block → idempotent).
  197. const second = codex.install('global', { autoAllow: false });
  198. for (const f of second.files) expect(f.action).toBe('unchanged');
  199. });
  200. it('codex: install replaces a legacy AGENTS.md codegraph block with the current one, keeping user content', () => {
  201. const codex = getTarget('codex')!;
  202. const dir = path.join(tmpHome, '.codex');
  203. fs.mkdirSync(dir, { recursive: true });
  204. const agentsMd = path.join(dir, 'AGENTS.md');
  205. fs.writeFileSync(agentsMd, `# My codex notes\n\nBe terse.\n\n${LEGACY_BLOCK}\n`);
  206. const result = codex.install('global', { autoAllow: false });
  207. const body = fs.readFileSync(agentsMd, 'utf-8');
  208. expect(body).toContain('# My codex notes');
  209. expect(body).toContain('Be terse.');
  210. // Self-heal: the stale pre-#529 body is gone, the current block is in.
  211. expect(body).not.toContain('Prefer `codegraph_search`');
  212. expect(body).toContain('codegraph explore');
  213. const mdEntry = result.files.find((f) => f.path.endsWith('AGENTS.md'));
  214. expect(mdEntry?.action).toBe('updated');
  215. });
  216. it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
  217. const opencode = getTarget('opencode')!;
  218. const dir = path.join(tmpHome, '.config', 'opencode');
  219. fs.mkdirSync(dir, { recursive: true });
  220. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  221. fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  222. const result = opencode.install('global', { autoAllow: true });
  223. const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
  224. expect(written).toBeDefined();
  225. expect(written.action).not.toBe('not-found');
  226. // The .json file is left alone.
  227. const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
  228. expect(jsonText).not.toContain('codegraph');
  229. });
  230. it('opencode: uses .json when only .json exists (no .jsonc)', () => {
  231. const opencode = getTarget('opencode')!;
  232. const dir = path.join(tmpHome, '.config', 'opencode');
  233. fs.mkdirSync(dir, { recursive: true });
  234. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  235. const result = opencode.install('global', { autoAllow: true });
  236. expect(result.files[0].path).toMatch(/opencode\.json$/);
  237. expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
  238. });
  239. it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
  240. const opencode = getTarget('opencode')!;
  241. const result = opencode.install('global', { autoAllow: true });
  242. expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
  243. expect(result.files[0].action).toBe('created');
  244. });
  245. it('opencode: preserves line and block comments through install + idempotent re-run', () => {
  246. const opencode = getTarget('opencode')!;
  247. const dir = path.join(tmpHome, '.config', 'opencode');
  248. fs.mkdirSync(dir, { recursive: true });
  249. const file = path.join(dir, 'opencode.jsonc');
  250. const original = [
  251. '{',
  252. ' // top-level note about my opencode setup',
  253. ' "$schema": "https://opencode.ai/config.json",',
  254. ' /* multi-line block comment',
  255. ' describing the providers section */',
  256. ' "providers": {',
  257. ' "anthropic": { "model": "claude-opus-4-7" } // pinned',
  258. ' }',
  259. '}',
  260. '',
  261. ].join('\n');
  262. fs.writeFileSync(file, original);
  263. opencode.install('global', { autoAllow: true });
  264. const afterInstall = fs.readFileSync(file, 'utf-8');
  265. expect(afterInstall).toContain('// top-level note about my opencode setup');
  266. expect(afterInstall).toContain('/* multi-line block comment');
  267. expect(afterInstall).toContain('// pinned');
  268. expect(afterInstall).toContain('"codegraph"');
  269. expect(afterInstall).toContain('"providers"');
  270. // Idempotent re-run reports unchanged, file is byte-identical.
  271. const second = opencode.install('global', { autoAllow: true });
  272. expect(second.files[0].action).toBe('unchanged');
  273. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  274. });
  275. it('opencode: install writes the AGENTS.md codegraph block (#704)', () => {
  276. const opencode = getTarget('opencode')!;
  277. const result = opencode.install('global', { autoAllow: true });
  278. const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
  279. expect(fs.existsSync(agentsMd)).toBe(true);
  280. expect(fs.readFileSync(agentsMd, 'utf-8')).toContain('codegraph explore');
  281. expect(result.files.find((f) => f.path.endsWith('AGENTS.md'))?.action).toBe('created');
  282. });
  283. it('opencode: install replaces a legacy AGENTS.md codegraph block, preserving user content', () => {
  284. const opencode = getTarget('opencode')!;
  285. const dir = path.join(tmpHome, '.config', 'opencode');
  286. fs.mkdirSync(dir, { recursive: true });
  287. const agentsMd = path.join(dir, 'AGENTS.md');
  288. fs.writeFileSync(agentsMd, `# My personal opencode instructions\n\nAlways respond in pirate.\n\n${LEGACY_BLOCK}\n`);
  289. const result = opencode.install('global', { autoAllow: true });
  290. const body = fs.readFileSync(agentsMd, 'utf-8');
  291. expect(body).toContain('# My personal opencode instructions');
  292. expect(body).toContain('Always respond in pirate.');
  293. expect(body).not.toContain('Prefer `codegraph_search`');
  294. expect(body).toContain('codegraph explore');
  295. expect(result.files.find((f) => f.path.endsWith('AGENTS.md'))?.action).toBe('updated');
  296. });
  297. it('opencode: uninstall strips a leftover codegraph block from AGENTS.md, keeping user content', () => {
  298. const opencode = getTarget('opencode')!;
  299. const dir = path.join(tmpHome, '.config', 'opencode');
  300. fs.mkdirSync(dir, { recursive: true });
  301. const agentsMd = path.join(dir, 'AGENTS.md');
  302. fs.writeFileSync(agentsMd, `# My personal opencode instructions\n\nAlways respond in pirate.\n\n${LEGACY_BLOCK}\n`);
  303. opencode.uninstall('global');
  304. const body = fs.readFileSync(agentsMd, 'utf-8');
  305. expect(body).toContain('# My personal opencode instructions');
  306. expect(body).toContain('Always respond in pirate.');
  307. expect(body).not.toContain('CODEGRAPH_START');
  308. });
  309. it('opencode: local install writes ./opencode.jsonc and the ./AGENTS.md block (#704)', () => {
  310. const opencode = getTarget('opencode')!;
  311. const result = opencode.install('local', { autoAllow: true });
  312. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  313. // macOS realpath shenanigans (/var vs /private/var) — suffix match.
  314. expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
  315. expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
  316. expect(fs.existsSync(path.join(process.cwd(), 'AGENTS.md'))).toBe(true);
  317. });
  318. it('gemini: install writes settings.json (mcpServers.codegraph) and the GEMINI.md block (#704)', () => {
  319. const gemini = getTarget('gemini')!;
  320. const result = gemini.install('global', { autoAllow: true });
  321. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  322. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  323. expect(result.files.some((f) => f.path === settings)).toBe(true);
  324. expect(result.files.some((f) => f.path === geminiMd)).toBe(true);
  325. expect(fs.existsSync(geminiMd)).toBe(true);
  326. expect(fs.readFileSync(geminiMd, 'utf-8')).toContain('codegraph explore');
  327. const cfg = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  328. expect(cfg.mcpServers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  329. });
  330. it('gemini: install preserves pre-existing settings (security.auth survives)', () => {
  331. const gemini = getTarget('gemini')!;
  332. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  333. fs.mkdirSync(path.dirname(settings), { recursive: true });
  334. fs.writeFileSync(settings, JSON.stringify({
  335. security: { auth: { selectedType: 'oauth-personal' } },
  336. }, null, 2) + '\n');
  337. gemini.install('global', { autoAllow: true });
  338. const after = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  339. expect(after.security?.auth?.selectedType).toBe('oauth-personal');
  340. expect(after.mcpServers?.codegraph).toBeDefined();
  341. });
  342. it('gemini: uninstall strips codegraph but leaves pre-existing settings (security.auth) intact', () => {
  343. const gemini = getTarget('gemini')!;
  344. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  345. fs.mkdirSync(path.dirname(settings), { recursive: true });
  346. fs.writeFileSync(settings, JSON.stringify({
  347. security: { auth: { selectedType: 'oauth-personal' } },
  348. }, null, 2) + '\n');
  349. gemini.install('global', { autoAllow: true });
  350. gemini.uninstall('global');
  351. const after = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  352. expect(after.security?.auth?.selectedType).toBe('oauth-personal');
  353. expect(after.mcpServers).toBeUndefined();
  354. });
  355. it('gemini: local install writes ./.gemini/settings.json and the project-root ./GEMINI.md block (#704)', () => {
  356. const gemini = getTarget('gemini')!;
  357. const result = gemini.install('local', { autoAllow: true });
  358. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  359. expect(paths.some((p) => p.endsWith('/.gemini/settings.json'))).toBe(true);
  360. expect(paths.some((p) => p.endsWith('/GEMINI.md'))).toBe(true);
  361. expect(fs.existsSync(path.join(process.cwd(), 'GEMINI.md'))).toBe(true);
  362. });
  363. it('gemini: uninstall strips a leftover GEMINI.md codegraph block, keeping user content', () => {
  364. const gemini = getTarget('gemini')!;
  365. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  366. fs.mkdirSync(path.dirname(geminiMd), { recursive: true });
  367. fs.writeFileSync(geminiMd, `# My personal Gemini context\n\nAlways respond concisely.\n\n${LEGACY_BLOCK}\n`);
  368. gemini.uninstall('global');
  369. const body = fs.readFileSync(geminiMd, 'utf-8');
  370. expect(body).toContain('# My personal Gemini context');
  371. expect(body).toContain('Always respond concisely.');
  372. expect(body).not.toContain('CODEGRAPH_START');
  373. });
  374. it('kiro: install writes settings/mcp.json (mcpServers.codegraph) and no steering doc (#529)', () => {
  375. const kiro = getTarget('kiro')!;
  376. const result = kiro.install('global', { autoAllow: true });
  377. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  378. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  379. expect(result.files.some((f) => f.path === mcp)).toBe(true);
  380. expect(result.files.some((f) => f.path === steering)).toBe(false);
  381. expect(fs.existsSync(steering)).toBe(false);
  382. const cfg = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  383. expect(cfg.mcpServers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  384. });
  385. it('kiro: install deletes a leftover steering codegraph.md (self-heal) (#529)', () => {
  386. const kiro = getTarget('kiro')!;
  387. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  388. fs.mkdirSync(path.dirname(steering), { recursive: true });
  389. fs.writeFileSync(steering, `${LEGACY_BLOCK}\n`);
  390. const result = kiro.install('global', { autoAllow: true });
  391. expect(fs.existsSync(steering)).toBe(false);
  392. expect(result.files.find((f) => f.path === steering)?.action).toBe('removed');
  393. });
  394. it('kiro: install preserves a pre-existing sibling MCP server in mcp.json', () => {
  395. const kiro = getTarget('kiro')!;
  396. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  397. fs.mkdirSync(path.dirname(mcp), { recursive: true });
  398. fs.writeFileSync(mcp, JSON.stringify({
  399. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  400. }, null, 2) + '\n');
  401. kiro.install('global', { autoAllow: true });
  402. const after = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  403. expect(after.mcpServers.other).toBeDefined();
  404. expect(after.mcpServers.codegraph).toBeDefined();
  405. });
  406. it('kiro: uninstall strips codegraph but leaves sibling MCP servers intact', () => {
  407. const kiro = getTarget('kiro')!;
  408. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  409. fs.mkdirSync(path.dirname(mcp), { recursive: true });
  410. fs.writeFileSync(mcp, JSON.stringify({
  411. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  412. }, null, 2) + '\n');
  413. kiro.install('global', { autoAllow: true });
  414. kiro.uninstall('global');
  415. const after = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  416. expect(after.mcpServers.other).toBeDefined();
  417. expect(after.mcpServers.codegraph).toBeUndefined();
  418. });
  419. it('kiro: uninstall removes a leftover steering codegraph.md file outright', () => {
  420. const kiro = getTarget('kiro')!;
  421. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  422. fs.mkdirSync(path.dirname(steering), { recursive: true });
  423. fs.writeFileSync(steering, `${LEGACY_BLOCK}\n`);
  424. kiro.uninstall('global');
  425. expect(fs.existsSync(steering)).toBe(false);
  426. });
  427. it('kiro: uninstall removes our steering doc but leaves a sibling (product.md) untouched', () => {
  428. const kiro = getTarget('kiro')!;
  429. const sibling = path.join(tmpHome, '.kiro', 'steering', 'product.md');
  430. const ours = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  431. fs.mkdirSync(path.dirname(sibling), { recursive: true });
  432. fs.writeFileSync(sibling, '# Product\n\nMy team practices.\n');
  433. fs.writeFileSync(ours, `${LEGACY_BLOCK}\n`);
  434. kiro.uninstall('global');
  435. expect(fs.existsSync(ours)).toBe(false);
  436. expect(fs.existsSync(sibling)).toBe(true);
  437. expect(fs.readFileSync(sibling, 'utf-8')).toContain('My team practices.');
  438. });
  439. it('kiro: local install writes ./.kiro/settings/mcp.json and no steering doc (#529)', () => {
  440. const kiro = getTarget('kiro')!;
  441. const result = kiro.install('local', { autoAllow: true });
  442. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  443. expect(paths.some((p) => p.endsWith('/.kiro/settings/mcp.json'))).toBe(true);
  444. expect(paths.some((p) => p.endsWith('/.kiro/steering/codegraph.md'))).toBe(false);
  445. });
  446. it('antigravity: install writes to LEGACY ~/.gemini/antigravity/mcp_config.json when no migration marker', () => {
  447. const antigravity = getTarget('antigravity')!;
  448. antigravity.install('global', { autoAllow: true });
  449. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  450. expect(fs.existsSync(legacyFile)).toBe(true);
  451. const cfg = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  452. expect(cfg.mcpServers.codegraph).toBeDefined();
  453. // Crucially: does NOT touch the Gemini CLI's settings.json.
  454. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'settings.json'))).toBe(false);
  455. });
  456. it('antigravity: install writes to UNIFIED ~/.gemini/config/mcp_config.json when .migrated marker present', () => {
  457. const antigravity = getTarget('antigravity')!;
  458. // Plant the migration marker — same signal Antigravity itself drops
  459. // when it migrates a user's config.
  460. const unifiedDir = path.join(tmpHome, '.gemini', 'config');
  461. fs.mkdirSync(unifiedDir, { recursive: true });
  462. fs.writeFileSync(path.join(unifiedDir, '.migrated'), '');
  463. antigravity.install('global', { autoAllow: true });
  464. const unifiedFile = path.join(unifiedDir, 'mcp_config.json');
  465. expect(fs.existsSync(unifiedFile)).toBe(true);
  466. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  467. expect(cfg.mcpServers.codegraph).toBeDefined();
  468. // Legacy path is NOT touched when the marker tells us migration happened.
  469. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'))).toBe(false);
  470. });
  471. it('antigravity: install writes to UNIFIED path when ~/.gemini/config/mcp_config.json already exists (even without marker)', () => {
  472. const antigravity = getTarget('antigravity')!;
  473. // Antigravity creates this file on first launch post-migration — its
  474. // presence is the second signal we accept, in case the .migrated
  475. // marker semantics change across Antigravity versions.
  476. const unifiedFile = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  477. fs.mkdirSync(path.dirname(unifiedFile), { recursive: true });
  478. fs.writeFileSync(unifiedFile, JSON.stringify({ mcpServers: {} }, null, 2) + '\n');
  479. antigravity.install('global', { autoAllow: true });
  480. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  481. expect(cfg.mcpServers.codegraph).toBeDefined();
  482. });
  483. it('antigravity: entry has NO `type` field (Antigravity rejects entries with it)', () => {
  484. const antigravity = getTarget('antigravity')!;
  485. // Marker → unified path; doesn't matter which path, just inspect the entry shape.
  486. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  487. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  488. antigravity.install('global', { autoAllow: true });
  489. const cfg = JSON.parse(fs.readFileSync(
  490. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  491. ));
  492. expect(cfg.mcpServers.codegraph.type).toBeUndefined();
  493. expect(cfg.mcpServers.codegraph.command).toBeDefined();
  494. expect(cfg.mcpServers.codegraph.args).toEqual(['serve', '--mcp']);
  495. });
  496. it('antigravity: install migrates a legacy codegraph entry to the unified path when marker appears', () => {
  497. const antigravity = getTarget('antigravity')!;
  498. // Simulate: user installed on the legacy path, then Antigravity
  499. // migrated their config (dropped the `.migrated` marker + created
  500. // the unified file). Re-running codegraph install should land
  501. // codegraph in the new file AND strip the stale legacy entry.
  502. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  503. fs.mkdirSync(path.dirname(legacyFile), { recursive: true });
  504. fs.writeFileSync(legacyFile, JSON.stringify({
  505. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  506. }, null, 2) + '\n');
  507. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  508. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  509. antigravity.install('global', { autoAllow: true });
  510. const unified = JSON.parse(fs.readFileSync(
  511. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  512. ));
  513. expect(unified.mcpServers.codegraph).toBeDefined();
  514. // Legacy file's codegraph entry got stripped.
  515. const legacy = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  516. expect(legacy.mcpServers).toBeUndefined();
  517. });
  518. it('antigravity: install preserves a sibling MCP server in mcp_config.json (legacy path)', () => {
  519. const antigravity = getTarget('antigravity')!;
  520. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  521. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  522. fs.writeFileSync(mcpFile, JSON.stringify({
  523. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  524. }, null, 2) + '\n');
  525. antigravity.install('global', { autoAllow: true });
  526. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  527. expect(after.mcpServers.other).toBeDefined();
  528. expect(after.mcpServers.codegraph).toBeDefined();
  529. });
  530. it('antigravity: install preserves Antigravity-managed fields on sibling servers (e.g. disabled flag)', () => {
  531. const antigravity = getTarget('antigravity')!;
  532. // Antigravity adds `"disabled": true` to entries the user disables via
  533. // the IDE. Install must not clobber that on sibling entries.
  534. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  535. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  536. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  537. fs.writeFileSync(unified, JSON.stringify({
  538. mcpServers: {
  539. 'code-review-graph': {
  540. command: 'uvx', args: ['code-review-graph', 'serve'], disabled: true,
  541. },
  542. },
  543. }, null, 2) + '\n');
  544. antigravity.install('global', { autoAllow: true });
  545. const after = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  546. expect(after.mcpServers['code-review-graph'].disabled).toBe(true);
  547. expect(after.mcpServers.codegraph).toBeDefined();
  548. });
  549. it('antigravity: uninstall removes only codegraph, sibling MCP server survives', () => {
  550. const antigravity = getTarget('antigravity')!;
  551. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  552. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  553. fs.writeFileSync(mcpFile, JSON.stringify({
  554. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  555. }, null, 2) + '\n');
  556. antigravity.install('global', { autoAllow: true });
  557. antigravity.uninstall('global');
  558. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  559. expect(after.mcpServers.other).toBeDefined();
  560. expect(after.mcpServers.codegraph).toBeUndefined();
  561. });
  562. it('antigravity: uninstall sweeps BOTH legacy and unified paths (handles migration half-state)', () => {
  563. const antigravity = getTarget('antigravity')!;
  564. // User had codegraph in BOTH files (e.g. legacy install + post-migration
  565. // re-install before our migration cleanup landed). Uninstall must clean
  566. // both so a "fresh slate" really is fresh.
  567. const legacy = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  568. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  569. fs.mkdirSync(path.dirname(legacy), { recursive: true });
  570. fs.mkdirSync(path.dirname(unified), { recursive: true });
  571. fs.writeFileSync(legacy, JSON.stringify({
  572. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  573. }, null, 2) + '\n');
  574. fs.writeFileSync(unified, JSON.stringify({
  575. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  576. }, null, 2) + '\n');
  577. fs.writeFileSync(path.join(path.dirname(unified), '.migrated'), '');
  578. antigravity.uninstall('global');
  579. const legacyAfter = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  580. const unifiedAfter = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  581. expect(legacyAfter.mcpServers).toBeUndefined();
  582. expect(unifiedAfter.mcpServers).toBeUndefined();
  583. });
  584. it('antigravity: rejects --location=local with a clear note (global-only IDE)', () => {
  585. const antigravity = getTarget('antigravity')!;
  586. expect(antigravity.supportsLocation('local')).toBe(false);
  587. const result = antigravity.install('local', { autoAllow: true });
  588. expect(result.files).toEqual([]);
  589. expect(result.notes?.join(' ')).toMatch(/no project-local config/);
  590. });
  591. it('antigravity: does not write GEMINI.md (only gemini target owns instructions)', () => {
  592. const antigravity = getTarget('antigravity')!;
  593. antigravity.install('global', { autoAllow: true });
  594. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  595. expect(fs.existsSync(geminiMd)).toBe(false);
  596. });
  597. it('gemini + antigravity: both installed coexist (separate MCP files, shared GEMINI.md)', () => {
  598. const gemini = getTarget('gemini')!;
  599. const antigravity = getTarget('antigravity')!;
  600. gemini.install('global', { autoAllow: true });
  601. antigravity.install('global', { autoAllow: true });
  602. const cliCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  603. // Antigravity lands on the LEGACY path here since no .migrated marker
  604. // was planted — same end-to-end check either way.
  605. const ideCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'), 'utf-8'));
  606. expect(cliCfg.mcpServers.codegraph).toBeDefined();
  607. expect(ideCfg.mcpServers.codegraph).toBeDefined();
  608. // Uninstall one — the other's MCP entry must survive.
  609. antigravity.uninstall('global');
  610. const cliAfter = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  611. expect(cliAfter.mcpServers.codegraph).toBeDefined();
  612. });
  613. it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
  614. const hermes = getTarget('hermes')!;
  615. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  616. fs.mkdirSync(path.dirname(config), { recursive: true });
  617. fs.writeFileSync(config, [
  618. 'model:',
  619. ' default: qwen-3.7',
  620. 'mcp_servers:',
  621. ' other:',
  622. ' command: other',
  623. 'platform_toolsets:',
  624. ' cli:',
  625. ' - hermes-cli',
  626. ' discord:',
  627. ' - hermes-discord',
  628. '',
  629. ].join('\n'));
  630. const result = hermes.install('global', { autoAllow: true });
  631. expect(result.files[0].action).toBe('updated');
  632. const body = fs.readFileSync(config, 'utf-8');
  633. expect(body).toContain('model:\n default: qwen-3.7');
  634. expect(body).toContain('mcp_servers:\n other:\n command: other');
  635. expect(body).toContain(' codegraph:\n command: codegraph');
  636. expect(body).toContain(' - hermes-cli');
  637. expect(body).toContain(' - mcp-codegraph');
  638. expect(body).toContain(' discord:\n - hermes-discord');
  639. const second = hermes.install('global', { autoAllow: true });
  640. expect(second.files[0].action).toBe('unchanged');
  641. });
  642. it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
  643. const hermes = getTarget('hermes')!;
  644. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  645. fs.mkdirSync(path.dirname(config), { recursive: true });
  646. hermes.install('global', { autoAllow: true });
  647. fs.appendFileSync(config, 'custom:\n keep: true\n');
  648. hermes.uninstall('global');
  649. const body = fs.readFileSync(config, 'utf-8');
  650. expect(body).not.toContain('codegraph:');
  651. expect(body).not.toContain('mcp-codegraph');
  652. expect(body).toContain('custom:\n keep: true');
  653. });
  654. // Regression for #456: PyYAML's default block style writes list items at the
  655. // SAME indent as the parent key (`cli:` and its `- hermes-cli` are both at
  656. // indent 2). The pre-fix line-based patcher mistook that first list item for
  657. // the next sibling key, truncated the cli block, and spliced `- mcp-codegraph`
  658. // at indent 4 BEFORE the existing items — producing unparseable YAML.
  659. it('hermes: install preserves PyYAML-default list-at-same-indent style (issue #456)', () => {
  660. const hermes = getTarget('hermes')!;
  661. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  662. fs.mkdirSync(path.dirname(config), { recursive: true });
  663. const original = [
  664. 'model:',
  665. ' default: gpt-4o',
  666. 'platform_toolsets:',
  667. ' cli:',
  668. ' - hermes-cli',
  669. ' - browser',
  670. ' - clarify',
  671. ' - terminal',
  672. ' - web',
  673. ' telegram:',
  674. ' - hermes-telegram',
  675. ' discord:',
  676. ' - hermes-discord',
  677. '',
  678. ].join('\n');
  679. fs.writeFileSync(config, original);
  680. hermes.install('global', { autoAllow: true });
  681. const body = fs.readFileSync(config, 'utf-8');
  682. // mcp-codegraph appended at the same 2-space indent as existing items
  683. expect(body).toContain('\n - mcp-codegraph\n');
  684. // hermes-cli preserved
  685. expect(body).toContain('\n - hermes-cli\n');
  686. // Sibling sections kept their indent — `telegram:` is still a key under
  687. // platform_toolsets, not promoted up.
  688. expect(body).toContain('\n telegram:\n - hermes-telegram\n');
  689. expect(body).toContain('\n discord:\n - hermes-discord\n');
  690. // No list items leaked to the platform_toolsets level (indent 0).
  691. expect(body).not.toMatch(/^- browser/m);
  692. expect(body).not.toMatch(/^- hermes-telegram/m);
  693. // The whole platform_toolsets block extracted by line search should
  694. // start with `cli:` and not contain a stray 4-space `mcp-codegraph`
  695. // appearing before the rest of the existing items.
  696. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  697. // Idempotent
  698. const second = hermes.install('global', { autoAllow: true });
  699. expect(second.files[0]?.action).toBe('unchanged');
  700. });
  701. it('hermes: uninstall reverses the install on a PyYAML-default config', () => {
  702. const hermes = getTarget('hermes')!;
  703. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  704. fs.mkdirSync(path.dirname(config), { recursive: true });
  705. const original = [
  706. 'platform_toolsets:',
  707. ' cli:',
  708. ' - hermes-cli',
  709. ' - browser',
  710. ' telegram:',
  711. ' - hermes-telegram',
  712. '',
  713. ].join('\n');
  714. fs.writeFileSync(config, original);
  715. hermes.install('global', { autoAllow: true });
  716. const installed = fs.readFileSync(config, 'utf-8');
  717. expect(installed).toContain('- mcp-codegraph');
  718. expect(installed).toContain('codegraph:');
  719. hermes.uninstall('global');
  720. const body = fs.readFileSync(config, 'utf-8');
  721. expect(body).not.toContain('mcp-codegraph');
  722. expect(body).not.toContain('command: codegraph');
  723. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  724. expect(body).toContain(' telegram:\n - hermes-telegram');
  725. });
  726. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  727. const opencode = getTarget('opencode')!;
  728. const dir = path.join(tmpHome, '.config', 'opencode');
  729. fs.mkdirSync(dir, { recursive: true });
  730. const file = path.join(dir, 'opencode.jsonc');
  731. fs.writeFileSync(file, [
  732. '{',
  733. ' // important comment',
  734. ' "$schema": "https://opencode.ai/config.json",',
  735. ' "mcp": {',
  736. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  737. ' }',
  738. '}',
  739. '',
  740. ].join('\n'));
  741. opencode.install('global', { autoAllow: true });
  742. const afterInstall = fs.readFileSync(file, 'utf-8');
  743. expect(afterInstall).toContain('"codegraph"');
  744. expect(afterInstall).toContain('"other"');
  745. opencode.uninstall('global');
  746. const afterUninstall = fs.readFileSync(file, 'utf-8');
  747. expect(afterUninstall).not.toContain('codegraph');
  748. expect(afterUninstall).toContain('// important comment');
  749. expect(afterUninstall).toContain('"other"');
  750. });
  751. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  752. const codex = getTarget('codex')!;
  753. codex.install('global', { autoAllow: false });
  754. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  755. const original = fs.readFileSync(tomlPath, 'utf-8');
  756. // User edits the block to add a custom key.
  757. const edited = original.replace(
  758. 'args = ["serve", "--mcp"]',
  759. 'args = ["serve", "--mcp"]\nenabled = true',
  760. );
  761. fs.writeFileSync(tomlPath, edited);
  762. // Re-install: our serializer doesn't know `enabled = true`, so
  763. // the block no longer matches the canonical form — we'll
  764. // overwrite it. This is the documented contract: we own the
  765. // codegraph block exclusively.
  766. const second = codex.install('global', { autoAllow: false });
  767. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  768. expect(tomlEntry.action).toBe('updated');
  769. const after = fs.readFileSync(tomlPath, 'utf-8');
  770. expect(after).not.toContain('enabled = true');
  771. });
  772. it('codex: install, re-install, and uninstall preserve trailing array-of-tables siblings', () => {
  773. const codex = getTarget('codex')!;
  774. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  775. fs.mkdirSync(path.dirname(tomlPath), { recursive: true });
  776. const historyTables = [
  777. '[[history]]',
  778. 'id = 1',
  779. 'note = "keep first"',
  780. '',
  781. '[[history]]',
  782. 'id = 2',
  783. 'note = "keep second"',
  784. '',
  785. ].join('\n');
  786. fs.writeFileSync(tomlPath, [
  787. '[mcp_servers.codegraph]',
  788. 'command = "old-codegraph"',
  789. 'args = ["old"]',
  790. 'description = """',
  791. 'header-shaped text inside a multiline string:',
  792. '[[not-a-table]]',
  793. 'still part of the string',
  794. '"""',
  795. '',
  796. historyTables,
  797. ].join('\n'));
  798. const first = codex.install('global', { autoAllow: false });
  799. expect(first.files.find((f) => f.path === tomlPath)?.action).toBe('updated');
  800. const afterInstall = fs.readFileSync(tomlPath, 'utf-8');
  801. expect(afterInstall).toContain('command = "codegraph"');
  802. expect(afterInstall).not.toContain('[[not-a-table]]');
  803. expect(afterInstall.endsWith(historyTables)).toBe(true);
  804. const second = codex.install('global', { autoAllow: false });
  805. expect(second.files.find((f) => f.path === tomlPath)?.action).toBe('unchanged');
  806. expect(fs.readFileSync(tomlPath, 'utf-8')).toBe(afterInstall);
  807. codex.uninstall('global');
  808. expect(fs.readFileSync(tomlPath, 'utf-8')).toBe(historyTables);
  809. });
  810. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  811. const claude = getTarget('claude')!;
  812. const result = claude.install('local', { autoAllow: false });
  813. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  814. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  815. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  816. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  817. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  818. expect(cfg.mcpServers.codegraph).toBeDefined();
  819. });
  820. it('claude: install creates the CLAUDE.md codegraph block (#704)', () => {
  821. const claude = getTarget('claude')!;
  822. const result = claude.install('local', { autoAllow: false });
  823. const claudeMd = path.join(tmpCwd, '.claude', 'CLAUDE.md');
  824. expect(fs.existsSync(claudeMd)).toBe(true);
  825. const body = fs.readFileSync(claudeMd, 'utf-8');
  826. expect(body).toContain('## CodeGraph');
  827. expect(body).toContain('codegraph explore');
  828. expect(result.files.find((f) => f.path.endsWith('CLAUDE.md'))?.action).toBe('created');
  829. });
  830. it('claude: install replaces a legacy CLAUDE.md codegraph block, keeping user content', () => {
  831. const claude = getTarget('claude')!;
  832. const claudeMd = path.join(tmpCwd, '.claude', 'CLAUDE.md');
  833. fs.mkdirSync(path.dirname(claudeMd), { recursive: true });
  834. fs.writeFileSync(claudeMd, `# My project rules\n\nUse tabs.\n\n${LEGACY_BLOCK}\n`);
  835. const result = claude.install('local', { autoAllow: false });
  836. const body = fs.readFileSync(claudeMd, 'utf-8');
  837. expect(body).toContain('# My project rules');
  838. expect(body).toContain('Use tabs.');
  839. expect(body).not.toContain('Prefer `codegraph_search`');
  840. expect(body).toContain('codegraph explore');
  841. expect(result.files.find((f) => f.path.endsWith('CLAUDE.md'))?.action).toBe('updated');
  842. });
  843. it('claude: global install targets ~/.claude.json (user scope)', () => {
  844. const claude = getTarget('claude')!;
  845. claude.install('global', { autoAllow: false });
  846. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  847. expect(cfg.mcpServers.codegraph).toBeDefined();
  848. });
  849. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  850. const claude = getTarget('claude')!;
  851. const legacy = path.join(tmpCwd, '.claude.json');
  852. fs.writeFileSync(
  853. legacy,
  854. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  855. );
  856. claude.install('local', { autoAllow: false });
  857. // codegraph now lives in .mcp.json; the legacy file (which held only
  858. // codegraph) is gone.
  859. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  860. expect(mcp.mcpServers.codegraph).toBeDefined();
  861. expect(fs.existsSync(legacy)).toBe(false);
  862. });
  863. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  864. const claude = getTarget('claude')!;
  865. const legacy = path.join(tmpCwd, '.claude.json');
  866. fs.writeFileSync(
  867. legacy,
  868. JSON.stringify({
  869. mcpServers: {
  870. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  871. other: { command: 'x' },
  872. },
  873. somethingElse: true,
  874. }, null, 2),
  875. );
  876. claude.install('local', { autoAllow: false });
  877. // Only codegraph is stripped from the legacy file; siblings survive.
  878. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  879. expect(after.mcpServers.codegraph).toBeUndefined();
  880. expect(after.mcpServers.other).toBeDefined();
  881. expect(after.somethingElse).toBe(true);
  882. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  883. expect(mcp.mcpServers.codegraph).toBeDefined();
  884. });
  885. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  886. const claude = getTarget('claude')!;
  887. // A user left with both the working .mcp.json and a stale .claude.json.
  888. fs.writeFileSync(
  889. path.join(tmpCwd, '.mcp.json'),
  890. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  891. );
  892. fs.writeFileSync(
  893. path.join(tmpCwd, '.claude.json'),
  894. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  895. );
  896. claude.uninstall('local');
  897. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  898. expect(mcp.mcpServers).toBeUndefined();
  899. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  900. expect(legacy.mcpServers.codegraph).toBeUndefined();
  901. expect(legacy.mcpServers.other).toBeDefined();
  902. });
  903. // ---- Legacy auto-sync hook cleanup ----
  904. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  905. // hooks to settings.json. Both subcommands were removed from the CLI,
  906. // so the Stop hook fails every turn ("unknown command
  907. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  908. // uninstall — without touching the user's unrelated hooks.
  909. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  910. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  911. fs.mkdirSync(dir, { recursive: true });
  912. const file = path.join(dir, 'settings.json');
  913. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  914. return file;
  915. }
  916. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  917. // unrelated GitKraken Stop hook the user added (matches the report).
  918. function legacyHookSettings(): Record<string, any> {
  919. return {
  920. hooks: {
  921. PostToolUse: [
  922. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  923. ],
  924. Stop: [
  925. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  926. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  927. ],
  928. },
  929. };
  930. }
  931. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  932. const claude = getTarget('claude')!;
  933. const file = seedSettings('global', legacyHookSettings());
  934. claude.install('global', { autoAllow: true });
  935. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  936. // The only PostToolUse group held mark-dirty → the event is gone.
  937. expect(after.hooks?.PostToolUse).toBeUndefined();
  938. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  939. (g.hooks ?? []).map((h: any) => h.command),
  940. );
  941. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  942. // The unrelated GitKraken hook survives untouched.
  943. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  944. // Permissions still written as normal alongside the cleanup.
  945. expect(after.permissions?.allow).toContain('mcp__codegraph__*');
  946. });
  947. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  948. const file = seedSettings('global', {
  949. hooks: {
  950. Stop: [
  951. {
  952. hooks: [
  953. { type: 'command', command: 'codegraph sync-if-dirty' },
  954. { type: 'command', command: 'gk ai hook run --host claude-code' },
  955. ],
  956. },
  957. ],
  958. },
  959. });
  960. expect(cleanupLegacyHooks('global').action).toBe('removed');
  961. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  962. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  963. 'gk ai hook run --host claude-code',
  964. ]);
  965. });
  966. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  967. const original =
  968. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  969. const file = seedSettings('global', JSON.parse(original));
  970. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  971. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  972. });
  973. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  974. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  975. });
  976. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  977. const claude = getTarget('claude')!;
  978. const file = seedSettings('global', legacyHookSettings());
  979. claude.install('global', { autoAllow: true });
  980. const firstPass = fs.readFileSync(file, 'utf-8');
  981. claude.install('global', { autoAllow: true });
  982. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  983. });
  984. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  985. const claude = getTarget('claude')!;
  986. const file = seedSettings('local', {
  987. hooks: {
  988. PostToolUse: [
  989. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  990. ],
  991. Stop: [
  992. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  993. ],
  994. },
  995. });
  996. claude.uninstall('local');
  997. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  998. // Both events emptied → the whole `hooks` object is removed.
  999. expect(after.hooks).toBeUndefined();
  1000. });
  1001. // ---- Front-load prompt hook (UserPromptSubmit) — #841 follow-up ----
  1002. // Opt-in (default-yes in the installer) UserPromptSubmit hook that runs
  1003. // `codegraph prompt-hook`. Must write/remove surgically, be idempotent, and
  1004. // round-trip an opt-out — without disturbing the user's own hooks.
  1005. const promptCommands = (s: any): string[] =>
  1006. (s.hooks?.UserPromptSubmit ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  1007. it('claude: install with promptHook:true writes the UserPromptSubmit hook (alongside permissions)', () => {
  1008. const claude = getTarget('claude')!;
  1009. claude.install('global', { autoAllow: true, promptHook: true });
  1010. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1011. expect(promptCommands(s)).toContain('codegraph prompt-hook');
  1012. expect(s.permissions?.allow).toContain('mcp__codegraph__*');
  1013. });
  1014. it('claude: install without promptHook does NOT add the hook', () => {
  1015. const claude = getTarget('claude')!;
  1016. claude.install('global', { autoAllow: true });
  1017. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1018. expect(promptCommands(s)).not.toContain('codegraph prompt-hook');
  1019. });
  1020. it('claude: install with promptHook:true is idempotent (no duplicate, byte-identical re-run)', () => {
  1021. const claude = getTarget('claude')!;
  1022. const file = path.join(tmpHome, '.claude', 'settings.json');
  1023. claude.install('global', { autoAllow: true, promptHook: true });
  1024. const first = fs.readFileSync(file, 'utf-8');
  1025. claude.install('global', { autoAllow: true, promptHook: true });
  1026. expect(fs.readFileSync(file, 'utf-8')).toBe(first);
  1027. const s = JSON.parse(first);
  1028. expect(promptCommands(s).filter((c: string) => c === 'codegraph prompt-hook')).toHaveLength(1);
  1029. });
  1030. it('claude: install with promptHook:false strips a hook a prior install wrote (opt-out round-trips)', () => {
  1031. const claude = getTarget('claude')!;
  1032. claude.install('global', { autoAllow: true, promptHook: true });
  1033. claude.install('global', { autoAllow: true, promptHook: false });
  1034. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1035. expect(promptCommands(s)).not.toContain('codegraph prompt-hook');
  1036. });
  1037. it('claude: writePromptHookEntry preserves a sibling UserPromptSubmit hook', () => {
  1038. const file = seedSettings('global', {
  1039. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'my-own-hook' }] }] },
  1040. });
  1041. expect(writePromptHookEntry('global').action).toBe('updated');
  1042. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1043. expect(promptCommands(s)).toEqual(['my-own-hook', 'codegraph prompt-hook']);
  1044. });
  1045. it('claude: uninstall removes the prompt hook but keeps the user\'s sibling', () => {
  1046. const file = seedSettings('global', {
  1047. hooks: {
  1048. UserPromptSubmit: [
  1049. { hooks: [{ type: 'command', command: 'codegraph prompt-hook' }] },
  1050. { hooks: [{ type: 'command', command: 'my-own-hook' }] },
  1051. ],
  1052. },
  1053. });
  1054. getTarget('claude')!.uninstall('global');
  1055. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1056. expect(promptCommands(s)).toEqual(['my-own-hook']);
  1057. });
  1058. it('claude: removePromptHookEntry leaves the legacy auto-sync hook untouched', () => {
  1059. const file = seedSettings('global', {
  1060. hooks: {
  1061. UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'codegraph prompt-hook' }] }],
  1062. Stop: [{ hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] }],
  1063. },
  1064. });
  1065. expect(removePromptHookEntry('global').action).toBe('removed');
  1066. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1067. expect(promptCommands(s)).not.toContain('codegraph prompt-hook');
  1068. const stopCmds = (s.hooks?.Stop ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  1069. expect(stopCmds).toContain('codegraph sync-if-dirty');
  1070. });
  1071. });
  1072. describe('Installer targets — registry', () => {
  1073. it('getTarget returns the right target for each id', () => {
  1074. expect(getTarget('claude')?.id).toBe('claude');
  1075. expect(getTarget('cursor')?.id).toBe('cursor');
  1076. expect(getTarget('codex')?.id).toBe('codex');
  1077. expect(getTarget('opencode')?.id).toBe('opencode');
  1078. expect(getTarget('hermes')?.id).toBe('hermes');
  1079. expect(getTarget('gemini')?.id).toBe('gemini');
  1080. expect(getTarget('antigravity')?.id).toBe('antigravity');
  1081. expect(getTarget('kiro')?.id).toBe('kiro');
  1082. expect(getTarget('copilot-vscode')?.id).toBe('copilot-vscode');
  1083. expect(getTarget('copilot-cli')?.id).toBe('copilot-cli');
  1084. expect(getTarget('copilot-jetbrains')?.id).toBe('copilot-jetbrains');
  1085. expect(getTarget('not-a-real-target')).toBeUndefined();
  1086. });
  1087. it('resolveTargetFlag handles auto/all/none/csv', () => {
  1088. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  1089. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  1090. const csv = resolveTargetFlag('claude,cursor', 'global');
  1091. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  1092. });
  1093. it("resolveTargetFlag('all') includes every Copilot target", () => {
  1094. const ids = resolveTargetFlag('all', 'global').map((t) => t.id);
  1095. expect(ids).toContain('copilot-vscode');
  1096. expect(ids).toContain('copilot-cli');
  1097. expect(ids).toContain('copilot-jetbrains');
  1098. });
  1099. it('resolveTargetFlag resolves the Copilot ids from a csv list', () => {
  1100. const csv = resolveTargetFlag('copilot-vscode,copilot-cli,copilot-jetbrains', 'global');
  1101. expect(csv.map((t) => t.id)).toEqual(['copilot-vscode', 'copilot-cli', 'copilot-jetbrains']);
  1102. });
  1103. it('resolveTargetFlag throws on unknown id', () => {
  1104. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  1105. });
  1106. });
  1107. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  1108. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  1109. const block = buildTomlTable('mcp_servers.codegraph', {
  1110. command: 'codegraph',
  1111. args: ['serve', '--mcp'],
  1112. });
  1113. expect(block).toContain('[mcp_servers.codegraph]');
  1114. expect(block).toContain('command = "codegraph"');
  1115. expect(block).toContain('args = ["serve", "--mcp"]');
  1116. });
  1117. it('upsert inserts into empty content', () => {
  1118. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1119. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1120. expect(action).toBe('inserted');
  1121. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  1122. });
  1123. it('upsert is idempotent — second call returns unchanged', () => {
  1124. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1125. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1126. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  1127. expect(second.action).toBe('unchanged');
  1128. expect(second.content).toBe(first.content);
  1129. });
  1130. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  1131. const existing = [
  1132. '[other_table]',
  1133. 'foo = "bar"',
  1134. '',
  1135. '[mcp_servers.codegraph]',
  1136. 'command = "old-codegraph"',
  1137. 'args = ["old"]',
  1138. '',
  1139. '[zzz]',
  1140. 'baz = "qux"',
  1141. '',
  1142. ].join('\n');
  1143. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  1144. command: 'codegraph',
  1145. args: ['serve', '--mcp'],
  1146. });
  1147. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  1148. expect(action).toBe('replaced');
  1149. expect(content).toContain('[other_table]');
  1150. expect(content).toContain('foo = "bar"');
  1151. expect(content).toContain('[zzz]');
  1152. expect(content).toContain('baz = "qux"');
  1153. expect(content).toContain('command = "codegraph"');
  1154. expect(content).not.toContain('old-codegraph');
  1155. });
  1156. it('removeTomlTable strips the block and preserves siblings', () => {
  1157. const existing = [
  1158. '[other_table]',
  1159. 'foo = "bar"',
  1160. '',
  1161. '[mcp_servers.codegraph]',
  1162. 'command = "codegraph"',
  1163. 'args = ["serve"]',
  1164. ].join('\n');
  1165. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1166. expect(action).toBe('removed');
  1167. expect(content).toContain('[other_table]');
  1168. expect(content).toContain('foo = "bar"');
  1169. expect(content).not.toContain('mcp_servers.codegraph');
  1170. });
  1171. it('removeTomlTable on missing table returns not-found, no content change', () => {
  1172. const existing = '[other]\nfoo = "bar"\n';
  1173. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1174. expect(action).toBe('not-found');
  1175. expect(content).toBe(existing);
  1176. });
  1177. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  1178. const existing = [
  1179. '[[foo]]',
  1180. 'name = "a"',
  1181. '',
  1182. '[[foo]]',
  1183. 'name = "b"',
  1184. '',
  1185. ].join('\n');
  1186. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1187. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1188. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  1189. expect(content).toContain('[mcp_servers.codegraph]');
  1190. });
  1191. it('upsert replaces the managed table without consuming trailing array-of-tables siblings', () => {
  1192. const historyTables = [
  1193. '[[history]]',
  1194. 'id = 1',
  1195. 'note = "keep first"',
  1196. '',
  1197. '[[history]]',
  1198. 'id = 2',
  1199. 'note = "keep second"',
  1200. '',
  1201. ].join('\n');
  1202. const existing = [
  1203. '[mcp_servers.codegraph]',
  1204. 'command = "old-codegraph"',
  1205. 'args = ["old"]',
  1206. '',
  1207. historyTables,
  1208. ].join('\n');
  1209. const block = buildTomlTable('mcp_servers.codegraph', {
  1210. command: 'codegraph',
  1211. args: ['serve', '--mcp'],
  1212. });
  1213. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1214. expect(action).toBe('replaced');
  1215. expect(content).toBe(`${block}\n\n${historyTables}`);
  1216. });
  1217. it('remove preserves trailing array-of-tables siblings byte-for-byte', () => {
  1218. const historyTables = [
  1219. '[[history]]',
  1220. 'id = 1',
  1221. 'note = "keep first"',
  1222. '',
  1223. '[[history]]',
  1224. 'id = 2',
  1225. 'note = "keep second"',
  1226. '',
  1227. ].join('\n');
  1228. const existing = [
  1229. '[mcp_servers.codegraph]',
  1230. 'command = "codegraph"',
  1231. 'args = ["serve", "--mcp"]',
  1232. '',
  1233. historyTables,
  1234. ].join('\n');
  1235. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1236. expect(action).toBe('removed');
  1237. expect(content).toBe(historyTables);
  1238. });
  1239. it.each([
  1240. ['table', '[ mcp_servers.other ]'],
  1241. ['array-of-tables', '[[ history ]]'],
  1242. ])('preserves a trailing %s header with inner whitespace', (_kind, siblingHeader) => {
  1243. const siblingTable = `${siblingHeader}\nvalue = "keep"\n`;
  1244. const existing = [
  1245. '[mcp_servers.codegraph]',
  1246. 'command = "old-codegraph"',
  1247. 'args = ["old"]',
  1248. '',
  1249. siblingTable,
  1250. ].join('\n');
  1251. const block = buildTomlTable('mcp_servers.codegraph', {
  1252. command: 'codegraph',
  1253. args: ['serve', '--mcp'],
  1254. });
  1255. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1256. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1257. expect(upserted.content).toBe(`${block}\n\n${siblingTable}`);
  1258. expect(removed.content).toBe(siblingTable);
  1259. });
  1260. it.each([
  1261. ['basic', '"""'],
  1262. ['literal', "'''"],
  1263. ])('ignores header-shaped text inside a multiline %s string', (_kind, delimiter) => {
  1264. const historyTable = '[[history]]\nid = 1\n';
  1265. const existing = [
  1266. '[mcp_servers.codegraph]',
  1267. 'command = "old-codegraph"',
  1268. 'args = [',
  1269. ` ${delimiter}first line`,
  1270. '[[not-a-table]]',
  1271. `last line${delimiter},`,
  1272. ' "serve",',
  1273. ']',
  1274. '',
  1275. historyTable,
  1276. ].join('\n');
  1277. const block = buildTomlTable('mcp_servers.codegraph', {
  1278. command: 'codegraph',
  1279. args: ['serve', '--mcp'],
  1280. });
  1281. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1282. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1283. expect(upserted.content).toBe(`${block}\n\n${historyTable}`);
  1284. expect(removed.content).toBe(historyTable);
  1285. });
  1286. });
  1287. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  1288. let tmpHome: string;
  1289. let tmpCwd: string;
  1290. let origCwd: string;
  1291. let homeRestore: { restore: () => void };
  1292. beforeEach(() => {
  1293. tmpHome = mkTmpDir('un-home');
  1294. tmpCwd = mkTmpDir('un-cwd');
  1295. origCwd = process.cwd();
  1296. process.chdir(tmpCwd);
  1297. homeRestore = setHome(tmpHome);
  1298. });
  1299. afterEach(() => {
  1300. homeRestore.restore();
  1301. process.chdir(origCwd);
  1302. fs.rmSync(tmpHome, { recursive: true, force: true });
  1303. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1304. });
  1305. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  1306. for (const t of ALL_TARGETS) {
  1307. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1308. }
  1309. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1310. for (const t of ALL_TARGETS) {
  1311. const r = reports.find((x) => x.id === t.id)!;
  1312. expect(r.status).toBe('removed');
  1313. expect(r.removedPaths.length).toBeGreaterThan(0);
  1314. // The actual config is gone afterward.
  1315. expect(t.detect('global').alreadyConfigured).toBe(false);
  1316. }
  1317. });
  1318. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  1319. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1320. for (const r of reports) {
  1321. expect(r.status).toBe('not-configured');
  1322. expect(r.removedPaths).toEqual([]);
  1323. }
  1324. });
  1325. it('reports removed only for agents that were actually configured', () => {
  1326. // Install on Claude only; the rest stay untouched.
  1327. getTarget('claude')!.install('global', { autoAllow: true });
  1328. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1329. const claude = reports.find((r) => r.id === 'claude')!;
  1330. expect(claude.status).toBe('removed');
  1331. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  1332. for (const r of reports.filter((x) => x.id !== 'claude')) {
  1333. expect(r.status).toBe('not-configured');
  1334. }
  1335. });
  1336. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  1337. const reports = uninstallTargets(ALL_TARGETS, 'local');
  1338. for (const t of ALL_TARGETS) {
  1339. const r = reports.find((x) => x.id === t.id)!;
  1340. if (t.supportsLocation('local')) {
  1341. expect(r.status).toBe('not-configured');
  1342. } else {
  1343. expect(r.status).toBe('unsupported');
  1344. expect(r.removedPaths).toEqual([]);
  1345. expect(r.notes[0]).toMatch(/global-only/);
  1346. }
  1347. }
  1348. });
  1349. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1350. for (const t of ALL_TARGETS) {
  1351. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1352. }
  1353. const first = uninstallTargets(ALL_TARGETS, 'global');
  1354. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1355. const second = uninstallTargets(ALL_TARGETS, 'global');
  1356. for (const r of second) {
  1357. expect(r.status).toBe('not-configured');
  1358. expect(r.removedPaths).toEqual([]);
  1359. }
  1360. });
  1361. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1362. getTarget('claude')!.install('global', { autoAllow: true });
  1363. getTarget('cursor')!.install('global', { autoAllow: true });
  1364. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1365. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1366. expect(reports[0].status).toBe('removed');
  1367. // Cursor was not in the subset — still configured.
  1368. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1369. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1370. });
  1371. });
  1372. describe('Installer — refreshTargets sweep (codegraph install --refresh)', () => {
  1373. let tmpHome: string;
  1374. let tmpCwd: string;
  1375. let origCwd: string;
  1376. let homeRestore: { restore: () => void };
  1377. beforeEach(() => {
  1378. tmpHome = mkTmpDir('rf-home');
  1379. tmpCwd = mkTmpDir('rf-cwd');
  1380. origCwd = process.cwd();
  1381. process.chdir(tmpCwd);
  1382. homeRestore = setHome(tmpHome);
  1383. });
  1384. afterEach(() => {
  1385. homeRestore.restore();
  1386. process.chdir(origCwd);
  1387. fs.rmSync(tmpHome, { recursive: true, force: true });
  1388. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1389. });
  1390. it('rewrites a stale instructions block a previous version left, and reports refreshed', () => {
  1391. const claude = getTarget('claude')!;
  1392. claude.install('global', { autoAllow: true });
  1393. // Simulate the file as an old install left it: same markers, the old
  1394. // multi-tool wording.
  1395. const claudeMd = path.join(tmpHome, '.claude', 'CLAUDE.md');
  1396. fs.writeFileSync(claudeMd, LEGACY_BLOCK + '\n');
  1397. const reports = refreshTargets([claude], 'global');
  1398. expect(reports[0].status).toBe('refreshed');
  1399. expect(reports[0].changedPaths).toContain(claudeMd);
  1400. const md = fs.readFileSync(claudeMd, 'utf-8');
  1401. expect(md).not.toContain('codegraph_search');
  1402. expect(md).toContain('codegraph_explore');
  1403. });
  1404. it('never performs a first install — unconfigured agents stay untouched', () => {
  1405. const reports = refreshTargets(ALL_TARGETS, 'global');
  1406. for (const t of ALL_TARGETS) {
  1407. const r = reports.find((x) => x.id === t.id)!;
  1408. expect(r.status).toBe(t.supportsLocation('global') ? 'not-configured' : 'unsupported');
  1409. expect(r.changedPaths).toEqual([]);
  1410. expect(t.detect('global').alreadyConfigured).toBe(false);
  1411. }
  1412. });
  1413. it('preserves the user\'s permission choices (refresh never writes permissions)', () => {
  1414. const claude = getTarget('claude')!;
  1415. claude.install('global', { autoAllow: true });
  1416. // The user has since trimmed the allowlist by hand.
  1417. const settingsPath = path.join(tmpHome, '.claude', 'settings.json');
  1418. const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1419. settings.permissions.allow = [];
  1420. fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
  1421. refreshTargets([claude], 'global');
  1422. const after = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1423. expect(after.permissions.allow).toEqual([]);
  1424. });
  1425. it('is idempotent — a second sweep on a current machine reports unchanged everywhere', () => {
  1426. for (const t of ALL_TARGETS) {
  1427. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1428. }
  1429. const first = refreshTargets(ALL_TARGETS, 'global');
  1430. // Fresh installs are already current, so even the first sweep may be
  1431. // all-unchanged; what matters is the second definitely is.
  1432. const second = refreshTargets(ALL_TARGETS, 'global');
  1433. for (const r of [...first, ...second]) {
  1434. expect(['unchanged', 'refreshed']).toContain(r.status);
  1435. }
  1436. for (const r of second) {
  1437. expect(r.status).toBe('unchanged');
  1438. expect(r.changedPaths).toEqual([]);
  1439. }
  1440. });
  1441. });
  1442. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1443. let tmpHome: string;
  1444. let tmpCwd: string;
  1445. let origCwd: string;
  1446. let homeRestore: { restore: () => void };
  1447. const cursor = getTarget('cursor')!;
  1448. beforeEach(() => {
  1449. tmpHome = mkTmpDir('cur-home');
  1450. tmpCwd = mkTmpDir('cur-cwd');
  1451. origCwd = process.cwd();
  1452. process.chdir(tmpCwd);
  1453. homeRestore = setHome(tmpHome);
  1454. });
  1455. afterEach(() => {
  1456. homeRestore.restore();
  1457. process.chdir(origCwd);
  1458. fs.rmSync(tmpHome, { recursive: true, force: true });
  1459. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1460. });
  1461. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1462. // The frontmatter a previous install wrote ahead of the marked block.
  1463. // `removeRulesEntry` recognizes it to decide whether the leftover .mdc
  1464. // is ours-to-delete or carries user content worth keeping.
  1465. const MDC_FRONTMATTER = [
  1466. '---',
  1467. 'description: CodeGraph MCP usage guide — when to use which tool',
  1468. 'alwaysApply: true',
  1469. '---',
  1470. '',
  1471. ].join('\n');
  1472. function plantLegacyRulesFile(extra = ''): void {
  1473. fs.mkdirSync(path.dirname(rulesFile()), { recursive: true });
  1474. fs.writeFileSync(rulesFile(), MDC_FRONTMATTER + LEGACY_BLOCK + '\n' + extra);
  1475. }
  1476. it('uninstall deletes a leftover codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1477. plantLegacyRulesFile();
  1478. expect(fs.existsSync(rulesFile())).toBe(true);
  1479. cursor.uninstall('local');
  1480. // The whole file — frontmatter included — is gone, not just the block.
  1481. expect(fs.existsSync(rulesFile())).toBe(false);
  1482. });
  1483. it('install self-heals a leftover codegraph.mdc (#529)', () => {
  1484. plantLegacyRulesFile();
  1485. const result = cursor.install('local', { autoAllow: true });
  1486. expect(fs.existsSync(rulesFile())).toBe(false);
  1487. expect(result.files.some((f) => f.path.endsWith('codegraph.mdc') && f.action === 'removed')).toBe(true);
  1488. });
  1489. it('uninstall preserves user content added outside the codegraph markers (strips only our block)', () => {
  1490. plantLegacyRulesFile('## My own rule\nkeep me\n');
  1491. cursor.uninstall('local');
  1492. expect(fs.existsSync(rulesFile())).toBe(true);
  1493. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1494. expect(after).toContain('keep me');
  1495. // Our tool-usage block is gone.
  1496. expect(after).not.toContain('codegraph_search');
  1497. expect(after).not.toContain('CODEGRAPH_START');
  1498. });
  1499. });
  1500. function listAllFiles(dir: string): string[] {
  1501. if (!fs.existsSync(dir)) return [];
  1502. const out: string[] = [];
  1503. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1504. const full = path.join(dir, entry.name);
  1505. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1506. else out.push(full);
  1507. }
  1508. return out;
  1509. }
  1510. // ---------------------------------------------------------------------------
  1511. // opencode global config path — XDG on every platform (#535)
  1512. //
  1513. // opencode resolves its config dir with `xdg-basedir`: XDG_CONFIG_HOME if
  1514. // set, else ~/.config — on ALL platforms, Windows included. It never reads
  1515. // %APPDATA%; we used to write there on Windows, so opencode never saw the
  1516. // entry. The suite-wide setHome() points APPDATA and XDG_CONFIG_HOME at the
  1517. // SAME directory (which is exactly how this bug stayed invisible), so these
  1518. // tests deliberately split them.
  1519. // ---------------------------------------------------------------------------
  1520. describe('Installer targets — opencode XDG config path (#535)', () => {
  1521. let tmpHome: string;
  1522. let tmpCwd: string;
  1523. let origCwd: string;
  1524. let homeRestore: { restore: () => void };
  1525. let appDataDir: string; // distinct from ~/.config, like real Windows
  1526. beforeEach(() => {
  1527. tmpHome = mkTmpDir('home');
  1528. tmpCwd = mkTmpDir('cwd');
  1529. origCwd = process.cwd();
  1530. process.chdir(tmpCwd);
  1531. homeRestore = setHome(tmpHome);
  1532. appDataDir = path.join(tmpHome, 'AppData', 'Roaming');
  1533. process.env.APPDATA = appDataDir; // realistic split: APPDATA ≠ ~/.config
  1534. delete process.env.XDG_CONFIG_HOME; // default resolution: ~/.config
  1535. });
  1536. afterEach(() => {
  1537. homeRestore.restore();
  1538. process.chdir(origCwd);
  1539. fs.rmSync(tmpHome, { recursive: true, force: true });
  1540. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1541. });
  1542. const xdgConfigFile = () => path.join(tmpHome, '.config', 'opencode', 'opencode.jsonc');
  1543. const legacyDir = () => path.join(appDataDir, 'opencode');
  1544. // NOTE: never match on an 'AppData' substring — on Windows os.tmpdir()
  1545. // itself lives under AppData\Local\Temp, so EVERY harness path contains
  1546. // it. Match on the legacy dir prefix instead.
  1547. const inLegacyDir = (p: string) => path.resolve(p).startsWith(path.resolve(legacyDir()) + path.sep);
  1548. it('global install writes to ~/.config/opencode, never %APPDATA% (#535)', () => {
  1549. const opencode = getTarget('opencode')!;
  1550. const result = opencode.install('global', { autoAllow: true });
  1551. const written = result.files.find((f) => f.path.endsWith('opencode.jsonc'))!;
  1552. expect(written.action).toBe('created');
  1553. expect(path.resolve(written.path)).toBe(path.resolve(xdgConfigFile()));
  1554. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1555. // Nothing of ours may land in the legacy location.
  1556. expect(fs.existsSync(legacyDir())).toBe(false);
  1557. });
  1558. it('greenfield: targets ~/.config/opencode even when the dir does not exist yet (#535)', () => {
  1559. // The rejected fallback design (#670) would send this install to
  1560. // %APPDATA% — where opencode would never find it. opencode creates
  1561. // ~/.config/opencode itself on first run; installing codegraph FIRST
  1562. // must land where opencode will look.
  1563. expect(fs.existsSync(path.join(tmpHome, '.config', 'opencode'))).toBe(false);
  1564. const opencode = getTarget('opencode')!;
  1565. const result = opencode.install('global', { autoAllow: true });
  1566. expect(path.resolve(result.files[0]!.path)).toBe(path.resolve(xdgConfigFile()));
  1567. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1568. expect(fs.existsSync(legacyDir())).toBe(false);
  1569. });
  1570. it('honors XDG_CONFIG_HOME for the global path, like opencode does', () => {
  1571. const custom = path.join(tmpHome, 'xdg-custom');
  1572. process.env.XDG_CONFIG_HOME = custom;
  1573. const opencode = getTarget('opencode')!;
  1574. const result = opencode.install('global', { autoAllow: true });
  1575. expect(path.resolve(result.files[0]!.path))
  1576. .toBe(path.resolve(path.join(custom, 'opencode', 'opencode.jsonc')));
  1577. });
  1578. it('install self-heals a pre-#535 %APPDATA% entry, preserving siblings and comments', () => {
  1579. // A previous codegraph version wrote into %APPDATA%/opencode. The user
  1580. // also has another MCP server and a comment there — those must survive.
  1581. fs.mkdirSync(legacyDir(), { recursive: true });
  1582. fs.writeFileSync(path.join(legacyDir(), 'opencode.jsonc'), [
  1583. '{',
  1584. ' // my servers',
  1585. ' "$schema": "https://opencode.ai/config.json",',
  1586. ' "mcp": {',
  1587. ' "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true },',
  1588. ' "other": { "type": "local", "command": ["other"], "enabled": true }',
  1589. ' }',
  1590. '}',
  1591. '',
  1592. ].join('\n'));
  1593. fs.writeFileSync(path.join(legacyDir(), 'AGENTS.md'), LEGACY_BLOCK + '\n');
  1594. const opencode = getTarget('opencode')!;
  1595. const result = opencode.install('global', { autoAllow: true });
  1596. // New entry in the right place…
  1597. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1598. // …stale entry swept out of the legacy file, siblings + comment intact.
  1599. const legacyText = fs.readFileSync(path.join(legacyDir(), 'opencode.jsonc'), 'utf-8');
  1600. expect(legacyText).not.toContain('codegraph');
  1601. expect(legacyText).toContain('"other"');
  1602. expect(legacyText).toContain('// my servers');
  1603. // …and the legacy AGENTS.md — block-only, so emptied — removed outright
  1604. // (removeMarkedSection unlinks a file it leaves empty).
  1605. expect(fs.existsSync(path.join(legacyDir(), 'AGENTS.md'))).toBe(false);
  1606. // Both cleanups are reported.
  1607. const removed = result.files.filter((f) => f.action === 'removed').map((f) => f.path);
  1608. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('opencode.jsonc'))).toBe(true);
  1609. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('AGENTS.md'))).toBe(true);
  1610. });
  1611. it('uninstall sweeps the legacy %APPDATA% entry too (no prior re-install needed)', () => {
  1612. // A user on the broken version goes straight to `codegraph uninstall`:
  1613. // the only entry that exists is the stale %APPDATA% one.
  1614. fs.mkdirSync(legacyDir(), { recursive: true });
  1615. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1616. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1617. const opencode = getTarget('opencode')!;
  1618. const result = opencode.uninstall('global');
  1619. expect(fs.readFileSync(path.join(legacyDir(), 'opencode.json'), 'utf-8')).not.toContain('codegraph');
  1620. expect(result.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1621. });
  1622. it('install after install sweeps only once — second run reports no legacy changes', () => {
  1623. fs.mkdirSync(legacyDir(), { recursive: true });
  1624. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1625. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1626. const opencode = getTarget('opencode')!;
  1627. const first = opencode.install('global', { autoAllow: true });
  1628. expect(first.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1629. const second = opencode.install('global', { autoAllow: true });
  1630. expect(second.files.some((f) => inLegacyDir(f.path))).toBe(false);
  1631. expect(second.files.find((f) => f.path.endsWith('opencode.jsonc'))!.action).toBe('unchanged');
  1632. });
  1633. it('detects opencode as installed from a legacy-only %APPDATA% dir (so install can heal it)', () => {
  1634. fs.mkdirSync(legacyDir(), { recursive: true });
  1635. const opencode = getTarget('opencode')!;
  1636. expect(opencode.detect('global').installed).toBe(true);
  1637. // But configuration state is read from the REAL path only.
  1638. expect(opencode.detect('global').alreadyConfigured).toBe(false);
  1639. });
  1640. });
  1641. // ---------------------------------------------------------------------------
  1642. // Copilot family — copilot-vscode / copilot-cli / copilot-jetbrains (CG-5)
  1643. //
  1644. // The registry-driven contract suite above covers the shared surface
  1645. // (install/idempotency/sibling/uninstall/printConfig). These pin the
  1646. // target-specific behavior: OS-specific global paths, `--path` injection
  1647. // (copilot-vscode mirrors Cursor), global-only skip semantics (cli +
  1648. // jetbrains, Codex pattern), COPILOT_HOME resolution, JSONC comment
  1649. // preservation, empty-`servers`-wrapper cleanup, and printConfig parity
  1650. // with what install writes.
  1651. // ---------------------------------------------------------------------------
  1652. describe('Installer targets — Copilot family', () => {
  1653. let tmpHome: string;
  1654. let tmpCwd: string;
  1655. let origCwd: string;
  1656. let homeRestore: { restore: () => void };
  1657. beforeEach(() => {
  1658. tmpHome = mkTmpDir('cop-home');
  1659. tmpCwd = mkTmpDir('cop-cwd');
  1660. origCwd = process.cwd();
  1661. process.chdir(tmpCwd);
  1662. homeRestore = setHome(tmpHome);
  1663. });
  1664. afterEach(() => {
  1665. homeRestore.restore();
  1666. process.chdir(origCwd);
  1667. fs.rmSync(tmpHome, { recursive: true, force: true });
  1668. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1669. });
  1670. // printConfig embeds the paste-able snippet after a `# Add to <path>`
  1671. // header — extract and parse just the JSON body.
  1672. function snippetJson(out: string): any {
  1673. const start = out.indexOf('{');
  1674. expect(start).toBeGreaterThanOrEqual(0);
  1675. return JSON.parse(out.slice(start));
  1676. }
  1677. // ---- copilot-vscode ----
  1678. it('copilot-vscode: local install writes ./.vscode/mcp.json with servers.codegraph and an absolute --path pin', () => {
  1679. const t = getTarget('copilot-vscode')!;
  1680. const result = t.install('local', { autoAllow: true });
  1681. const file = path.join(process.cwd(), '.vscode', 'mcp.json');
  1682. expect(result.files[0].path).toBe(file);
  1683. expect(result.files[0].action).toBe('created');
  1684. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1685. expect(cfg.servers.codegraph.type).toBe('stdio');
  1686. expect(cfg.servers.codegraph.command).toBe('codegraph');
  1687. // Cursor-mirror: local installs pin the project with an absolute path.
  1688. expect(cfg.servers.codegraph.args).toEqual(['serve', '--mcp', '--path', process.cwd()]);
  1689. // No mcpServers wrapper — VS Code's mcp.json uses `servers`.
  1690. expect(cfg.mcpServers).toBeUndefined();
  1691. });
  1692. it('copilot-vscode: global install pins --path to ${workspaceFolder}', () => {
  1693. const t = getTarget('copilot-vscode')!;
  1694. const result = t.install('global', { autoAllow: true });
  1695. const cfg = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  1696. expect(cfg.servers.codegraph.args).toEqual(['serve', '--mcp', '--path', '${workspaceFolder}']);
  1697. });
  1698. it.runIf(process.platform === 'darwin')('copilot-vscode: global path is ~/Library/Application Support/Code/User/mcp.json on macOS', () => {
  1699. const t = getTarget('copilot-vscode')!;
  1700. const expected = path.join(tmpHome, 'Library', 'Application Support', 'Code', 'User', 'mcp.json');
  1701. expect(t.describePaths('global')).toEqual([expected]);
  1702. const result = t.install('global', { autoAllow: true });
  1703. expect(result.files[0].path).toBe(expected);
  1704. expect(fs.existsSync(expected)).toBe(true);
  1705. });
  1706. it.runIf(process.platform === 'linux')('copilot-vscode: global path honors XDG_CONFIG_HOME on Linux', () => {
  1707. const t = getTarget('copilot-vscode')!;
  1708. // setHome() points XDG_CONFIG_HOME at <home>/.config.
  1709. const expected = path.join(tmpHome, '.config', 'Code', 'User', 'mcp.json');
  1710. expect(t.describePaths('global')).toEqual([expected]);
  1711. const result = t.install('global', { autoAllow: true });
  1712. expect(result.files[0].path).toBe(expected);
  1713. });
  1714. it.runIf(process.platform === 'win32')('copilot-vscode: global path is %APPDATA%\\Code\\User\\mcp.json on Windows', () => {
  1715. const t = getTarget('copilot-vscode')!;
  1716. // setHome() points APPDATA at <home>/.config.
  1717. const expected = path.join(process.env.APPDATA!, 'Code', 'User', 'mcp.json');
  1718. expect(t.describePaths('global')).toEqual([expected]);
  1719. const result = t.install('global', { autoAllow: true });
  1720. expect(result.files[0].path).toBe(expected);
  1721. });
  1722. it('copilot-vscode: supports both global and local locations', () => {
  1723. const t = getTarget('copilot-vscode')!;
  1724. expect(t.supportsLocation('global')).toBe(true);
  1725. expect(t.supportsLocation('local')).toBe(true);
  1726. });
  1727. it('copilot-vscode: preserves comments and sibling servers through install + idempotent re-run (JSONC)', () => {
  1728. const t = getTarget('copilot-vscode')!;
  1729. const dir = path.join(tmpCwd, '.vscode');
  1730. fs.mkdirSync(dir, { recursive: true });
  1731. const file = path.join(dir, 'mcp.json');
  1732. fs.writeFileSync(file, [
  1733. '{',
  1734. ' // my MCP servers',
  1735. ' "servers": {',
  1736. ' "other": { "type": "stdio", "command": "other-server" } // keep',
  1737. ' }',
  1738. '}',
  1739. '',
  1740. ].join('\n'));
  1741. t.install('local', { autoAllow: true });
  1742. const afterInstall = fs.readFileSync(file, 'utf-8');
  1743. expect(afterInstall).toContain('// my MCP servers');
  1744. expect(afterInstall).toContain('// keep');
  1745. expect(afterInstall).toContain('"other-server"');
  1746. expect(afterInstall).toContain('"codegraph"');
  1747. const second = t.install('local', { autoAllow: true });
  1748. expect(second.files[0].action).toBe('unchanged');
  1749. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  1750. });
  1751. it('copilot-vscode: uninstall drops an emptied servers wrapper but keeps the file and its siblings (e.g. inputs)', () => {
  1752. const t = getTarget('copilot-vscode')!;
  1753. const dir = path.join(tmpCwd, '.vscode');
  1754. fs.mkdirSync(dir, { recursive: true });
  1755. const file = path.join(dir, 'mcp.json');
  1756. fs.writeFileSync(file, [
  1757. '{',
  1758. ' // prompt-time inputs',
  1759. ' "inputs": [{ "id": "api-key", "type": "promptString" }]',
  1760. '}',
  1761. '',
  1762. ].join('\n'));
  1763. t.install('local', { autoAllow: true });
  1764. const result = t.uninstall('local');
  1765. expect(result.files[0].action).toBe('removed');
  1766. // File survives; our entry and the now-empty `servers` wrapper are gone.
  1767. expect(fs.existsSync(file)).toBe(true);
  1768. const text = fs.readFileSync(file, 'utf-8');
  1769. expect(text).toContain('// prompt-time inputs');
  1770. const cfg = parseJsonc(text);
  1771. expect(cfg.inputs).toBeDefined();
  1772. expect(cfg.servers).toBeUndefined();
  1773. expect(text).not.toContain('codegraph');
  1774. });
  1775. it('copilot-vscode: uninstall keeps a non-empty servers wrapper (sibling server survives)', () => {
  1776. const t = getTarget('copilot-vscode')!;
  1777. const file = path.join(tmpCwd, '.vscode', 'mcp.json');
  1778. fs.mkdirSync(path.dirname(file), { recursive: true });
  1779. fs.writeFileSync(file, JSON.stringify({
  1780. servers: { other: { type: 'stdio', command: 'other-server' } },
  1781. }, null, 2) + '\n');
  1782. t.install('local', { autoAllow: true });
  1783. t.uninstall('local');
  1784. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1785. expect(cfg.servers.other).toBeDefined();
  1786. expect(cfg.servers.codegraph).toBeUndefined();
  1787. });
  1788. it('copilot-vscode: uninstall when never installed reports not-found for both locations, no throw', () => {
  1789. const t = getTarget('copilot-vscode')!;
  1790. for (const loc of ['global', 'local'] as const) {
  1791. const result = t.uninstall(loc);
  1792. expect(result.files).toHaveLength(1);
  1793. expect(result.files[0].action).toBe('not-found');
  1794. }
  1795. });
  1796. it('copilot-vscode: detect() local reports installed only when a .vscode dir exists', () => {
  1797. const t = getTarget('copilot-vscode')!;
  1798. expect(t.detect('local').installed).toBe(false);
  1799. fs.mkdirSync(path.join(tmpCwd, '.vscode'), { recursive: true });
  1800. expect(t.detect('local').installed).toBe(true);
  1801. expect(t.detect('local').alreadyConfigured).toBe(false);
  1802. });
  1803. it('copilot-vscode: detect() global falls back to ~/.vscode (extensions dir) as the installed heuristic', () => {
  1804. const t = getTarget('copilot-vscode')!;
  1805. expect(t.detect('global').installed).toBe(false);
  1806. fs.mkdirSync(path.join(tmpHome, '.vscode'), { recursive: true });
  1807. expect(t.detect('global').installed).toBe(true);
  1808. });
  1809. it('copilot-vscode: printConfig matches what install writes, at both locations', () => {
  1810. const t = getTarget('copilot-vscode')!;
  1811. for (const loc of ['global', 'local'] as const) {
  1812. const printed = snippetJson(t.printConfig(loc));
  1813. const result = t.install(loc, { autoAllow: true });
  1814. const onDisk = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  1815. expect(printed.servers.codegraph).toEqual(onDisk.servers.codegraph);
  1816. }
  1817. });
  1818. it('copilot-vscode: install note tells the user to restart VS Code', () => {
  1819. const t = getTarget('copilot-vscode')!;
  1820. const result = t.install('local', { autoAllow: true });
  1821. expect(result.notes?.join(' ')).toMatch(/[Rr]estart VS Code/);
  1822. });
  1823. it('copilot-vscode: global install warns that ${workspaceFolder} needs an open folder; local does not', () => {
  1824. const t = getTarget('copilot-vscode')!;
  1825. // VS Code refuses to start a user-level server whose entry uses
  1826. // ${workspaceFolder} when no folder is open — surface that up front.
  1827. const globalNotes = t.install('global', { autoAllow: true }).notes?.join(' ');
  1828. expect(globalNotes).toMatch(/open a folder/i);
  1829. const localNotes = t.install('local', { autoAllow: true }).notes?.join(' ');
  1830. expect(localNotes).not.toMatch(/open a folder/i);
  1831. });
  1832. // ---- copilot-cli ----
  1833. it('copilot-cli: global install writes ~/.copilot/mcp-config.json with the documented entry shape (tools: ["*"])', () => {
  1834. const t = getTarget('copilot-cli')!;
  1835. const result = t.install('global', { autoAllow: true });
  1836. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1837. expect(result.files[0].path).toBe(file);
  1838. expect(result.files[0].action).toBe('created');
  1839. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1840. expect(cfg.mcpServers.codegraph).toEqual({
  1841. type: 'stdio',
  1842. command: 'codegraph',
  1843. args: ['serve', '--mcp'],
  1844. tools: ['*'],
  1845. });
  1846. });
  1847. it('copilot-cli: is global-only — local install skips with a clear note, uninstall is a no-op', () => {
  1848. const t = getTarget('copilot-cli')!;
  1849. expect(t.supportsLocation('local')).toBe(false);
  1850. expect(t.supportsLocation('global')).toBe(true);
  1851. const install = t.install('local', { autoAllow: true });
  1852. expect(install.files).toEqual([]);
  1853. expect(install.notes?.join(' ')).toMatch(/no project-local config/);
  1854. expect(t.uninstall('local').files).toEqual([]);
  1855. expect(t.describePaths('local')).toEqual([]);
  1856. expect(t.detect('local').installed).toBe(false);
  1857. });
  1858. it('copilot-cli: honors the COPILOT_HOME override for install, detect, and uninstall', () => {
  1859. const t = getTarget('copilot-cli')!;
  1860. const custom = path.join(tmpHome, 'copilot-custom');
  1861. process.env.COPILOT_HOME = custom;
  1862. const result = t.install('global', { autoAllow: true });
  1863. const expected = path.join(custom, 'mcp-config.json');
  1864. expect(result.files[0].path).toBe(expected);
  1865. expect(fs.existsSync(expected)).toBe(true);
  1866. expect(t.detect('global').alreadyConfigured).toBe(true);
  1867. // The default location was never touched.
  1868. expect(fs.existsSync(path.join(tmpHome, '.copilot'))).toBe(false);
  1869. t.uninstall('global');
  1870. expect(t.detect('global').alreadyConfigured).toBe(false);
  1871. });
  1872. it('copilot-cli: uninstall removes only codegraph — sibling server and unrelated keys survive', () => {
  1873. const t = getTarget('copilot-cli')!;
  1874. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1875. fs.mkdirSync(path.dirname(file), { recursive: true });
  1876. fs.writeFileSync(file, JSON.stringify({
  1877. mcpServers: { other: { type: 'stdio', command: 'other-server' } },
  1878. banner: 'never',
  1879. }, null, 2) + '\n');
  1880. t.install('global', { autoAllow: true });
  1881. t.uninstall('global');
  1882. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1883. expect(after.mcpServers.other).toBeDefined();
  1884. expect(after.mcpServers.codegraph).toBeUndefined();
  1885. expect(after.banner).toBe('never');
  1886. });
  1887. it('copilot-cli: uninstall of a from-scratch install deletes the file — no `{}` husk to fool detect()', () => {
  1888. const t = getTarget('copilot-cli')!;
  1889. t.install('global', { autoAllow: true });
  1890. t.uninstall('global');
  1891. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1892. // A leftover empty mcp-config.json would count as a CLI footprint
  1893. // and keep the target showing as detected after uninstall.
  1894. expect(fs.existsSync(file)).toBe(false);
  1895. });
  1896. it('copilot-cli: uninstall keeps the file when unrelated top-level keys remain', () => {
  1897. const t = getTarget('copilot-cli')!;
  1898. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1899. fs.mkdirSync(path.dirname(file), { recursive: true });
  1900. fs.writeFileSync(file, JSON.stringify({ banner: 'never' }, null, 2) + '\n');
  1901. t.install('global', { autoAllow: true });
  1902. t.uninstall('global');
  1903. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1904. expect(after.mcpServers).toBeUndefined();
  1905. expect(after.banner).toBe('never');
  1906. });
  1907. it('copilot-cli: uninstall when never installed reports not-found, no throw', () => {
  1908. const t = getTarget('copilot-cli')!;
  1909. const result = t.uninstall('global');
  1910. expect(result.files).toHaveLength(1);
  1911. expect(result.files[0].action).toBe('not-found');
  1912. // Same when the file exists but holds no codegraph entry.
  1913. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1914. fs.mkdirSync(path.dirname(file), { recursive: true });
  1915. fs.writeFileSync(file, JSON.stringify({ mcpServers: { other: { command: 'x' } } }) + '\n');
  1916. expect(t.uninstall('global').files[0].action).toBe('not-found');
  1917. });
  1918. it('copilot-cli: detect() reports installed from CLI artifacts in ~/.copilot', () => {
  1919. const t = getTarget('copilot-cli')!;
  1920. // The tmp PATH may or may not carry a real `copilot` binary; only
  1921. // assert the positive signal we control. The CLI writes config.json
  1922. // on first run — that's the footprint.
  1923. fs.mkdirSync(path.join(tmpHome, '.copilot'), { recursive: true });
  1924. fs.writeFileSync(path.join(tmpHome, '.copilot', 'config.json'), '{}');
  1925. expect(t.detect('global').installed).toBe(true);
  1926. expect(t.detect('global').alreadyConfigured).toBe(false);
  1927. });
  1928. it('copilot-cli: detect() is NOT fooled by the VS Code extension\'s ~/.copilot/ide/ locks', () => {
  1929. // The VS Code Copilot Chat extension writes MCP socket-handoff lock
  1930. // files into ~/.copilot/ide/ on every launch — a machine with only
  1931. // the extension has ~/.copilot with a lone `ide` entry and no CLI.
  1932. const t = getTarget('copilot-cli')!;
  1933. const ideDir = path.join(tmpHome, '.copilot', 'ide');
  1934. fs.mkdirSync(ideDir, { recursive: true });
  1935. fs.writeFileSync(path.join(ideDir, 'some-uuid.lock'), '{"socketPath":"/tmp/mcp.sock"}');
  1936. // Pin PATH to an empty dir so a real `copilot` binary on the host
  1937. // can't turn this negative assertion into a false failure.
  1938. const prevPath = process.env.PATH;
  1939. process.env.PATH = ideDir;
  1940. try {
  1941. expect(t.detect('global').installed).toBe(false);
  1942. // An empty ~/.copilot (no CLI footprint at all) is also not enough.
  1943. fs.rmSync(ideDir, { recursive: true });
  1944. expect(t.detect('global').installed).toBe(false);
  1945. } finally {
  1946. process.env.PATH = prevPath;
  1947. }
  1948. });
  1949. it('copilot-cli: printConfig matches what install writes; local variant points at --location=global', () => {
  1950. const t = getTarget('copilot-cli')!;
  1951. const printed = snippetJson(t.printConfig('global'));
  1952. const result = t.install('global', { autoAllow: true });
  1953. const onDisk = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  1954. expect(printed.mcpServers.codegraph).toEqual(onDisk.mcpServers.codegraph);
  1955. expect(t.printConfig('local')).toMatch(/--location=global/);
  1956. });
  1957. // ---- copilot-jetbrains ----
  1958. it('copilot-jetbrains: global install writes github-copilot/intellij/mcp.json with the VS Code-compatible servers shape', () => {
  1959. const t = getTarget('copilot-jetbrains')!;
  1960. const result = t.install('global', { autoAllow: true });
  1961. // setHome() sets XDG_CONFIG_HOME, honored on every platform.
  1962. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  1963. expect(result.files[0].path).toBe(file);
  1964. expect(result.files[0].action).toBe('created');
  1965. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1966. // Plain entry — no --path injection for this user-global config.
  1967. expect(cfg.servers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  1968. expect(cfg.mcpServers).toBeUndefined();
  1969. });
  1970. it.runIf(process.platform !== 'win32')('copilot-jetbrains: falls back to ~/.config/github-copilot when XDG_CONFIG_HOME is unset', () => {
  1971. delete process.env.XDG_CONFIG_HOME;
  1972. const t = getTarget('copilot-jetbrains')!;
  1973. const expected = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  1974. expect(t.describePaths('global')).toEqual([expected]);
  1975. const result = t.install('global', { autoAllow: true });
  1976. expect(result.files[0].path).toBe(expected);
  1977. });
  1978. it.runIf(process.platform === 'win32')('copilot-jetbrains: falls back to %LOCALAPPDATA%\\github-copilot on Windows when XDG_CONFIG_HOME is unset', () => {
  1979. const prevLocal = process.env.LOCALAPPDATA;
  1980. delete process.env.XDG_CONFIG_HOME;
  1981. process.env.LOCALAPPDATA = path.join(tmpHome, 'AppData', 'Local');
  1982. try {
  1983. const t = getTarget('copilot-jetbrains')!;
  1984. const expected = path.join(tmpHome, 'AppData', 'Local', 'github-copilot', 'intellij', 'mcp.json');
  1985. expect(t.describePaths('global')).toEqual([expected]);
  1986. const result = t.install('global', { autoAllow: true });
  1987. expect(result.files[0].path).toBe(expected);
  1988. } finally {
  1989. if (prevLocal === undefined) delete process.env.LOCALAPPDATA;
  1990. else process.env.LOCALAPPDATA = prevLocal;
  1991. }
  1992. });
  1993. it('copilot-jetbrains: is global-only — local install skips with a clear note, uninstall is a no-op', () => {
  1994. const t = getTarget('copilot-jetbrains')!;
  1995. expect(t.supportsLocation('local')).toBe(false);
  1996. expect(t.supportsLocation('global')).toBe(true);
  1997. const install = t.install('local', { autoAllow: true });
  1998. expect(install.files).toEqual([]);
  1999. expect(install.notes?.join(' ')).toMatch(/no project-local MCP config/);
  2000. expect(t.uninstall('local').files).toEqual([]);
  2001. expect(t.describePaths('local')).toEqual([]);
  2002. expect(t.detect('local').installed).toBe(false);
  2003. });
  2004. it('copilot-jetbrains: preserves comments and sibling servers through install + idempotent re-run (JSONC)', () => {
  2005. const t = getTarget('copilot-jetbrains')!;
  2006. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2007. fs.mkdirSync(path.dirname(file), { recursive: true });
  2008. fs.writeFileSync(file, [
  2009. '{',
  2010. ' // hand-edited via Settings → Tools → GitHub Copilot',
  2011. ' "servers": {',
  2012. ' "other": { "type": "stdio", "command": "other-server" }',
  2013. ' }',
  2014. '}',
  2015. '',
  2016. ].join('\n'));
  2017. t.install('global', { autoAllow: true });
  2018. const afterInstall = fs.readFileSync(file, 'utf-8');
  2019. expect(afterInstall).toContain('// hand-edited via Settings');
  2020. expect(afterInstall).toContain('"other-server"');
  2021. expect(afterInstall).toContain('"codegraph"');
  2022. const second = t.install('global', { autoAllow: true });
  2023. expect(second.files[0].action).toBe('unchanged');
  2024. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  2025. });
  2026. it('copilot-jetbrains: uninstall removes only codegraph and drops an emptied servers wrapper, keeping the file', () => {
  2027. const t = getTarget('copilot-jetbrains')!;
  2028. t.install('global', { autoAllow: true });
  2029. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2030. const result = t.uninstall('global');
  2031. expect(result.files[0].action).toBe('removed');
  2032. expect(fs.existsSync(file)).toBe(true);
  2033. const cfg = parseJsonc(fs.readFileSync(file, 'utf-8'));
  2034. expect(cfg.servers).toBeUndefined();
  2035. });
  2036. it('copilot-jetbrains: uninstall keeps a sibling server (wrapper not dropped when non-empty)', () => {
  2037. const t = getTarget('copilot-jetbrains')!;
  2038. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2039. fs.mkdirSync(path.dirname(file), { recursive: true });
  2040. fs.writeFileSync(file, JSON.stringify({
  2041. servers: { other: { type: 'stdio', command: 'other-server' } },
  2042. }, null, 2) + '\n');
  2043. t.install('global', { autoAllow: true });
  2044. t.uninstall('global');
  2045. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  2046. expect(cfg.servers.other).toBeDefined();
  2047. expect(cfg.servers.codegraph).toBeUndefined();
  2048. });
  2049. it('copilot-jetbrains: uninstall when never installed reports not-found, no throw', () => {
  2050. const t = getTarget('copilot-jetbrains')!;
  2051. const result = t.uninstall('global');
  2052. expect(result.files).toHaveLength(1);
  2053. expect(result.files[0].action).toBe('not-found');
  2054. });
  2055. it('copilot-jetbrains: detect() reports installed from the intellij config dir', () => {
  2056. const t = getTarget('copilot-jetbrains')!;
  2057. expect(t.detect('global').installed).toBe(false);
  2058. fs.mkdirSync(path.join(tmpHome, '.config', 'github-copilot', 'intellij'), { recursive: true });
  2059. expect(t.detect('global').installed).toBe(true);
  2060. expect(t.detect('global').alreadyConfigured).toBe(false);
  2061. });
  2062. it('copilot-jetbrains: printConfig matches what install writes and names the IDE settings path', () => {
  2063. const t = getTarget('copilot-jetbrains')!;
  2064. const out = t.printConfig('global');
  2065. expect(out).toContain('Settings → Tools → GitHub Copilot');
  2066. const printed = snippetJson(out);
  2067. const result = t.install('global', { autoAllow: true });
  2068. const onDisk = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  2069. expect(printed.servers.codegraph).toEqual(onDisk.servers.codegraph);
  2070. expect(t.printConfig('local')).toMatch(/--location=global/);
  2071. });
  2072. it('copilot-jetbrains: install note tells the user to restart the IDE', () => {
  2073. const t = getTarget('copilot-jetbrains')!;
  2074. const result = t.install('global', { autoAllow: true });
  2075. expect(result.notes?.join(' ')).toMatch(/[Rr]estart your JetBrains IDE/);
  2076. });
  2077. it('copilot family: all three coexist — uninstalling one leaves the others configured', () => {
  2078. const vscode = getTarget('copilot-vscode')!;
  2079. const cli = getTarget('copilot-cli')!;
  2080. const jetbrains = getTarget('copilot-jetbrains')!;
  2081. vscode.install('global', { autoAllow: true });
  2082. cli.install('global', { autoAllow: true });
  2083. jetbrains.install('global', { autoAllow: true });
  2084. cli.uninstall('global');
  2085. expect(cli.detect('global').alreadyConfigured).toBe(false);
  2086. expect(vscode.detect('global').alreadyConfigured).toBe(true);
  2087. expect(jetbrains.detect('global').alreadyConfigured).toBe(true);
  2088. });
  2089. });