installer-targets.test.ts 113 KB

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