installer-targets.test.ts 106 KB

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