installer-targets.test.ts 122 KB

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