installer-targets.test.ts 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447
  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. // Platform-aware since #1466: Windows writes `codegraph.cmd prompt-hook`
  1006. // (Git Bash applies no PATHEXT, so the bare form is exit 127 there), and
  1007. // install self-heals the other platform's spelling in place.
  1008. const HOOK_CMD = process.platform === 'win32' ? 'codegraph.cmd prompt-hook' : 'codegraph prompt-hook';
  1009. const OTHER_PLATFORM_HOOK_CMD = process.platform === 'win32' ? 'codegraph prompt-hook' : 'codegraph.cmd prompt-hook';
  1010. const promptCommands = (s: any): string[] =>
  1011. (s.hooks?.UserPromptSubmit ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  1012. it('claude: install with promptHook:true writes the UserPromptSubmit hook (alongside permissions)', () => {
  1013. const claude = getTarget('claude')!;
  1014. claude.install('global', { autoAllow: true, promptHook: true });
  1015. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1016. expect(promptCommands(s)).toContain(HOOK_CMD);
  1017. expect(s.permissions?.allow).toContain('mcp__codegraph__*');
  1018. });
  1019. it('claude: install without promptHook does NOT add the hook', () => {
  1020. const claude = getTarget('claude')!;
  1021. claude.install('global', { autoAllow: true });
  1022. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1023. expect(promptCommands(s)).not.toContain(HOOK_CMD);
  1024. });
  1025. it('claude: install with promptHook:true is idempotent (no duplicate, byte-identical re-run)', () => {
  1026. const claude = getTarget('claude')!;
  1027. const file = path.join(tmpHome, '.claude', 'settings.json');
  1028. claude.install('global', { autoAllow: true, promptHook: true });
  1029. const first = fs.readFileSync(file, 'utf-8');
  1030. claude.install('global', { autoAllow: true, promptHook: true });
  1031. expect(fs.readFileSync(file, 'utf-8')).toBe(first);
  1032. const s = JSON.parse(first);
  1033. expect(promptCommands(s).filter((c: string) => c === HOOK_CMD)).toHaveLength(1);
  1034. });
  1035. it('claude: install with promptHook:false strips a hook a prior install wrote (opt-out round-trips)', () => {
  1036. const claude = getTarget('claude')!;
  1037. claude.install('global', { autoAllow: true, promptHook: true });
  1038. claude.install('global', { autoAllow: true, promptHook: false });
  1039. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1040. expect(promptCommands(s)).not.toContain(HOOK_CMD);
  1041. });
  1042. it('claude: writePromptHookEntry preserves a sibling UserPromptSubmit hook', () => {
  1043. const file = seedSettings('global', {
  1044. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'my-own-hook' }] }] },
  1045. });
  1046. expect(writePromptHookEntry('global').action).toBe('updated');
  1047. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1048. expect(promptCommands(s)).toEqual(['my-own-hook', HOOK_CMD]);
  1049. });
  1050. it('claude: writePromptHookEntry migrates the other platform\'s spelling in place (#1466 self-heal)', () => {
  1051. const file = seedSettings('global', {
  1052. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: OTHER_PLATFORM_HOOK_CMD }] }] },
  1053. });
  1054. expect(writePromptHookEntry('global').action).toBe('updated');
  1055. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1056. expect(promptCommands(s)).toEqual([HOOK_CMD]);
  1057. // A re-run after migration is byte-identical.
  1058. const healed = fs.readFileSync(file, 'utf-8');
  1059. expect(writePromptHookEntry('global').action).toBe('unchanged');
  1060. expect(fs.readFileSync(file, 'utf-8')).toBe(healed);
  1061. });
  1062. it('claude: writePromptHookEntry leaves an npx-form hook untouched (no duplicate, no rewrite)', () => {
  1063. const npxCmd = 'npx @colbymchenry/codegraph prompt-hook';
  1064. const file = seedSettings('global', {
  1065. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: npxCmd }] }] },
  1066. });
  1067. expect(writePromptHookEntry('global').action).toBe('unchanged');
  1068. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1069. expect(promptCommands(s)).toEqual([npxCmd]);
  1070. });
  1071. it('claude: uninstall removes the prompt hook but keeps the user\'s sibling', () => {
  1072. const file = seedSettings('global', {
  1073. hooks: {
  1074. UserPromptSubmit: [
  1075. { hooks: [{ type: 'command', command: HOOK_CMD }] },
  1076. { hooks: [{ type: 'command', command: 'my-own-hook' }] },
  1077. ],
  1078. },
  1079. });
  1080. getTarget('claude')!.uninstall('global');
  1081. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1082. expect(promptCommands(s)).toEqual(['my-own-hook']);
  1083. });
  1084. it('claude: removePromptHookEntry removes the other platform\'s spelling too', () => {
  1085. const file = seedSettings('global', {
  1086. hooks: {
  1087. UserPromptSubmit: [{ hooks: [{ type: 'command', command: OTHER_PLATFORM_HOOK_CMD }] }],
  1088. },
  1089. });
  1090. expect(removePromptHookEntry('global').action).toBe('removed');
  1091. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1092. expect(promptCommands(s)).toEqual([]);
  1093. });
  1094. it('claude: removePromptHookEntry leaves the legacy auto-sync hook untouched', () => {
  1095. const file = seedSettings('global', {
  1096. hooks: {
  1097. UserPromptSubmit: [{ hooks: [{ type: 'command', command: HOOK_CMD }] }],
  1098. Stop: [{ hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] }],
  1099. },
  1100. });
  1101. expect(removePromptHookEntry('global').action).toBe('removed');
  1102. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1103. expect(promptCommands(s)).not.toContain(HOOK_CMD);
  1104. const stopCmds = (s.hooks?.Stop ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  1105. expect(stopCmds).toContain('codegraph sync-if-dirty');
  1106. });
  1107. });
  1108. describe('Installer targets — registry', () => {
  1109. it('getTarget returns the right target for each id', () => {
  1110. expect(getTarget('claude')?.id).toBe('claude');
  1111. expect(getTarget('cursor')?.id).toBe('cursor');
  1112. expect(getTarget('codex')?.id).toBe('codex');
  1113. expect(getTarget('opencode')?.id).toBe('opencode');
  1114. expect(getTarget('hermes')?.id).toBe('hermes');
  1115. expect(getTarget('gemini')?.id).toBe('gemini');
  1116. expect(getTarget('antigravity')?.id).toBe('antigravity');
  1117. expect(getTarget('kiro')?.id).toBe('kiro');
  1118. expect(getTarget('copilot-vscode')?.id).toBe('copilot-vscode');
  1119. expect(getTarget('copilot-cli')?.id).toBe('copilot-cli');
  1120. expect(getTarget('copilot-jetbrains')?.id).toBe('copilot-jetbrains');
  1121. expect(getTarget('not-a-real-target')).toBeUndefined();
  1122. });
  1123. it('resolveTargetFlag handles auto/all/none/csv', () => {
  1124. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  1125. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  1126. const csv = resolveTargetFlag('claude,cursor', 'global');
  1127. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  1128. });
  1129. it("resolveTargetFlag('all') includes every Copilot target", () => {
  1130. const ids = resolveTargetFlag('all', 'global').map((t) => t.id);
  1131. expect(ids).toContain('copilot-vscode');
  1132. expect(ids).toContain('copilot-cli');
  1133. expect(ids).toContain('copilot-jetbrains');
  1134. });
  1135. it('resolveTargetFlag resolves the Copilot ids from a csv list', () => {
  1136. const csv = resolveTargetFlag('copilot-vscode,copilot-cli,copilot-jetbrains', 'global');
  1137. expect(csv.map((t) => t.id)).toEqual(['copilot-vscode', 'copilot-cli', 'copilot-jetbrains']);
  1138. });
  1139. it('resolveTargetFlag throws on unknown id', () => {
  1140. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  1141. });
  1142. });
  1143. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  1144. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  1145. const block = buildTomlTable('mcp_servers.codegraph', {
  1146. command: 'codegraph',
  1147. args: ['serve', '--mcp'],
  1148. });
  1149. expect(block).toContain('[mcp_servers.codegraph]');
  1150. expect(block).toContain('command = "codegraph"');
  1151. expect(block).toContain('args = ["serve", "--mcp"]');
  1152. });
  1153. it('upsert inserts into empty content', () => {
  1154. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1155. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1156. expect(action).toBe('inserted');
  1157. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  1158. });
  1159. it('upsert is idempotent — second call returns unchanged', () => {
  1160. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1161. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1162. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  1163. expect(second.action).toBe('unchanged');
  1164. expect(second.content).toBe(first.content);
  1165. });
  1166. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  1167. const existing = [
  1168. '[other_table]',
  1169. 'foo = "bar"',
  1170. '',
  1171. '[mcp_servers.codegraph]',
  1172. 'command = "old-codegraph"',
  1173. 'args = ["old"]',
  1174. '',
  1175. '[zzz]',
  1176. 'baz = "qux"',
  1177. '',
  1178. ].join('\n');
  1179. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  1180. command: 'codegraph',
  1181. args: ['serve', '--mcp'],
  1182. });
  1183. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  1184. expect(action).toBe('replaced');
  1185. expect(content).toContain('[other_table]');
  1186. expect(content).toContain('foo = "bar"');
  1187. expect(content).toContain('[zzz]');
  1188. expect(content).toContain('baz = "qux"');
  1189. expect(content).toContain('command = "codegraph"');
  1190. expect(content).not.toContain('old-codegraph');
  1191. });
  1192. it('removeTomlTable strips the block and preserves siblings', () => {
  1193. const existing = [
  1194. '[other_table]',
  1195. 'foo = "bar"',
  1196. '',
  1197. '[mcp_servers.codegraph]',
  1198. 'command = "codegraph"',
  1199. 'args = ["serve"]',
  1200. ].join('\n');
  1201. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1202. expect(action).toBe('removed');
  1203. expect(content).toContain('[other_table]');
  1204. expect(content).toContain('foo = "bar"');
  1205. expect(content).not.toContain('mcp_servers.codegraph');
  1206. });
  1207. it('removeTomlTable on missing table returns not-found, no content change', () => {
  1208. const existing = '[other]\nfoo = "bar"\n';
  1209. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1210. expect(action).toBe('not-found');
  1211. expect(content).toBe(existing);
  1212. });
  1213. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  1214. const existing = [
  1215. '[[foo]]',
  1216. 'name = "a"',
  1217. '',
  1218. '[[foo]]',
  1219. 'name = "b"',
  1220. '',
  1221. ].join('\n');
  1222. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1223. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1224. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  1225. expect(content).toContain('[mcp_servers.codegraph]');
  1226. });
  1227. it('upsert replaces the managed table without consuming trailing array-of-tables siblings', () => {
  1228. const historyTables = [
  1229. '[[history]]',
  1230. 'id = 1',
  1231. 'note = "keep first"',
  1232. '',
  1233. '[[history]]',
  1234. 'id = 2',
  1235. 'note = "keep second"',
  1236. '',
  1237. ].join('\n');
  1238. const existing = [
  1239. '[mcp_servers.codegraph]',
  1240. 'command = "old-codegraph"',
  1241. 'args = ["old"]',
  1242. '',
  1243. historyTables,
  1244. ].join('\n');
  1245. const block = buildTomlTable('mcp_servers.codegraph', {
  1246. command: 'codegraph',
  1247. args: ['serve', '--mcp'],
  1248. });
  1249. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1250. expect(action).toBe('replaced');
  1251. expect(content).toBe(`${block}\n\n${historyTables}`);
  1252. });
  1253. it('remove preserves trailing array-of-tables siblings byte-for-byte', () => {
  1254. const historyTables = [
  1255. '[[history]]',
  1256. 'id = 1',
  1257. 'note = "keep first"',
  1258. '',
  1259. '[[history]]',
  1260. 'id = 2',
  1261. 'note = "keep second"',
  1262. '',
  1263. ].join('\n');
  1264. const existing = [
  1265. '[mcp_servers.codegraph]',
  1266. 'command = "codegraph"',
  1267. 'args = ["serve", "--mcp"]',
  1268. '',
  1269. historyTables,
  1270. ].join('\n');
  1271. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1272. expect(action).toBe('removed');
  1273. expect(content).toBe(historyTables);
  1274. });
  1275. it.each([
  1276. ['table', '[ mcp_servers.other ]'],
  1277. ['array-of-tables', '[[ history ]]'],
  1278. ])('preserves a trailing %s header with inner whitespace', (_kind, siblingHeader) => {
  1279. const siblingTable = `${siblingHeader}\nvalue = "keep"\n`;
  1280. const existing = [
  1281. '[mcp_servers.codegraph]',
  1282. 'command = "old-codegraph"',
  1283. 'args = ["old"]',
  1284. '',
  1285. siblingTable,
  1286. ].join('\n');
  1287. const block = buildTomlTable('mcp_servers.codegraph', {
  1288. command: 'codegraph',
  1289. args: ['serve', '--mcp'],
  1290. });
  1291. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1292. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1293. expect(upserted.content).toBe(`${block}\n\n${siblingTable}`);
  1294. expect(removed.content).toBe(siblingTable);
  1295. });
  1296. it.each([
  1297. ['basic', '"""'],
  1298. ['literal', "'''"],
  1299. ])('ignores header-shaped text inside a multiline %s string', (_kind, delimiter) => {
  1300. const historyTable = '[[history]]\nid = 1\n';
  1301. const existing = [
  1302. '[mcp_servers.codegraph]',
  1303. 'command = "old-codegraph"',
  1304. 'args = [',
  1305. ` ${delimiter}first line`,
  1306. '[[not-a-table]]',
  1307. `last line${delimiter},`,
  1308. ' "serve",',
  1309. ']',
  1310. '',
  1311. historyTable,
  1312. ].join('\n');
  1313. const block = buildTomlTable('mcp_servers.codegraph', {
  1314. command: 'codegraph',
  1315. args: ['serve', '--mcp'],
  1316. });
  1317. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1318. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1319. expect(upserted.content).toBe(`${block}\n\n${historyTable}`);
  1320. expect(removed.content).toBe(historyTable);
  1321. });
  1322. });
  1323. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  1324. let tmpHome: string;
  1325. let tmpCwd: string;
  1326. let origCwd: string;
  1327. let homeRestore: { restore: () => void };
  1328. beforeEach(() => {
  1329. tmpHome = mkTmpDir('un-home');
  1330. tmpCwd = mkTmpDir('un-cwd');
  1331. origCwd = process.cwd();
  1332. process.chdir(tmpCwd);
  1333. homeRestore = setHome(tmpHome);
  1334. });
  1335. afterEach(() => {
  1336. homeRestore.restore();
  1337. process.chdir(origCwd);
  1338. fs.rmSync(tmpHome, { recursive: true, force: true });
  1339. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1340. });
  1341. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  1342. for (const t of ALL_TARGETS) {
  1343. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1344. }
  1345. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1346. for (const t of ALL_TARGETS) {
  1347. const r = reports.find((x) => x.id === t.id)!;
  1348. expect(r.status).toBe('removed');
  1349. expect(r.removedPaths.length).toBeGreaterThan(0);
  1350. // The actual config is gone afterward.
  1351. expect(t.detect('global').alreadyConfigured).toBe(false);
  1352. }
  1353. });
  1354. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  1355. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1356. for (const r of reports) {
  1357. expect(r.status).toBe('not-configured');
  1358. expect(r.removedPaths).toEqual([]);
  1359. }
  1360. });
  1361. it('reports removed only for agents that were actually configured', () => {
  1362. // Install on Claude only; the rest stay untouched.
  1363. getTarget('claude')!.install('global', { autoAllow: true });
  1364. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1365. const claude = reports.find((r) => r.id === 'claude')!;
  1366. expect(claude.status).toBe('removed');
  1367. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  1368. for (const r of reports.filter((x) => x.id !== 'claude')) {
  1369. expect(r.status).toBe('not-configured');
  1370. }
  1371. });
  1372. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  1373. const reports = uninstallTargets(ALL_TARGETS, 'local');
  1374. for (const t of ALL_TARGETS) {
  1375. const r = reports.find((x) => x.id === t.id)!;
  1376. if (t.supportsLocation('local')) {
  1377. expect(r.status).toBe('not-configured');
  1378. } else {
  1379. expect(r.status).toBe('unsupported');
  1380. expect(r.removedPaths).toEqual([]);
  1381. expect(r.notes[0]).toMatch(/global-only/);
  1382. }
  1383. }
  1384. });
  1385. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1386. for (const t of ALL_TARGETS) {
  1387. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1388. }
  1389. const first = uninstallTargets(ALL_TARGETS, 'global');
  1390. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1391. const second = uninstallTargets(ALL_TARGETS, 'global');
  1392. for (const r of second) {
  1393. expect(r.status).toBe('not-configured');
  1394. expect(r.removedPaths).toEqual([]);
  1395. }
  1396. });
  1397. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1398. getTarget('claude')!.install('global', { autoAllow: true });
  1399. getTarget('cursor')!.install('global', { autoAllow: true });
  1400. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1401. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1402. expect(reports[0].status).toBe('removed');
  1403. // Cursor was not in the subset — still configured.
  1404. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1405. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1406. });
  1407. });
  1408. describe('Installer — refreshTargets sweep (codegraph install --refresh)', () => {
  1409. let tmpHome: string;
  1410. let tmpCwd: string;
  1411. let origCwd: string;
  1412. let homeRestore: { restore: () => void };
  1413. beforeEach(() => {
  1414. tmpHome = mkTmpDir('rf-home');
  1415. tmpCwd = mkTmpDir('rf-cwd');
  1416. origCwd = process.cwd();
  1417. process.chdir(tmpCwd);
  1418. homeRestore = setHome(tmpHome);
  1419. });
  1420. afterEach(() => {
  1421. homeRestore.restore();
  1422. process.chdir(origCwd);
  1423. fs.rmSync(tmpHome, { recursive: true, force: true });
  1424. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1425. });
  1426. it('rewrites a stale instructions block a previous version left, and reports refreshed', () => {
  1427. const claude = getTarget('claude')!;
  1428. claude.install('global', { autoAllow: true });
  1429. // Simulate the file as an old install left it: same markers, the old
  1430. // multi-tool wording.
  1431. const claudeMd = path.join(tmpHome, '.claude', 'CLAUDE.md');
  1432. fs.writeFileSync(claudeMd, LEGACY_BLOCK + '\n');
  1433. const reports = refreshTargets([claude], 'global');
  1434. expect(reports[0].status).toBe('refreshed');
  1435. expect(reports[0].changedPaths).toContain(claudeMd);
  1436. const md = fs.readFileSync(claudeMd, 'utf-8');
  1437. expect(md).not.toContain('codegraph_search');
  1438. expect(md).toContain('codegraph_explore');
  1439. });
  1440. it('never performs a first install — unconfigured agents stay untouched', () => {
  1441. const reports = refreshTargets(ALL_TARGETS, 'global');
  1442. for (const t of ALL_TARGETS) {
  1443. const r = reports.find((x) => x.id === t.id)!;
  1444. expect(r.status).toBe(t.supportsLocation('global') ? 'not-configured' : 'unsupported');
  1445. expect(r.changedPaths).toEqual([]);
  1446. expect(t.detect('global').alreadyConfigured).toBe(false);
  1447. }
  1448. });
  1449. it('preserves the user\'s permission choices (refresh never writes permissions)', () => {
  1450. const claude = getTarget('claude')!;
  1451. claude.install('global', { autoAllow: true });
  1452. // The user has since trimmed the allowlist by hand.
  1453. const settingsPath = path.join(tmpHome, '.claude', 'settings.json');
  1454. const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1455. settings.permissions.allow = [];
  1456. fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
  1457. refreshTargets([claude], 'global');
  1458. const after = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1459. expect(after.permissions.allow).toEqual([]);
  1460. });
  1461. it('is idempotent — a second sweep on a current machine reports unchanged everywhere', () => {
  1462. for (const t of ALL_TARGETS) {
  1463. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1464. }
  1465. const first = refreshTargets(ALL_TARGETS, 'global');
  1466. // Fresh installs are already current, so even the first sweep may be
  1467. // all-unchanged; what matters is the second definitely is.
  1468. const second = refreshTargets(ALL_TARGETS, 'global');
  1469. for (const r of [...first, ...second]) {
  1470. expect(['unchanged', 'refreshed']).toContain(r.status);
  1471. }
  1472. for (const r of second) {
  1473. expect(r.status).toBe('unchanged');
  1474. expect(r.changedPaths).toEqual([]);
  1475. }
  1476. });
  1477. });
  1478. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1479. let tmpHome: string;
  1480. let tmpCwd: string;
  1481. let origCwd: string;
  1482. let homeRestore: { restore: () => void };
  1483. const cursor = getTarget('cursor')!;
  1484. beforeEach(() => {
  1485. tmpHome = mkTmpDir('cur-home');
  1486. tmpCwd = mkTmpDir('cur-cwd');
  1487. origCwd = process.cwd();
  1488. process.chdir(tmpCwd);
  1489. homeRestore = setHome(tmpHome);
  1490. });
  1491. afterEach(() => {
  1492. homeRestore.restore();
  1493. process.chdir(origCwd);
  1494. fs.rmSync(tmpHome, { recursive: true, force: true });
  1495. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1496. });
  1497. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1498. // The frontmatter a previous install wrote ahead of the marked block.
  1499. // `removeRulesEntry` recognizes it to decide whether the leftover .mdc
  1500. // is ours-to-delete or carries user content worth keeping.
  1501. const MDC_FRONTMATTER = [
  1502. '---',
  1503. 'description: CodeGraph MCP usage guide — when to use which tool',
  1504. 'alwaysApply: true',
  1505. '---',
  1506. '',
  1507. ].join('\n');
  1508. function plantLegacyRulesFile(extra = ''): void {
  1509. fs.mkdirSync(path.dirname(rulesFile()), { recursive: true });
  1510. fs.writeFileSync(rulesFile(), MDC_FRONTMATTER + LEGACY_BLOCK + '\n' + extra);
  1511. }
  1512. it('uninstall deletes a leftover codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1513. plantLegacyRulesFile();
  1514. expect(fs.existsSync(rulesFile())).toBe(true);
  1515. cursor.uninstall('local');
  1516. // The whole file — frontmatter included — is gone, not just the block.
  1517. expect(fs.existsSync(rulesFile())).toBe(false);
  1518. });
  1519. it('install self-heals a leftover codegraph.mdc (#529)', () => {
  1520. plantLegacyRulesFile();
  1521. const result = cursor.install('local', { autoAllow: true });
  1522. expect(fs.existsSync(rulesFile())).toBe(false);
  1523. expect(result.files.some((f) => f.path.endsWith('codegraph.mdc') && f.action === 'removed')).toBe(true);
  1524. });
  1525. it('uninstall preserves user content added outside the codegraph markers (strips only our block)', () => {
  1526. plantLegacyRulesFile('## My own rule\nkeep me\n');
  1527. cursor.uninstall('local');
  1528. expect(fs.existsSync(rulesFile())).toBe(true);
  1529. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1530. expect(after).toContain('keep me');
  1531. // Our tool-usage block is gone.
  1532. expect(after).not.toContain('codegraph_search');
  1533. expect(after).not.toContain('CODEGRAPH_START');
  1534. });
  1535. });
  1536. function listAllFiles(dir: string): string[] {
  1537. if (!fs.existsSync(dir)) return [];
  1538. const out: string[] = [];
  1539. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1540. const full = path.join(dir, entry.name);
  1541. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1542. else out.push(full);
  1543. }
  1544. return out;
  1545. }
  1546. // ---------------------------------------------------------------------------
  1547. // opencode global config path — XDG on every platform (#535)
  1548. //
  1549. // opencode resolves its config dir with `xdg-basedir`: XDG_CONFIG_HOME if
  1550. // set, else ~/.config — on ALL platforms, Windows included. It never reads
  1551. // %APPDATA%; we used to write there on Windows, so opencode never saw the
  1552. // entry. The suite-wide setHome() points APPDATA and XDG_CONFIG_HOME at the
  1553. // SAME directory (which is exactly how this bug stayed invisible), so these
  1554. // tests deliberately split them.
  1555. // ---------------------------------------------------------------------------
  1556. describe('Installer targets — opencode XDG config path (#535)', () => {
  1557. let tmpHome: string;
  1558. let tmpCwd: string;
  1559. let origCwd: string;
  1560. let homeRestore: { restore: () => void };
  1561. let appDataDir: string; // distinct from ~/.config, like real Windows
  1562. beforeEach(() => {
  1563. tmpHome = mkTmpDir('home');
  1564. tmpCwd = mkTmpDir('cwd');
  1565. origCwd = process.cwd();
  1566. process.chdir(tmpCwd);
  1567. homeRestore = setHome(tmpHome);
  1568. appDataDir = path.join(tmpHome, 'AppData', 'Roaming');
  1569. process.env.APPDATA = appDataDir; // realistic split: APPDATA ≠ ~/.config
  1570. delete process.env.XDG_CONFIG_HOME; // default resolution: ~/.config
  1571. });
  1572. afterEach(() => {
  1573. homeRestore.restore();
  1574. process.chdir(origCwd);
  1575. fs.rmSync(tmpHome, { recursive: true, force: true });
  1576. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1577. });
  1578. const xdgConfigFile = () => path.join(tmpHome, '.config', 'opencode', 'opencode.jsonc');
  1579. const legacyDir = () => path.join(appDataDir, 'opencode');
  1580. // NOTE: never match on an 'AppData' substring — on Windows os.tmpdir()
  1581. // itself lives under AppData\Local\Temp, so EVERY harness path contains
  1582. // it. Match on the legacy dir prefix instead.
  1583. const inLegacyDir = (p: string) => path.resolve(p).startsWith(path.resolve(legacyDir()) + path.sep);
  1584. it('global install writes to ~/.config/opencode, never %APPDATA% (#535)', () => {
  1585. const opencode = getTarget('opencode')!;
  1586. const result = opencode.install('global', { autoAllow: true });
  1587. const written = result.files.find((f) => f.path.endsWith('opencode.jsonc'))!;
  1588. expect(written.action).toBe('created');
  1589. expect(path.resolve(written.path)).toBe(path.resolve(xdgConfigFile()));
  1590. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1591. // Nothing of ours may land in the legacy location.
  1592. expect(fs.existsSync(legacyDir())).toBe(false);
  1593. });
  1594. it('greenfield: targets ~/.config/opencode even when the dir does not exist yet (#535)', () => {
  1595. // The rejected fallback design (#670) would send this install to
  1596. // %APPDATA% — where opencode would never find it. opencode creates
  1597. // ~/.config/opencode itself on first run; installing codegraph FIRST
  1598. // must land where opencode will look.
  1599. expect(fs.existsSync(path.join(tmpHome, '.config', 'opencode'))).toBe(false);
  1600. const opencode = getTarget('opencode')!;
  1601. const result = opencode.install('global', { autoAllow: true });
  1602. expect(path.resolve(result.files[0]!.path)).toBe(path.resolve(xdgConfigFile()));
  1603. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1604. expect(fs.existsSync(legacyDir())).toBe(false);
  1605. });
  1606. it('honors XDG_CONFIG_HOME for the global path, like opencode does', () => {
  1607. const custom = path.join(tmpHome, 'xdg-custom');
  1608. process.env.XDG_CONFIG_HOME = custom;
  1609. const opencode = getTarget('opencode')!;
  1610. const result = opencode.install('global', { autoAllow: true });
  1611. expect(path.resolve(result.files[0]!.path))
  1612. .toBe(path.resolve(path.join(custom, 'opencode', 'opencode.jsonc')));
  1613. });
  1614. it('install self-heals a pre-#535 %APPDATA% entry, preserving siblings and comments', () => {
  1615. // A previous codegraph version wrote into %APPDATA%/opencode. The user
  1616. // also has another MCP server and a comment there — those must survive.
  1617. fs.mkdirSync(legacyDir(), { recursive: true });
  1618. fs.writeFileSync(path.join(legacyDir(), 'opencode.jsonc'), [
  1619. '{',
  1620. ' // my servers',
  1621. ' "$schema": "https://opencode.ai/config.json",',
  1622. ' "mcp": {',
  1623. ' "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true },',
  1624. ' "other": { "type": "local", "command": ["other"], "enabled": true }',
  1625. ' }',
  1626. '}',
  1627. '',
  1628. ].join('\n'));
  1629. fs.writeFileSync(path.join(legacyDir(), 'AGENTS.md'), LEGACY_BLOCK + '\n');
  1630. const opencode = getTarget('opencode')!;
  1631. const result = opencode.install('global', { autoAllow: true });
  1632. // New entry in the right place…
  1633. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1634. // …stale entry swept out of the legacy file, siblings + comment intact.
  1635. const legacyText = fs.readFileSync(path.join(legacyDir(), 'opencode.jsonc'), 'utf-8');
  1636. expect(legacyText).not.toContain('codegraph');
  1637. expect(legacyText).toContain('"other"');
  1638. expect(legacyText).toContain('// my servers');
  1639. // …and the legacy AGENTS.md — block-only, so emptied — removed outright
  1640. // (removeMarkedSection unlinks a file it leaves empty).
  1641. expect(fs.existsSync(path.join(legacyDir(), 'AGENTS.md'))).toBe(false);
  1642. // Both cleanups are reported.
  1643. const removed = result.files.filter((f) => f.action === 'removed').map((f) => f.path);
  1644. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('opencode.jsonc'))).toBe(true);
  1645. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('AGENTS.md'))).toBe(true);
  1646. });
  1647. it('uninstall sweeps the legacy %APPDATA% entry too (no prior re-install needed)', () => {
  1648. // A user on the broken version goes straight to `codegraph uninstall`:
  1649. // the only entry that exists is the stale %APPDATA% one.
  1650. fs.mkdirSync(legacyDir(), { recursive: true });
  1651. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1652. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1653. const opencode = getTarget('opencode')!;
  1654. const result = opencode.uninstall('global');
  1655. expect(fs.readFileSync(path.join(legacyDir(), 'opencode.json'), 'utf-8')).not.toContain('codegraph');
  1656. expect(result.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1657. });
  1658. it('install after install sweeps only once — second run reports no legacy changes', () => {
  1659. fs.mkdirSync(legacyDir(), { recursive: true });
  1660. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1661. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1662. const opencode = getTarget('opencode')!;
  1663. const first = opencode.install('global', { autoAllow: true });
  1664. expect(first.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1665. const second = opencode.install('global', { autoAllow: true });
  1666. expect(second.files.some((f) => inLegacyDir(f.path))).toBe(false);
  1667. expect(second.files.find((f) => f.path.endsWith('opencode.jsonc'))!.action).toBe('unchanged');
  1668. });
  1669. it('detects opencode as installed from a legacy-only %APPDATA% dir (so install can heal it)', () => {
  1670. fs.mkdirSync(legacyDir(), { recursive: true });
  1671. const opencode = getTarget('opencode')!;
  1672. expect(opencode.detect('global').installed).toBe(true);
  1673. // But configuration state is read from the REAL path only.
  1674. expect(opencode.detect('global').alreadyConfigured).toBe(false);
  1675. });
  1676. });
  1677. // ---------------------------------------------------------------------------
  1678. // Copilot family — copilot-vscode / copilot-cli / copilot-jetbrains (CG-5)
  1679. //
  1680. // The registry-driven contract suite above covers the shared surface
  1681. // (install/idempotency/sibling/uninstall/printConfig). These pin the
  1682. // target-specific behavior: OS-specific global paths, `--path` injection
  1683. // (copilot-vscode mirrors Cursor), global-only skip semantics (cli +
  1684. // jetbrains, Codex pattern), COPILOT_HOME resolution, JSONC comment
  1685. // preservation, empty-`servers`-wrapper cleanup, and printConfig parity
  1686. // with what install writes.
  1687. // ---------------------------------------------------------------------------
  1688. describe('Installer targets — Copilot family', () => {
  1689. let tmpHome: string;
  1690. let tmpCwd: string;
  1691. let origCwd: string;
  1692. let homeRestore: { restore: () => void };
  1693. beforeEach(() => {
  1694. tmpHome = mkTmpDir('cop-home');
  1695. tmpCwd = mkTmpDir('cop-cwd');
  1696. origCwd = process.cwd();
  1697. process.chdir(tmpCwd);
  1698. homeRestore = setHome(tmpHome);
  1699. });
  1700. afterEach(() => {
  1701. homeRestore.restore();
  1702. process.chdir(origCwd);
  1703. fs.rmSync(tmpHome, { recursive: true, force: true });
  1704. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1705. });
  1706. // printConfig embeds the paste-able snippet after a `# Add to <path>`
  1707. // header — extract and parse just the JSON body.
  1708. function snippetJson(out: string): any {
  1709. const start = out.indexOf('{');
  1710. expect(start).toBeGreaterThanOrEqual(0);
  1711. return JSON.parse(out.slice(start));
  1712. }
  1713. // ---- copilot-vscode ----
  1714. it('copilot-vscode: local install writes ./.vscode/mcp.json with servers.codegraph and an absolute --path pin', () => {
  1715. const t = getTarget('copilot-vscode')!;
  1716. const result = t.install('local', { autoAllow: true });
  1717. const file = path.join(process.cwd(), '.vscode', 'mcp.json');
  1718. expect(result.files[0].path).toBe(file);
  1719. expect(result.files[0].action).toBe('created');
  1720. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1721. expect(cfg.servers.codegraph.type).toBe('stdio');
  1722. expect(cfg.servers.codegraph.command).toBe('codegraph');
  1723. // Cursor-mirror: local installs pin the project with an absolute path.
  1724. expect(cfg.servers.codegraph.args).toEqual(['serve', '--mcp', '--path', process.cwd()]);
  1725. // No mcpServers wrapper — VS Code's mcp.json uses `servers`.
  1726. expect(cfg.mcpServers).toBeUndefined();
  1727. });
  1728. it('copilot-vscode: global install writes a variable-free entry — no --path, no ${workspaceFolder}', () => {
  1729. // VS Code refuses to start a user-level server whose entry uses
  1730. // ${workspaceFolder} in any window with no folder open, toasting
  1731. // "Variable workspaceFolder can not be resolved" (hit live). VS Code
  1732. // documents cwd = workspace folder for stdio servers, and the
  1733. // codegraph server resolves the project from roots/cwd — so the
  1734. // global entry must carry no --path and no variables at all.
  1735. const t = getTarget('copilot-vscode')!;
  1736. const result = t.install('global', { autoAllow: true });
  1737. const cfg = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  1738. expect(cfg.servers.codegraph.args).toEqual(['serve', '--mcp']);
  1739. expect(JSON.stringify(cfg)).not.toContain('${');
  1740. });
  1741. it.runIf(process.platform === 'darwin')('copilot-vscode: global path is ~/Library/Application Support/Code/User/mcp.json on macOS', () => {
  1742. const t = getTarget('copilot-vscode')!;
  1743. const expected = path.join(tmpHome, 'Library', 'Application Support', 'Code', 'User', 'mcp.json');
  1744. expect(t.describePaths('global')).toEqual([expected]);
  1745. const result = t.install('global', { autoAllow: true });
  1746. expect(result.files[0].path).toBe(expected);
  1747. expect(fs.existsSync(expected)).toBe(true);
  1748. });
  1749. it.runIf(process.platform === 'linux')('copilot-vscode: global path honors XDG_CONFIG_HOME on Linux', () => {
  1750. const t = getTarget('copilot-vscode')!;
  1751. // setHome() points XDG_CONFIG_HOME at <home>/.config.
  1752. const expected = path.join(tmpHome, '.config', 'Code', 'User', 'mcp.json');
  1753. expect(t.describePaths('global')).toEqual([expected]);
  1754. const result = t.install('global', { autoAllow: true });
  1755. expect(result.files[0].path).toBe(expected);
  1756. });
  1757. it.runIf(process.platform === 'win32')('copilot-vscode: global path is %APPDATA%\\Code\\User\\mcp.json on Windows', () => {
  1758. const t = getTarget('copilot-vscode')!;
  1759. // setHome() points APPDATA at <home>/.config.
  1760. const expected = path.join(process.env.APPDATA!, 'Code', 'User', 'mcp.json');
  1761. expect(t.describePaths('global')).toEqual([expected]);
  1762. const result = t.install('global', { autoAllow: true });
  1763. expect(result.files[0].path).toBe(expected);
  1764. });
  1765. it('copilot-vscode: supports both global and local locations', () => {
  1766. const t = getTarget('copilot-vscode')!;
  1767. expect(t.supportsLocation('global')).toBe(true);
  1768. expect(t.supportsLocation('local')).toBe(true);
  1769. });
  1770. it('copilot-vscode: preserves comments and sibling servers through install + idempotent re-run (JSONC)', () => {
  1771. const t = getTarget('copilot-vscode')!;
  1772. const dir = path.join(tmpCwd, '.vscode');
  1773. fs.mkdirSync(dir, { recursive: true });
  1774. const file = path.join(dir, 'mcp.json');
  1775. fs.writeFileSync(file, [
  1776. '{',
  1777. ' // my MCP servers',
  1778. ' "servers": {',
  1779. ' "other": { "type": "stdio", "command": "other-server" } // keep',
  1780. ' }',
  1781. '}',
  1782. '',
  1783. ].join('\n'));
  1784. t.install('local', { autoAllow: true });
  1785. const afterInstall = fs.readFileSync(file, 'utf-8');
  1786. expect(afterInstall).toContain('// my MCP servers');
  1787. expect(afterInstall).toContain('// keep');
  1788. expect(afterInstall).toContain('"other-server"');
  1789. expect(afterInstall).toContain('"codegraph"');
  1790. const second = t.install('local', { autoAllow: true });
  1791. expect(second.files[0].action).toBe('unchanged');
  1792. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  1793. });
  1794. it('copilot-vscode: uninstall drops an emptied servers wrapper but keeps the file and its siblings (e.g. inputs)', () => {
  1795. const t = getTarget('copilot-vscode')!;
  1796. const dir = path.join(tmpCwd, '.vscode');
  1797. fs.mkdirSync(dir, { recursive: true });
  1798. const file = path.join(dir, 'mcp.json');
  1799. fs.writeFileSync(file, [
  1800. '{',
  1801. ' // prompt-time inputs',
  1802. ' "inputs": [{ "id": "api-key", "type": "promptString" }]',
  1803. '}',
  1804. '',
  1805. ].join('\n'));
  1806. t.install('local', { autoAllow: true });
  1807. const result = t.uninstall('local');
  1808. expect(result.files[0].action).toBe('removed');
  1809. // File survives; our entry and the now-empty `servers` wrapper are gone.
  1810. expect(fs.existsSync(file)).toBe(true);
  1811. const text = fs.readFileSync(file, 'utf-8');
  1812. expect(text).toContain('// prompt-time inputs');
  1813. const cfg = parseJsonc(text);
  1814. expect(cfg.inputs).toBeDefined();
  1815. expect(cfg.servers).toBeUndefined();
  1816. expect(text).not.toContain('codegraph');
  1817. });
  1818. it('copilot-vscode: uninstall keeps a non-empty servers wrapper (sibling server survives)', () => {
  1819. const t = getTarget('copilot-vscode')!;
  1820. const file = path.join(tmpCwd, '.vscode', 'mcp.json');
  1821. fs.mkdirSync(path.dirname(file), { recursive: true });
  1822. fs.writeFileSync(file, JSON.stringify({
  1823. servers: { other: { type: 'stdio', command: 'other-server' } },
  1824. }, null, 2) + '\n');
  1825. t.install('local', { autoAllow: true });
  1826. t.uninstall('local');
  1827. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1828. expect(cfg.servers.other).toBeDefined();
  1829. expect(cfg.servers.codegraph).toBeUndefined();
  1830. });
  1831. it('copilot-vscode: uninstall when never installed reports not-found for both locations, no throw', () => {
  1832. const t = getTarget('copilot-vscode')!;
  1833. for (const loc of ['global', 'local'] as const) {
  1834. const result = t.uninstall(loc);
  1835. expect(result.files).toHaveLength(1);
  1836. expect(result.files[0].action).toBe('not-found');
  1837. }
  1838. });
  1839. it('copilot-vscode: detect() local reports installed only when a .vscode dir exists', () => {
  1840. const t = getTarget('copilot-vscode')!;
  1841. expect(t.detect('local').installed).toBe(false);
  1842. fs.mkdirSync(path.join(tmpCwd, '.vscode'), { recursive: true });
  1843. expect(t.detect('local').installed).toBe(true);
  1844. expect(t.detect('local').alreadyConfigured).toBe(false);
  1845. });
  1846. it('copilot-vscode: detect() global falls back to ~/.vscode (extensions dir) as the installed heuristic', () => {
  1847. const t = getTarget('copilot-vscode')!;
  1848. expect(t.detect('global').installed).toBe(false);
  1849. fs.mkdirSync(path.join(tmpHome, '.vscode'), { recursive: true });
  1850. expect(t.detect('global').installed).toBe(true);
  1851. });
  1852. it('copilot-vscode: printConfig matches what install writes, at both locations', () => {
  1853. const t = getTarget('copilot-vscode')!;
  1854. for (const loc of ['global', 'local'] as const) {
  1855. const printed = snippetJson(t.printConfig(loc));
  1856. const result = t.install(loc, { autoAllow: true });
  1857. const onDisk = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  1858. expect(printed.servers.codegraph).toEqual(onDisk.servers.codegraph);
  1859. }
  1860. });
  1861. it('copilot-vscode: install note tells the user to restart VS Code', () => {
  1862. const t = getTarget('copilot-vscode')!;
  1863. const result = t.install('local', { autoAllow: true });
  1864. expect(result.notes?.join(' ')).toMatch(/[Rr]estart VS Code/);
  1865. });
  1866. // ---- copilot-cli ----
  1867. it('copilot-cli: global install writes ~/.copilot/mcp-config.json with the documented entry shape (tools: ["*"])', () => {
  1868. const t = getTarget('copilot-cli')!;
  1869. const result = t.install('global', { autoAllow: true });
  1870. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1871. expect(result.files[0].path).toBe(file);
  1872. expect(result.files[0].action).toBe('created');
  1873. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1874. expect(cfg.mcpServers.codegraph).toEqual({
  1875. type: 'stdio',
  1876. command: 'codegraph',
  1877. args: ['serve', '--mcp'],
  1878. tools: ['*'],
  1879. });
  1880. });
  1881. it('copilot-cli: is global-only — local install skips with a clear note, uninstall is a no-op', () => {
  1882. const t = getTarget('copilot-cli')!;
  1883. expect(t.supportsLocation('local')).toBe(false);
  1884. expect(t.supportsLocation('global')).toBe(true);
  1885. const install = t.install('local', { autoAllow: true });
  1886. expect(install.files).toEqual([]);
  1887. expect(install.notes?.join(' ')).toMatch(/no project-local config/);
  1888. expect(t.uninstall('local').files).toEqual([]);
  1889. expect(t.describePaths('local')).toEqual([]);
  1890. expect(t.detect('local').installed).toBe(false);
  1891. });
  1892. it('copilot-cli: honors the COPILOT_HOME override for install, detect, and uninstall', () => {
  1893. const t = getTarget('copilot-cli')!;
  1894. const custom = path.join(tmpHome, 'copilot-custom');
  1895. process.env.COPILOT_HOME = custom;
  1896. const result = t.install('global', { autoAllow: true });
  1897. const expected = path.join(custom, 'mcp-config.json');
  1898. expect(result.files[0].path).toBe(expected);
  1899. expect(fs.existsSync(expected)).toBe(true);
  1900. expect(t.detect('global').alreadyConfigured).toBe(true);
  1901. // The default location was never touched.
  1902. expect(fs.existsSync(path.join(tmpHome, '.copilot'))).toBe(false);
  1903. t.uninstall('global');
  1904. expect(t.detect('global').alreadyConfigured).toBe(false);
  1905. });
  1906. it('copilot-cli: uninstall removes only codegraph — sibling server and unrelated keys survive', () => {
  1907. const t = getTarget('copilot-cli')!;
  1908. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1909. fs.mkdirSync(path.dirname(file), { recursive: true });
  1910. fs.writeFileSync(file, JSON.stringify({
  1911. mcpServers: { other: { type: 'stdio', command: 'other-server' } },
  1912. banner: 'never',
  1913. }, null, 2) + '\n');
  1914. t.install('global', { autoAllow: true });
  1915. t.uninstall('global');
  1916. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1917. expect(after.mcpServers.other).toBeDefined();
  1918. expect(after.mcpServers.codegraph).toBeUndefined();
  1919. expect(after.banner).toBe('never');
  1920. });
  1921. it('copilot-cli: uninstall of a from-scratch install deletes the file — no `{}` husk to fool detect()', () => {
  1922. const t = getTarget('copilot-cli')!;
  1923. t.install('global', { autoAllow: true });
  1924. t.uninstall('global');
  1925. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1926. // A leftover empty mcp-config.json would count as a CLI footprint
  1927. // and keep the target showing as detected after uninstall.
  1928. expect(fs.existsSync(file)).toBe(false);
  1929. });
  1930. it('copilot-cli: uninstall keeps the file when unrelated top-level keys remain', () => {
  1931. const t = getTarget('copilot-cli')!;
  1932. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1933. fs.mkdirSync(path.dirname(file), { recursive: true });
  1934. fs.writeFileSync(file, JSON.stringify({ banner: 'never' }, null, 2) + '\n');
  1935. t.install('global', { autoAllow: true });
  1936. t.uninstall('global');
  1937. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1938. expect(after.mcpServers).toBeUndefined();
  1939. expect(after.banner).toBe('never');
  1940. });
  1941. it('copilot-cli: uninstall when never installed reports not-found, no throw', () => {
  1942. const t = getTarget('copilot-cli')!;
  1943. const result = t.uninstall('global');
  1944. expect(result.files).toHaveLength(1);
  1945. expect(result.files[0].action).toBe('not-found');
  1946. // Same when the file exists but holds no codegraph entry.
  1947. const file = path.join(tmpHome, '.copilot', 'mcp-config.json');
  1948. fs.mkdirSync(path.dirname(file), { recursive: true });
  1949. fs.writeFileSync(file, JSON.stringify({ mcpServers: { other: { command: 'x' } } }) + '\n');
  1950. expect(t.uninstall('global').files[0].action).toBe('not-found');
  1951. });
  1952. it('copilot-cli: detect() reports installed from CLI artifacts in ~/.copilot', () => {
  1953. const t = getTarget('copilot-cli')!;
  1954. // The tmp PATH may or may not carry a real `copilot` binary; only
  1955. // assert the positive signal we control. The CLI writes config.json
  1956. // on first run — that's the footprint.
  1957. fs.mkdirSync(path.join(tmpHome, '.copilot'), { recursive: true });
  1958. fs.writeFileSync(path.join(tmpHome, '.copilot', 'config.json'), '{}');
  1959. expect(t.detect('global').installed).toBe(true);
  1960. expect(t.detect('global').alreadyConfigured).toBe(false);
  1961. });
  1962. it('copilot-cli: detect() is NOT fooled by the VS Code extension\'s ~/.copilot/ide/ locks', () => {
  1963. // The VS Code Copilot Chat extension writes MCP socket-handoff lock
  1964. // files into ~/.copilot/ide/ on every launch — a machine with only
  1965. // the extension has ~/.copilot with a lone `ide` entry and no CLI.
  1966. const t = getTarget('copilot-cli')!;
  1967. const ideDir = path.join(tmpHome, '.copilot', 'ide');
  1968. fs.mkdirSync(ideDir, { recursive: true });
  1969. fs.writeFileSync(path.join(ideDir, 'some-uuid.lock'), '{"socketPath":"/tmp/mcp.sock"}');
  1970. // Pin PATH to an empty dir so a real `copilot` binary on the host
  1971. // can't turn this negative assertion into a false failure.
  1972. const prevPath = process.env.PATH;
  1973. process.env.PATH = ideDir;
  1974. try {
  1975. expect(t.detect('global').installed).toBe(false);
  1976. // An empty ~/.copilot (no CLI footprint at all) is also not enough.
  1977. fs.rmSync(ideDir, { recursive: true });
  1978. expect(t.detect('global').installed).toBe(false);
  1979. } finally {
  1980. process.env.PATH = prevPath;
  1981. }
  1982. });
  1983. it('copilot-cli: printConfig matches what install writes; local variant points at --location=global', () => {
  1984. const t = getTarget('copilot-cli')!;
  1985. const printed = snippetJson(t.printConfig('global'));
  1986. const result = t.install('global', { autoAllow: true });
  1987. const onDisk = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  1988. expect(printed.mcpServers.codegraph).toEqual(onDisk.mcpServers.codegraph);
  1989. expect(t.printConfig('local')).toMatch(/--location=global/);
  1990. });
  1991. // ---- copilot-jetbrains ----
  1992. it('copilot-jetbrains: global install writes github-copilot/intellij/mcp.json with the VS Code-compatible servers shape', () => {
  1993. const t = getTarget('copilot-jetbrains')!;
  1994. const result = t.install('global', { autoAllow: true });
  1995. // setHome() sets XDG_CONFIG_HOME, honored on every platform.
  1996. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  1997. expect(result.files[0].path).toBe(file);
  1998. expect(result.files[0].action).toBe('created');
  1999. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  2000. // Plain entry — no --path injection for this user-global config.
  2001. expect(cfg.servers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  2002. expect(cfg.mcpServers).toBeUndefined();
  2003. });
  2004. it.runIf(process.platform !== 'win32')('copilot-jetbrains: falls back to ~/.config/github-copilot when XDG_CONFIG_HOME is unset', () => {
  2005. delete process.env.XDG_CONFIG_HOME;
  2006. const t = getTarget('copilot-jetbrains')!;
  2007. const expected = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2008. expect(t.describePaths('global')).toEqual([expected]);
  2009. const result = t.install('global', { autoAllow: true });
  2010. expect(result.files[0].path).toBe(expected);
  2011. });
  2012. it.runIf(process.platform === 'win32')('copilot-jetbrains: falls back to %LOCALAPPDATA%\\github-copilot on Windows when XDG_CONFIG_HOME is unset', () => {
  2013. const prevLocal = process.env.LOCALAPPDATA;
  2014. delete process.env.XDG_CONFIG_HOME;
  2015. process.env.LOCALAPPDATA = path.join(tmpHome, 'AppData', 'Local');
  2016. try {
  2017. const t = getTarget('copilot-jetbrains')!;
  2018. const expected = path.join(tmpHome, 'AppData', 'Local', 'github-copilot', 'intellij', 'mcp.json');
  2019. expect(t.describePaths('global')).toEqual([expected]);
  2020. const result = t.install('global', { autoAllow: true });
  2021. expect(result.files[0].path).toBe(expected);
  2022. } finally {
  2023. if (prevLocal === undefined) delete process.env.LOCALAPPDATA;
  2024. else process.env.LOCALAPPDATA = prevLocal;
  2025. }
  2026. });
  2027. it('copilot-jetbrains: is global-only — local install skips with a clear note, uninstall is a no-op', () => {
  2028. const t = getTarget('copilot-jetbrains')!;
  2029. expect(t.supportsLocation('local')).toBe(false);
  2030. expect(t.supportsLocation('global')).toBe(true);
  2031. const install = t.install('local', { autoAllow: true });
  2032. expect(install.files).toEqual([]);
  2033. expect(install.notes?.join(' ')).toMatch(/no project-local MCP config/);
  2034. expect(t.uninstall('local').files).toEqual([]);
  2035. expect(t.describePaths('local')).toEqual([]);
  2036. expect(t.detect('local').installed).toBe(false);
  2037. });
  2038. it('copilot-jetbrains: preserves comments and sibling servers through install + idempotent re-run (JSONC)', () => {
  2039. const t = getTarget('copilot-jetbrains')!;
  2040. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2041. fs.mkdirSync(path.dirname(file), { recursive: true });
  2042. fs.writeFileSync(file, [
  2043. '{',
  2044. ' // hand-edited via Settings → Tools → GitHub Copilot',
  2045. ' "servers": {',
  2046. ' "other": { "type": "stdio", "command": "other-server" }',
  2047. ' }',
  2048. '}',
  2049. '',
  2050. ].join('\n'));
  2051. t.install('global', { autoAllow: true });
  2052. const afterInstall = fs.readFileSync(file, 'utf-8');
  2053. expect(afterInstall).toContain('// hand-edited via Settings');
  2054. expect(afterInstall).toContain('"other-server"');
  2055. expect(afterInstall).toContain('"codegraph"');
  2056. const second = t.install('global', { autoAllow: true });
  2057. expect(second.files[0].action).toBe('unchanged');
  2058. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  2059. });
  2060. it('copilot-jetbrains: uninstall removes only codegraph and drops an emptied servers wrapper, keeping the file', () => {
  2061. const t = getTarget('copilot-jetbrains')!;
  2062. t.install('global', { autoAllow: true });
  2063. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2064. const result = t.uninstall('global');
  2065. expect(result.files[0].action).toBe('removed');
  2066. expect(fs.existsSync(file)).toBe(true);
  2067. const cfg = parseJsonc(fs.readFileSync(file, 'utf-8'));
  2068. expect(cfg.servers).toBeUndefined();
  2069. });
  2070. it('copilot-jetbrains: uninstall keeps a sibling server (wrapper not dropped when non-empty)', () => {
  2071. const t = getTarget('copilot-jetbrains')!;
  2072. const file = path.join(tmpHome, '.config', 'github-copilot', 'intellij', 'mcp.json');
  2073. fs.mkdirSync(path.dirname(file), { recursive: true });
  2074. fs.writeFileSync(file, JSON.stringify({
  2075. servers: { other: { type: 'stdio', command: 'other-server' } },
  2076. }, null, 2) + '\n');
  2077. t.install('global', { autoAllow: true });
  2078. t.uninstall('global');
  2079. const cfg = JSON.parse(fs.readFileSync(file, 'utf-8'));
  2080. expect(cfg.servers.other).toBeDefined();
  2081. expect(cfg.servers.codegraph).toBeUndefined();
  2082. });
  2083. it('copilot-jetbrains: uninstall when never installed reports not-found, no throw', () => {
  2084. const t = getTarget('copilot-jetbrains')!;
  2085. const result = t.uninstall('global');
  2086. expect(result.files).toHaveLength(1);
  2087. expect(result.files[0].action).toBe('not-found');
  2088. });
  2089. it('copilot-jetbrains: detect() reports installed from the intellij config dir', () => {
  2090. const t = getTarget('copilot-jetbrains')!;
  2091. expect(t.detect('global').installed).toBe(false);
  2092. fs.mkdirSync(path.join(tmpHome, '.config', 'github-copilot', 'intellij'), { recursive: true });
  2093. expect(t.detect('global').installed).toBe(true);
  2094. expect(t.detect('global').alreadyConfigured).toBe(false);
  2095. });
  2096. it('copilot-jetbrains: printConfig matches what install writes and names the IDE settings path', () => {
  2097. const t = getTarget('copilot-jetbrains')!;
  2098. const out = t.printConfig('global');
  2099. expect(out).toContain('Settings → Tools → GitHub Copilot');
  2100. const printed = snippetJson(out);
  2101. const result = t.install('global', { autoAllow: true });
  2102. const onDisk = JSON.parse(fs.readFileSync(result.files[0].path, 'utf-8'));
  2103. expect(printed.servers.codegraph).toEqual(onDisk.servers.codegraph);
  2104. expect(t.printConfig('local')).toMatch(/--location=global/);
  2105. });
  2106. it('copilot-jetbrains: install note tells the user to restart the IDE', () => {
  2107. const t = getTarget('copilot-jetbrains')!;
  2108. const result = t.install('global', { autoAllow: true });
  2109. expect(result.notes?.join(' ')).toMatch(/[Rr]estart your JetBrains IDE/);
  2110. });
  2111. it('copilot family: all three coexist — uninstalling one leaves the others configured', () => {
  2112. const vscode = getTarget('copilot-vscode')!;
  2113. const cli = getTarget('copilot-cli')!;
  2114. const jetbrains = getTarget('copilot-jetbrains')!;
  2115. vscode.install('global', { autoAllow: true });
  2116. cli.install('global', { autoAllow: true });
  2117. jetbrains.install('global', { autoAllow: true });
  2118. cli.uninstall('global');
  2119. expect(cli.detect('global').alreadyConfigured).toBe(false);
  2120. expect(vscode.detect('global').alreadyConfigured).toBe(true);
  2121. expect(jetbrains.detect('global').alreadyConfigured).toBe(true);
  2122. });
  2123. });