installer-targets.test.ts 102 KB

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