installer-targets.test.ts 111 KB

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