installer-targets.test.ts 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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 { ALL_TARGETS, getTarget, resolveTargetFlag } from '../src/installer/targets/registry';
  21. import { uninstallTargets, refreshTargets } from '../src/installer';
  22. import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  23. import { cleanupLegacyHooks, writePromptHookEntry, removePromptHookEntry } from '../src/installer/targets/claude';
  24. function mkTmpDir(label: string): string {
  25. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
  26. }
  27. // `os.homedir` is non-configurable on Node, so we redirect it via the
  28. // `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
  29. // `os.homedir()` reads first. Same trick the rest of the suite uses
  30. // when it needs a mock home.
  31. function setHome(dir: string): { restore: () => void } {
  32. const prev = {
  33. HOME: process.env.HOME,
  34. USERPROFILE: process.env.USERPROFILE,
  35. APPDATA: process.env.APPDATA,
  36. XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
  37. HERMES_HOME: process.env.HERMES_HOME,
  38. };
  39. process.env.HOME = dir;
  40. process.env.USERPROFILE = dir;
  41. process.env.APPDATA = path.join(dir, '.config');
  42. process.env.XDG_CONFIG_HOME = path.join(dir, '.config');
  43. delete process.env.HERMES_HOME;
  44. return {
  45. restore() {
  46. if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
  47. if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
  48. if (prev.APPDATA === undefined) delete process.env.APPDATA; else process.env.APPDATA = prev.APPDATA;
  49. if (prev.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = prev.XDG_CONFIG_HOME;
  50. if (prev.HERMES_HOME === undefined) delete process.env.HERMES_HOME; else process.env.HERMES_HOME = prev.HERMES_HOME;
  51. },
  52. };
  53. }
  54. // A marker-delimited CodeGraph block exactly as a previous installer
  55. // wrote it. Issue #529: the installer no longer writes an instructions
  56. // file, but install (self-heal on upgrade) and uninstall both still
  57. // strip a block a prior install left, so we plant this to exercise it.
  58. const LEGACY_BLOCK = [
  59. '<!-- CODEGRAPH_START -->',
  60. '## CodeGraph',
  61. '',
  62. 'Prefer `codegraph_search` / `codegraph_callers` over grep.',
  63. '<!-- CODEGRAPH_END -->',
  64. ].join('\n');
  65. describe('Installer targets — contract', () => {
  66. let tmpHome: string;
  67. let tmpCwd: string;
  68. let origCwd: string;
  69. let homeRestore: { restore: () => void };
  70. beforeEach(() => {
  71. tmpHome = mkTmpDir('home');
  72. tmpCwd = mkTmpDir('cwd');
  73. origCwd = process.cwd();
  74. process.chdir(tmpCwd);
  75. homeRestore = setHome(tmpHome);
  76. });
  77. afterEach(() => {
  78. homeRestore.restore();
  79. process.chdir(origCwd);
  80. fs.rmSync(tmpHome, { recursive: true, force: true });
  81. fs.rmSync(tmpCwd, { recursive: true, force: true });
  82. });
  83. for (const target of ALL_TARGETS) {
  84. describe(target.id, () => {
  85. const supportedLocations = (['global', 'local'] as const).filter((l) =>
  86. target.supportsLocation(l),
  87. );
  88. for (const location of supportedLocations) {
  89. describe(`location=${location}`, () => {
  90. it('install writes files; detect.alreadyConfigured becomes true', () => {
  91. expect(target.detect(location).alreadyConfigured).toBe(false);
  92. const result = target.install(location, { autoAllow: true });
  93. expect(result.files.length).toBeGreaterThan(0);
  94. for (const file of result.files) {
  95. if (file.action !== 'unchanged') {
  96. expect(fs.existsSync(file.path)).toBe(true);
  97. }
  98. }
  99. expect(target.detect(location).alreadyConfigured).toBe(true);
  100. });
  101. it('re-running install is idempotent (no actions other than unchanged)', () => {
  102. target.install(location, { autoAllow: true });
  103. const second = target.install(location, { autoAllow: true });
  104. for (const file of second.files) {
  105. expect(file.action).toBe('unchanged');
  106. }
  107. });
  108. it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
  109. // Plant a sibling entry in the same JSON config, install,
  110. // and verify the sibling survives. Skip for Codex (TOML)
  111. // and any target with no JSON config — they get covered
  112. // by their own dedicated tests below.
  113. const paths = target.describePaths(location);
  114. // Match .json or .jsonc — opencode prefers .jsonc.
  115. const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
  116. if (!jsonPath) return;
  117. // Seed pre-existing config.
  118. fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
  119. const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
  120. // opencode uses `mcp` not `mcpServers`. Match its shape too.
  121. if (target.id === 'opencode') {
  122. delete seed.mcpServers;
  123. seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
  124. }
  125. fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
  126. target.install(location, { autoAllow: true });
  127. const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
  128. if (target.id === 'opencode') {
  129. expect(after.mcp.other).toBeDefined();
  130. expect(after.mcp.codegraph).toBeDefined();
  131. } else {
  132. expect(after.mcpServers.other).toBeDefined();
  133. expect(after.mcpServers.codegraph).toBeDefined();
  134. }
  135. });
  136. it('uninstall reverses install (alreadyConfigured returns to false)', () => {
  137. target.install(location, { autoAllow: true });
  138. expect(target.detect(location).alreadyConfigured).toBe(true);
  139. target.uninstall(location);
  140. expect(target.detect(location).alreadyConfigured).toBe(false);
  141. });
  142. it('printConfig returns non-empty output without writing anything', () => {
  143. const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  144. const out = target.printConfig(location);
  145. expect(out.length).toBeGreaterThan(0);
  146. const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  147. expect(after.sort()).toEqual(before.sort());
  148. });
  149. });
  150. }
  151. });
  152. }
  153. });
  154. describe('Installer targets — partial-state idempotency', () => {
  155. let tmpHome: string;
  156. let tmpCwd: string;
  157. let origCwd: string;
  158. let homeRestore: { restore: () => void };
  159. beforeEach(() => {
  160. tmpHome = mkTmpDir('home');
  161. tmpCwd = mkTmpDir('cwd');
  162. origCwd = process.cwd();
  163. process.chdir(tmpCwd);
  164. homeRestore = setHome(tmpHome);
  165. });
  166. afterEach(() => {
  167. homeRestore.restore();
  168. process.chdir(origCwd);
  169. fs.rmSync(tmpHome, { recursive: true, force: true });
  170. fs.rmSync(tmpCwd, { recursive: true, force: true });
  171. });
  172. it('codex: install writes config.toml AND the AGENTS.md codegraph block (#704)', () => {
  173. const codex = getTarget('codex')!;
  174. const first = codex.install('global', { autoAllow: false });
  175. const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
  176. expect(first.files.some((f) => f.path.endsWith('config.toml'))).toBe(true);
  177. // The short instructions block IS written (subagents / non-MCP
  178. // harnesses read AGENTS.md but never the MCP initialize instructions).
  179. expect(fs.existsSync(agentsMd)).toBe(true);
  180. const body = fs.readFileSync(agentsMd, 'utf-8');
  181. expect(body).toContain('## CodeGraph');
  182. expect(body).toContain('codegraph explore');
  183. // Re-install is fully unchanged (byte-equal block → idempotent).
  184. const second = codex.install('global', { autoAllow: false });
  185. for (const f of second.files) expect(f.action).toBe('unchanged');
  186. });
  187. it('codex: install replaces a legacy AGENTS.md codegraph block with the current one, keeping user content', () => {
  188. const codex = getTarget('codex')!;
  189. const dir = path.join(tmpHome, '.codex');
  190. fs.mkdirSync(dir, { recursive: true });
  191. const agentsMd = path.join(dir, 'AGENTS.md');
  192. fs.writeFileSync(agentsMd, `# My codex notes\n\nBe terse.\n\n${LEGACY_BLOCK}\n`);
  193. const result = codex.install('global', { autoAllow: false });
  194. const body = fs.readFileSync(agentsMd, 'utf-8');
  195. expect(body).toContain('# My codex notes');
  196. expect(body).toContain('Be terse.');
  197. // Self-heal: the stale pre-#529 body is gone, the current block is in.
  198. expect(body).not.toContain('Prefer `codegraph_search`');
  199. expect(body).toContain('codegraph explore');
  200. const mdEntry = result.files.find((f) => f.path.endsWith('AGENTS.md'));
  201. expect(mdEntry?.action).toBe('updated');
  202. });
  203. it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
  204. const opencode = getTarget('opencode')!;
  205. const dir = path.join(tmpHome, '.config', 'opencode');
  206. fs.mkdirSync(dir, { recursive: true });
  207. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  208. fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  209. const result = opencode.install('global', { autoAllow: true });
  210. const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
  211. expect(written).toBeDefined();
  212. expect(written.action).not.toBe('not-found');
  213. // The .json file is left alone.
  214. const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
  215. expect(jsonText).not.toContain('codegraph');
  216. });
  217. it('opencode: uses .json when only .json exists (no .jsonc)', () => {
  218. const opencode = getTarget('opencode')!;
  219. const dir = path.join(tmpHome, '.config', 'opencode');
  220. fs.mkdirSync(dir, { recursive: true });
  221. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  222. const result = opencode.install('global', { autoAllow: true });
  223. expect(result.files[0].path).toMatch(/opencode\.json$/);
  224. expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
  225. });
  226. it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
  227. const opencode = getTarget('opencode')!;
  228. const result = opencode.install('global', { autoAllow: true });
  229. expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
  230. expect(result.files[0].action).toBe('created');
  231. });
  232. it('opencode: preserves line and block comments through install + idempotent re-run', () => {
  233. const opencode = getTarget('opencode')!;
  234. const dir = path.join(tmpHome, '.config', 'opencode');
  235. fs.mkdirSync(dir, { recursive: true });
  236. const file = path.join(dir, 'opencode.jsonc');
  237. const original = [
  238. '{',
  239. ' // top-level note about my opencode setup',
  240. ' "$schema": "https://opencode.ai/config.json",',
  241. ' /* multi-line block comment',
  242. ' describing the providers section */',
  243. ' "providers": {',
  244. ' "anthropic": { "model": "claude-opus-4-7" } // pinned',
  245. ' }',
  246. '}',
  247. '',
  248. ].join('\n');
  249. fs.writeFileSync(file, original);
  250. opencode.install('global', { autoAllow: true });
  251. const afterInstall = fs.readFileSync(file, 'utf-8');
  252. expect(afterInstall).toContain('// top-level note about my opencode setup');
  253. expect(afterInstall).toContain('/* multi-line block comment');
  254. expect(afterInstall).toContain('// pinned');
  255. expect(afterInstall).toContain('"codegraph"');
  256. expect(afterInstall).toContain('"providers"');
  257. // Idempotent re-run reports unchanged, file is byte-identical.
  258. const second = opencode.install('global', { autoAllow: true });
  259. expect(second.files[0].action).toBe('unchanged');
  260. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  261. });
  262. it('opencode: install writes the AGENTS.md codegraph block (#704)', () => {
  263. const opencode = getTarget('opencode')!;
  264. const result = opencode.install('global', { autoAllow: true });
  265. const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
  266. expect(fs.existsSync(agentsMd)).toBe(true);
  267. expect(fs.readFileSync(agentsMd, 'utf-8')).toContain('codegraph explore');
  268. expect(result.files.find((f) => f.path.endsWith('AGENTS.md'))?.action).toBe('created');
  269. });
  270. it('opencode: install replaces a legacy AGENTS.md codegraph block, preserving user content', () => {
  271. const opencode = getTarget('opencode')!;
  272. const dir = path.join(tmpHome, '.config', 'opencode');
  273. fs.mkdirSync(dir, { recursive: true });
  274. const agentsMd = path.join(dir, 'AGENTS.md');
  275. fs.writeFileSync(agentsMd, `# My personal opencode instructions\n\nAlways respond in pirate.\n\n${LEGACY_BLOCK}\n`);
  276. const result = opencode.install('global', { autoAllow: true });
  277. const body = fs.readFileSync(agentsMd, 'utf-8');
  278. expect(body).toContain('# My personal opencode instructions');
  279. expect(body).toContain('Always respond in pirate.');
  280. expect(body).not.toContain('Prefer `codegraph_search`');
  281. expect(body).toContain('codegraph explore');
  282. expect(result.files.find((f) => f.path.endsWith('AGENTS.md'))?.action).toBe('updated');
  283. });
  284. it('opencode: uninstall strips a leftover codegraph block from AGENTS.md, keeping user content', () => {
  285. const opencode = getTarget('opencode')!;
  286. const dir = path.join(tmpHome, '.config', 'opencode');
  287. fs.mkdirSync(dir, { recursive: true });
  288. const agentsMd = path.join(dir, 'AGENTS.md');
  289. fs.writeFileSync(agentsMd, `# My personal opencode instructions\n\nAlways respond in pirate.\n\n${LEGACY_BLOCK}\n`);
  290. opencode.uninstall('global');
  291. const body = fs.readFileSync(agentsMd, 'utf-8');
  292. expect(body).toContain('# My personal opencode instructions');
  293. expect(body).toContain('Always respond in pirate.');
  294. expect(body).not.toContain('CODEGRAPH_START');
  295. });
  296. it('opencode: local install writes ./opencode.jsonc and the ./AGENTS.md block (#704)', () => {
  297. const opencode = getTarget('opencode')!;
  298. const result = opencode.install('local', { autoAllow: true });
  299. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  300. // macOS realpath shenanigans (/var vs /private/var) — suffix match.
  301. expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
  302. expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
  303. expect(fs.existsSync(path.join(process.cwd(), 'AGENTS.md'))).toBe(true);
  304. });
  305. it('gemini: install writes settings.json (mcpServers.codegraph) and the GEMINI.md block (#704)', () => {
  306. const gemini = getTarget('gemini')!;
  307. const result = gemini.install('global', { autoAllow: true });
  308. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  309. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  310. expect(result.files.some((f) => f.path === settings)).toBe(true);
  311. expect(result.files.some((f) => f.path === geminiMd)).toBe(true);
  312. expect(fs.existsSync(geminiMd)).toBe(true);
  313. expect(fs.readFileSync(geminiMd, 'utf-8')).toContain('codegraph explore');
  314. const cfg = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  315. expect(cfg.mcpServers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  316. });
  317. it('gemini: install preserves pre-existing settings (security.auth survives)', () => {
  318. const gemini = getTarget('gemini')!;
  319. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  320. fs.mkdirSync(path.dirname(settings), { recursive: true });
  321. fs.writeFileSync(settings, JSON.stringify({
  322. security: { auth: { selectedType: 'oauth-personal' } },
  323. }, null, 2) + '\n');
  324. gemini.install('global', { autoAllow: true });
  325. const after = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  326. expect(after.security?.auth?.selectedType).toBe('oauth-personal');
  327. expect(after.mcpServers?.codegraph).toBeDefined();
  328. });
  329. it('gemini: uninstall strips codegraph but leaves pre-existing settings (security.auth) intact', () => {
  330. const gemini = getTarget('gemini')!;
  331. const settings = path.join(tmpHome, '.gemini', 'settings.json');
  332. fs.mkdirSync(path.dirname(settings), { recursive: true });
  333. fs.writeFileSync(settings, JSON.stringify({
  334. security: { auth: { selectedType: 'oauth-personal' } },
  335. }, null, 2) + '\n');
  336. gemini.install('global', { autoAllow: true });
  337. gemini.uninstall('global');
  338. const after = JSON.parse(fs.readFileSync(settings, 'utf-8'));
  339. expect(after.security?.auth?.selectedType).toBe('oauth-personal');
  340. expect(after.mcpServers).toBeUndefined();
  341. });
  342. it('gemini: local install writes ./.gemini/settings.json and the project-root ./GEMINI.md block (#704)', () => {
  343. const gemini = getTarget('gemini')!;
  344. const result = gemini.install('local', { autoAllow: true });
  345. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  346. expect(paths.some((p) => p.endsWith('/.gemini/settings.json'))).toBe(true);
  347. expect(paths.some((p) => p.endsWith('/GEMINI.md'))).toBe(true);
  348. expect(fs.existsSync(path.join(process.cwd(), 'GEMINI.md'))).toBe(true);
  349. });
  350. it('gemini: uninstall strips a leftover GEMINI.md codegraph block, keeping user content', () => {
  351. const gemini = getTarget('gemini')!;
  352. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  353. fs.mkdirSync(path.dirname(geminiMd), { recursive: true });
  354. fs.writeFileSync(geminiMd, `# My personal Gemini context\n\nAlways respond concisely.\n\n${LEGACY_BLOCK}\n`);
  355. gemini.uninstall('global');
  356. const body = fs.readFileSync(geminiMd, 'utf-8');
  357. expect(body).toContain('# My personal Gemini context');
  358. expect(body).toContain('Always respond concisely.');
  359. expect(body).not.toContain('CODEGRAPH_START');
  360. });
  361. it('kiro: install writes settings/mcp.json (mcpServers.codegraph) and no steering doc (#529)', () => {
  362. const kiro = getTarget('kiro')!;
  363. const result = kiro.install('global', { autoAllow: true });
  364. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  365. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  366. expect(result.files.some((f) => f.path === mcp)).toBe(true);
  367. expect(result.files.some((f) => f.path === steering)).toBe(false);
  368. expect(fs.existsSync(steering)).toBe(false);
  369. const cfg = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  370. expect(cfg.mcpServers.codegraph).toEqual({ type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] });
  371. });
  372. it('kiro: install deletes a leftover steering codegraph.md (self-heal) (#529)', () => {
  373. const kiro = getTarget('kiro')!;
  374. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  375. fs.mkdirSync(path.dirname(steering), { recursive: true });
  376. fs.writeFileSync(steering, `${LEGACY_BLOCK}\n`);
  377. const result = kiro.install('global', { autoAllow: true });
  378. expect(fs.existsSync(steering)).toBe(false);
  379. expect(result.files.find((f) => f.path === steering)?.action).toBe('removed');
  380. });
  381. it('kiro: install preserves a pre-existing sibling MCP server in mcp.json', () => {
  382. const kiro = getTarget('kiro')!;
  383. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  384. fs.mkdirSync(path.dirname(mcp), { recursive: true });
  385. fs.writeFileSync(mcp, JSON.stringify({
  386. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  387. }, null, 2) + '\n');
  388. kiro.install('global', { autoAllow: true });
  389. const after = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  390. expect(after.mcpServers.other).toBeDefined();
  391. expect(after.mcpServers.codegraph).toBeDefined();
  392. });
  393. it('kiro: uninstall strips codegraph but leaves sibling MCP servers intact', () => {
  394. const kiro = getTarget('kiro')!;
  395. const mcp = path.join(tmpHome, '.kiro', 'settings', 'mcp.json');
  396. fs.mkdirSync(path.dirname(mcp), { recursive: true });
  397. fs.writeFileSync(mcp, JSON.stringify({
  398. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  399. }, null, 2) + '\n');
  400. kiro.install('global', { autoAllow: true });
  401. kiro.uninstall('global');
  402. const after = JSON.parse(fs.readFileSync(mcp, 'utf-8'));
  403. expect(after.mcpServers.other).toBeDefined();
  404. expect(after.mcpServers.codegraph).toBeUndefined();
  405. });
  406. it('kiro: uninstall removes a leftover steering codegraph.md file outright', () => {
  407. const kiro = getTarget('kiro')!;
  408. const steering = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  409. fs.mkdirSync(path.dirname(steering), { recursive: true });
  410. fs.writeFileSync(steering, `${LEGACY_BLOCK}\n`);
  411. kiro.uninstall('global');
  412. expect(fs.existsSync(steering)).toBe(false);
  413. });
  414. it('kiro: uninstall removes our steering doc but leaves a sibling (product.md) untouched', () => {
  415. const kiro = getTarget('kiro')!;
  416. const sibling = path.join(tmpHome, '.kiro', 'steering', 'product.md');
  417. const ours = path.join(tmpHome, '.kiro', 'steering', 'codegraph.md');
  418. fs.mkdirSync(path.dirname(sibling), { recursive: true });
  419. fs.writeFileSync(sibling, '# Product\n\nMy team practices.\n');
  420. fs.writeFileSync(ours, `${LEGACY_BLOCK}\n`);
  421. kiro.uninstall('global');
  422. expect(fs.existsSync(ours)).toBe(false);
  423. expect(fs.existsSync(sibling)).toBe(true);
  424. expect(fs.readFileSync(sibling, 'utf-8')).toContain('My team practices.');
  425. });
  426. it('kiro: local install writes ./.kiro/settings/mcp.json and no steering doc (#529)', () => {
  427. const kiro = getTarget('kiro')!;
  428. const result = kiro.install('local', { autoAllow: true });
  429. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  430. expect(paths.some((p) => p.endsWith('/.kiro/settings/mcp.json'))).toBe(true);
  431. expect(paths.some((p) => p.endsWith('/.kiro/steering/codegraph.md'))).toBe(false);
  432. });
  433. it('antigravity: install writes to LEGACY ~/.gemini/antigravity/mcp_config.json when no migration marker', () => {
  434. const antigravity = getTarget('antigravity')!;
  435. antigravity.install('global', { autoAllow: true });
  436. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  437. expect(fs.existsSync(legacyFile)).toBe(true);
  438. const cfg = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  439. expect(cfg.mcpServers.codegraph).toBeDefined();
  440. // Crucially: does NOT touch the Gemini CLI's settings.json.
  441. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'settings.json'))).toBe(false);
  442. });
  443. it('antigravity: install writes to UNIFIED ~/.gemini/config/mcp_config.json when .migrated marker present', () => {
  444. const antigravity = getTarget('antigravity')!;
  445. // Plant the migration marker — same signal Antigravity itself drops
  446. // when it migrates a user's config.
  447. const unifiedDir = path.join(tmpHome, '.gemini', 'config');
  448. fs.mkdirSync(unifiedDir, { recursive: true });
  449. fs.writeFileSync(path.join(unifiedDir, '.migrated'), '');
  450. antigravity.install('global', { autoAllow: true });
  451. const unifiedFile = path.join(unifiedDir, 'mcp_config.json');
  452. expect(fs.existsSync(unifiedFile)).toBe(true);
  453. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  454. expect(cfg.mcpServers.codegraph).toBeDefined();
  455. // Legacy path is NOT touched when the marker tells us migration happened.
  456. expect(fs.existsSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'))).toBe(false);
  457. });
  458. it('antigravity: install writes to UNIFIED path when ~/.gemini/config/mcp_config.json already exists (even without marker)', () => {
  459. const antigravity = getTarget('antigravity')!;
  460. // Antigravity creates this file on first launch post-migration — its
  461. // presence is the second signal we accept, in case the .migrated
  462. // marker semantics change across Antigravity versions.
  463. const unifiedFile = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  464. fs.mkdirSync(path.dirname(unifiedFile), { recursive: true });
  465. fs.writeFileSync(unifiedFile, JSON.stringify({ mcpServers: {} }, null, 2) + '\n');
  466. antigravity.install('global', { autoAllow: true });
  467. const cfg = JSON.parse(fs.readFileSync(unifiedFile, 'utf-8'));
  468. expect(cfg.mcpServers.codegraph).toBeDefined();
  469. });
  470. it('antigravity: entry has NO `type` field (Antigravity rejects entries with it)', () => {
  471. const antigravity = getTarget('antigravity')!;
  472. // Marker → unified path; doesn't matter which path, just inspect the entry shape.
  473. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  474. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  475. antigravity.install('global', { autoAllow: true });
  476. const cfg = JSON.parse(fs.readFileSync(
  477. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  478. ));
  479. expect(cfg.mcpServers.codegraph.type).toBeUndefined();
  480. expect(cfg.mcpServers.codegraph.command).toBeDefined();
  481. expect(cfg.mcpServers.codegraph.args).toEqual(['serve', '--mcp']);
  482. });
  483. it('antigravity: install migrates a legacy codegraph entry to the unified path when marker appears', () => {
  484. const antigravity = getTarget('antigravity')!;
  485. // Simulate: user installed on the legacy path, then Antigravity
  486. // migrated their config (dropped the `.migrated` marker + created
  487. // the unified file). Re-running codegraph install should land
  488. // codegraph in the new file AND strip the stale legacy entry.
  489. const legacyFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  490. fs.mkdirSync(path.dirname(legacyFile), { recursive: true });
  491. fs.writeFileSync(legacyFile, JSON.stringify({
  492. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  493. }, null, 2) + '\n');
  494. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  495. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  496. antigravity.install('global', { autoAllow: true });
  497. const unified = JSON.parse(fs.readFileSync(
  498. path.join(tmpHome, '.gemini', 'config', 'mcp_config.json'), 'utf-8'
  499. ));
  500. expect(unified.mcpServers.codegraph).toBeDefined();
  501. // Legacy file's codegraph entry got stripped.
  502. const legacy = JSON.parse(fs.readFileSync(legacyFile, 'utf-8'));
  503. expect(legacy.mcpServers).toBeUndefined();
  504. });
  505. it('antigravity: install preserves a sibling MCP server in mcp_config.json (legacy path)', () => {
  506. const antigravity = getTarget('antigravity')!;
  507. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  508. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  509. fs.writeFileSync(mcpFile, JSON.stringify({
  510. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  511. }, null, 2) + '\n');
  512. antigravity.install('global', { autoAllow: true });
  513. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  514. expect(after.mcpServers.other).toBeDefined();
  515. expect(after.mcpServers.codegraph).toBeDefined();
  516. });
  517. it('antigravity: install preserves Antigravity-managed fields on sibling servers (e.g. disabled flag)', () => {
  518. const antigravity = getTarget('antigravity')!;
  519. // Antigravity adds `"disabled": true` to entries the user disables via
  520. // the IDE. Install must not clobber that on sibling entries.
  521. fs.mkdirSync(path.join(tmpHome, '.gemini', 'config'), { recursive: true });
  522. fs.writeFileSync(path.join(tmpHome, '.gemini', 'config', '.migrated'), '');
  523. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  524. fs.writeFileSync(unified, JSON.stringify({
  525. mcpServers: {
  526. 'code-review-graph': {
  527. command: 'uvx', args: ['code-review-graph', 'serve'], disabled: true,
  528. },
  529. },
  530. }, null, 2) + '\n');
  531. antigravity.install('global', { autoAllow: true });
  532. const after = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  533. expect(after.mcpServers['code-review-graph'].disabled).toBe(true);
  534. expect(after.mcpServers.codegraph).toBeDefined();
  535. });
  536. it('antigravity: uninstall removes only codegraph, sibling MCP server survives', () => {
  537. const antigravity = getTarget('antigravity')!;
  538. const mcpFile = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  539. fs.mkdirSync(path.dirname(mcpFile), { recursive: true });
  540. fs.writeFileSync(mcpFile, JSON.stringify({
  541. mcpServers: { other: { command: 'uvx', args: ['other-server'] } },
  542. }, null, 2) + '\n');
  543. antigravity.install('global', { autoAllow: true });
  544. antigravity.uninstall('global');
  545. const after = JSON.parse(fs.readFileSync(mcpFile, 'utf-8'));
  546. expect(after.mcpServers.other).toBeDefined();
  547. expect(after.mcpServers.codegraph).toBeUndefined();
  548. });
  549. it('antigravity: uninstall sweeps BOTH legacy and unified paths (handles migration half-state)', () => {
  550. const antigravity = getTarget('antigravity')!;
  551. // User had codegraph in BOTH files (e.g. legacy install + post-migration
  552. // re-install before our migration cleanup landed). Uninstall must clean
  553. // both so a "fresh slate" really is fresh.
  554. const legacy = path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json');
  555. const unified = path.join(tmpHome, '.gemini', 'config', 'mcp_config.json');
  556. fs.mkdirSync(path.dirname(legacy), { recursive: true });
  557. fs.mkdirSync(path.dirname(unified), { recursive: true });
  558. fs.writeFileSync(legacy, JSON.stringify({
  559. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  560. }, null, 2) + '\n');
  561. fs.writeFileSync(unified, JSON.stringify({
  562. mcpServers: { codegraph: { command: 'codegraph', args: ['serve', '--mcp'] } },
  563. }, null, 2) + '\n');
  564. fs.writeFileSync(path.join(path.dirname(unified), '.migrated'), '');
  565. antigravity.uninstall('global');
  566. const legacyAfter = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  567. const unifiedAfter = JSON.parse(fs.readFileSync(unified, 'utf-8'));
  568. expect(legacyAfter.mcpServers).toBeUndefined();
  569. expect(unifiedAfter.mcpServers).toBeUndefined();
  570. });
  571. it('antigravity: rejects --location=local with a clear note (global-only IDE)', () => {
  572. const antigravity = getTarget('antigravity')!;
  573. expect(antigravity.supportsLocation('local')).toBe(false);
  574. const result = antigravity.install('local', { autoAllow: true });
  575. expect(result.files).toEqual([]);
  576. expect(result.notes?.join(' ')).toMatch(/no project-local config/);
  577. });
  578. it('antigravity: does not write GEMINI.md (only gemini target owns instructions)', () => {
  579. const antigravity = getTarget('antigravity')!;
  580. antigravity.install('global', { autoAllow: true });
  581. const geminiMd = path.join(tmpHome, '.gemini', 'GEMINI.md');
  582. expect(fs.existsSync(geminiMd)).toBe(false);
  583. });
  584. it('gemini + antigravity: both installed coexist (separate MCP files, shared GEMINI.md)', () => {
  585. const gemini = getTarget('gemini')!;
  586. const antigravity = getTarget('antigravity')!;
  587. gemini.install('global', { autoAllow: true });
  588. antigravity.install('global', { autoAllow: true });
  589. const cliCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  590. // Antigravity lands on the LEGACY path here since no .migrated marker
  591. // was planted — same end-to-end check either way.
  592. const ideCfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'antigravity', 'mcp_config.json'), 'utf-8'));
  593. expect(cliCfg.mcpServers.codegraph).toBeDefined();
  594. expect(ideCfg.mcpServers.codegraph).toBeDefined();
  595. // Uninstall one — the other's MCP entry must survive.
  596. antigravity.uninstall('global');
  597. const cliAfter = JSON.parse(fs.readFileSync(path.join(tmpHome, '.gemini', 'settings.json'), 'utf-8'));
  598. expect(cliAfter.mcpServers.codegraph).toBeDefined();
  599. });
  600. it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
  601. const hermes = getTarget('hermes')!;
  602. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  603. fs.mkdirSync(path.dirname(config), { recursive: true });
  604. fs.writeFileSync(config, [
  605. 'model:',
  606. ' default: qwen-3.7',
  607. 'mcp_servers:',
  608. ' other:',
  609. ' command: other',
  610. 'platform_toolsets:',
  611. ' cli:',
  612. ' - hermes-cli',
  613. ' discord:',
  614. ' - hermes-discord',
  615. '',
  616. ].join('\n'));
  617. const result = hermes.install('global', { autoAllow: true });
  618. expect(result.files[0].action).toBe('updated');
  619. const body = fs.readFileSync(config, 'utf-8');
  620. expect(body).toContain('model:\n default: qwen-3.7');
  621. expect(body).toContain('mcp_servers:\n other:\n command: other');
  622. expect(body).toContain(' codegraph:\n command: codegraph');
  623. expect(body).toContain(' - hermes-cli');
  624. expect(body).toContain(' - mcp-codegraph');
  625. expect(body).toContain(' discord:\n - hermes-discord');
  626. const second = hermes.install('global', { autoAllow: true });
  627. expect(second.files[0].action).toBe('unchanged');
  628. });
  629. it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
  630. const hermes = getTarget('hermes')!;
  631. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  632. fs.mkdirSync(path.dirname(config), { recursive: true });
  633. hermes.install('global', { autoAllow: true });
  634. fs.appendFileSync(config, 'custom:\n keep: true\n');
  635. hermes.uninstall('global');
  636. const body = fs.readFileSync(config, 'utf-8');
  637. expect(body).not.toContain('codegraph:');
  638. expect(body).not.toContain('mcp-codegraph');
  639. expect(body).toContain('custom:\n keep: true');
  640. });
  641. // Regression for #456: PyYAML's default block style writes list items at the
  642. // SAME indent as the parent key (`cli:` and its `- hermes-cli` are both at
  643. // indent 2). The pre-fix line-based patcher mistook that first list item for
  644. // the next sibling key, truncated the cli block, and spliced `- mcp-codegraph`
  645. // at indent 4 BEFORE the existing items — producing unparseable YAML.
  646. it('hermes: install preserves PyYAML-default list-at-same-indent style (issue #456)', () => {
  647. const hermes = getTarget('hermes')!;
  648. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  649. fs.mkdirSync(path.dirname(config), { recursive: true });
  650. const original = [
  651. 'model:',
  652. ' default: gpt-4o',
  653. 'platform_toolsets:',
  654. ' cli:',
  655. ' - hermes-cli',
  656. ' - browser',
  657. ' - clarify',
  658. ' - terminal',
  659. ' - web',
  660. ' telegram:',
  661. ' - hermes-telegram',
  662. ' discord:',
  663. ' - hermes-discord',
  664. '',
  665. ].join('\n');
  666. fs.writeFileSync(config, original);
  667. hermes.install('global', { autoAllow: true });
  668. const body = fs.readFileSync(config, 'utf-8');
  669. // mcp-codegraph appended at the same 2-space indent as existing items
  670. expect(body).toContain('\n - mcp-codegraph\n');
  671. // hermes-cli preserved
  672. expect(body).toContain('\n - hermes-cli\n');
  673. // Sibling sections kept their indent — `telegram:` is still a key under
  674. // platform_toolsets, not promoted up.
  675. expect(body).toContain('\n telegram:\n - hermes-telegram\n');
  676. expect(body).toContain('\n discord:\n - hermes-discord\n');
  677. // No list items leaked to the platform_toolsets level (indent 0).
  678. expect(body).not.toMatch(/^- browser/m);
  679. expect(body).not.toMatch(/^- hermes-telegram/m);
  680. // The whole platform_toolsets block extracted by line search should
  681. // start with `cli:` and not contain a stray 4-space `mcp-codegraph`
  682. // appearing before the rest of the existing items.
  683. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  684. // Idempotent
  685. const second = hermes.install('global', { autoAllow: true });
  686. expect(second.files[0]?.action).toBe('unchanged');
  687. });
  688. it('hermes: uninstall reverses the install on a PyYAML-default config', () => {
  689. const hermes = getTarget('hermes')!;
  690. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  691. fs.mkdirSync(path.dirname(config), { recursive: true });
  692. const original = [
  693. 'platform_toolsets:',
  694. ' cli:',
  695. ' - hermes-cli',
  696. ' - browser',
  697. ' telegram:',
  698. ' - hermes-telegram',
  699. '',
  700. ].join('\n');
  701. fs.writeFileSync(config, original);
  702. hermes.install('global', { autoAllow: true });
  703. const installed = fs.readFileSync(config, 'utf-8');
  704. expect(installed).toContain('- mcp-codegraph');
  705. expect(installed).toContain('codegraph:');
  706. hermes.uninstall('global');
  707. const body = fs.readFileSync(config, 'utf-8');
  708. expect(body).not.toContain('mcp-codegraph');
  709. expect(body).not.toContain('command: codegraph');
  710. expect(body).toContain(' cli:\n - hermes-cli\n - browser');
  711. expect(body).toContain(' telegram:\n - hermes-telegram');
  712. });
  713. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  714. const opencode = getTarget('opencode')!;
  715. const dir = path.join(tmpHome, '.config', 'opencode');
  716. fs.mkdirSync(dir, { recursive: true });
  717. const file = path.join(dir, 'opencode.jsonc');
  718. fs.writeFileSync(file, [
  719. '{',
  720. ' // important comment',
  721. ' "$schema": "https://opencode.ai/config.json",',
  722. ' "mcp": {',
  723. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  724. ' }',
  725. '}',
  726. '',
  727. ].join('\n'));
  728. opencode.install('global', { autoAllow: true });
  729. const afterInstall = fs.readFileSync(file, 'utf-8');
  730. expect(afterInstall).toContain('"codegraph"');
  731. expect(afterInstall).toContain('"other"');
  732. opencode.uninstall('global');
  733. const afterUninstall = fs.readFileSync(file, 'utf-8');
  734. expect(afterUninstall).not.toContain('codegraph');
  735. expect(afterUninstall).toContain('// important comment');
  736. expect(afterUninstall).toContain('"other"');
  737. });
  738. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  739. const codex = getTarget('codex')!;
  740. codex.install('global', { autoAllow: false });
  741. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  742. const original = fs.readFileSync(tomlPath, 'utf-8');
  743. // User edits the block to add a custom key.
  744. const edited = original.replace(
  745. 'args = ["serve", "--mcp"]',
  746. 'args = ["serve", "--mcp"]\nenabled = true',
  747. );
  748. fs.writeFileSync(tomlPath, edited);
  749. // Re-install: our serializer doesn't know `enabled = true`, so
  750. // the block no longer matches the canonical form — we'll
  751. // overwrite it. This is the documented contract: we own the
  752. // codegraph block exclusively.
  753. const second = codex.install('global', { autoAllow: false });
  754. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  755. expect(tomlEntry.action).toBe('updated');
  756. const after = fs.readFileSync(tomlPath, 'utf-8');
  757. expect(after).not.toContain('enabled = true');
  758. });
  759. it('codex: install, re-install, and uninstall preserve trailing array-of-tables siblings', () => {
  760. const codex = getTarget('codex')!;
  761. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  762. fs.mkdirSync(path.dirname(tomlPath), { recursive: true });
  763. const historyTables = [
  764. '[[history]]',
  765. 'id = 1',
  766. 'note = "keep first"',
  767. '',
  768. '[[history]]',
  769. 'id = 2',
  770. 'note = "keep second"',
  771. '',
  772. ].join('\n');
  773. fs.writeFileSync(tomlPath, [
  774. '[mcp_servers.codegraph]',
  775. 'command = "old-codegraph"',
  776. 'args = ["old"]',
  777. 'description = """',
  778. 'header-shaped text inside a multiline string:',
  779. '[[not-a-table]]',
  780. 'still part of the string',
  781. '"""',
  782. '',
  783. historyTables,
  784. ].join('\n'));
  785. const first = codex.install('global', { autoAllow: false });
  786. expect(first.files.find((f) => f.path === tomlPath)?.action).toBe('updated');
  787. const afterInstall = fs.readFileSync(tomlPath, 'utf-8');
  788. expect(afterInstall).toContain('command = "codegraph"');
  789. expect(afterInstall).not.toContain('[[not-a-table]]');
  790. expect(afterInstall.endsWith(historyTables)).toBe(true);
  791. const second = codex.install('global', { autoAllow: false });
  792. expect(second.files.find((f) => f.path === tomlPath)?.action).toBe('unchanged');
  793. expect(fs.readFileSync(tomlPath, 'utf-8')).toBe(afterInstall);
  794. codex.uninstall('global');
  795. expect(fs.readFileSync(tomlPath, 'utf-8')).toBe(historyTables);
  796. });
  797. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  798. const claude = getTarget('claude')!;
  799. const result = claude.install('local', { autoAllow: false });
  800. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  801. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  802. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  803. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  804. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  805. expect(cfg.mcpServers.codegraph).toBeDefined();
  806. });
  807. it('claude: install creates the CLAUDE.md codegraph block (#704)', () => {
  808. const claude = getTarget('claude')!;
  809. const result = claude.install('local', { autoAllow: false });
  810. const claudeMd = path.join(tmpCwd, '.claude', 'CLAUDE.md');
  811. expect(fs.existsSync(claudeMd)).toBe(true);
  812. const body = fs.readFileSync(claudeMd, 'utf-8');
  813. expect(body).toContain('## CodeGraph');
  814. expect(body).toContain('codegraph explore');
  815. expect(result.files.find((f) => f.path.endsWith('CLAUDE.md'))?.action).toBe('created');
  816. });
  817. it('claude: install replaces a legacy CLAUDE.md codegraph block, keeping user content', () => {
  818. const claude = getTarget('claude')!;
  819. const claudeMd = path.join(tmpCwd, '.claude', 'CLAUDE.md');
  820. fs.mkdirSync(path.dirname(claudeMd), { recursive: true });
  821. fs.writeFileSync(claudeMd, `# My project rules\n\nUse tabs.\n\n${LEGACY_BLOCK}\n`);
  822. const result = claude.install('local', { autoAllow: false });
  823. const body = fs.readFileSync(claudeMd, 'utf-8');
  824. expect(body).toContain('# My project rules');
  825. expect(body).toContain('Use tabs.');
  826. expect(body).not.toContain('Prefer `codegraph_search`');
  827. expect(body).toContain('codegraph explore');
  828. expect(result.files.find((f) => f.path.endsWith('CLAUDE.md'))?.action).toBe('updated');
  829. });
  830. it('claude: global install targets ~/.claude.json (user scope)', () => {
  831. const claude = getTarget('claude')!;
  832. claude.install('global', { autoAllow: false });
  833. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  834. expect(cfg.mcpServers.codegraph).toBeDefined();
  835. });
  836. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  837. const claude = getTarget('claude')!;
  838. const legacy = path.join(tmpCwd, '.claude.json');
  839. fs.writeFileSync(
  840. legacy,
  841. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  842. );
  843. claude.install('local', { autoAllow: false });
  844. // codegraph now lives in .mcp.json; the legacy file (which held only
  845. // codegraph) is gone.
  846. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  847. expect(mcp.mcpServers.codegraph).toBeDefined();
  848. expect(fs.existsSync(legacy)).toBe(false);
  849. });
  850. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  851. const claude = getTarget('claude')!;
  852. const legacy = path.join(tmpCwd, '.claude.json');
  853. fs.writeFileSync(
  854. legacy,
  855. JSON.stringify({
  856. mcpServers: {
  857. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  858. other: { command: 'x' },
  859. },
  860. somethingElse: true,
  861. }, null, 2),
  862. );
  863. claude.install('local', { autoAllow: false });
  864. // Only codegraph is stripped from the legacy file; siblings survive.
  865. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  866. expect(after.mcpServers.codegraph).toBeUndefined();
  867. expect(after.mcpServers.other).toBeDefined();
  868. expect(after.somethingElse).toBe(true);
  869. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  870. expect(mcp.mcpServers.codegraph).toBeDefined();
  871. });
  872. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  873. const claude = getTarget('claude')!;
  874. // A user left with both the working .mcp.json and a stale .claude.json.
  875. fs.writeFileSync(
  876. path.join(tmpCwd, '.mcp.json'),
  877. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  878. );
  879. fs.writeFileSync(
  880. path.join(tmpCwd, '.claude.json'),
  881. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  882. );
  883. claude.uninstall('local');
  884. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  885. expect(mcp.mcpServers).toBeUndefined();
  886. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  887. expect(legacy.mcpServers.codegraph).toBeUndefined();
  888. expect(legacy.mcpServers.other).toBeDefined();
  889. });
  890. // ---- Legacy auto-sync hook cleanup ----
  891. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  892. // hooks to settings.json. Both subcommands were removed from the CLI,
  893. // so the Stop hook fails every turn ("unknown command
  894. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  895. // uninstall — without touching the user's unrelated hooks.
  896. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  897. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  898. fs.mkdirSync(dir, { recursive: true });
  899. const file = path.join(dir, 'settings.json');
  900. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  901. return file;
  902. }
  903. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  904. // unrelated GitKraken Stop hook the user added (matches the report).
  905. function legacyHookSettings(): Record<string, any> {
  906. return {
  907. hooks: {
  908. PostToolUse: [
  909. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  910. ],
  911. Stop: [
  912. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  913. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  914. ],
  915. },
  916. };
  917. }
  918. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  919. const claude = getTarget('claude')!;
  920. const file = seedSettings('global', legacyHookSettings());
  921. claude.install('global', { autoAllow: true });
  922. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  923. // The only PostToolUse group held mark-dirty → the event is gone.
  924. expect(after.hooks?.PostToolUse).toBeUndefined();
  925. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  926. (g.hooks ?? []).map((h: any) => h.command),
  927. );
  928. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  929. // The unrelated GitKraken hook survives untouched.
  930. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  931. // Permissions still written as normal alongside the cleanup.
  932. expect(after.permissions?.allow).toContain('mcp__codegraph__*');
  933. });
  934. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  935. const file = seedSettings('global', {
  936. hooks: {
  937. Stop: [
  938. {
  939. hooks: [
  940. { type: 'command', command: 'codegraph sync-if-dirty' },
  941. { type: 'command', command: 'gk ai hook run --host claude-code' },
  942. ],
  943. },
  944. ],
  945. },
  946. });
  947. expect(cleanupLegacyHooks('global').action).toBe('removed');
  948. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  949. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  950. 'gk ai hook run --host claude-code',
  951. ]);
  952. });
  953. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  954. const original =
  955. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  956. const file = seedSettings('global', JSON.parse(original));
  957. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  958. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  959. });
  960. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  961. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  962. });
  963. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  964. const claude = getTarget('claude')!;
  965. const file = seedSettings('global', legacyHookSettings());
  966. claude.install('global', { autoAllow: true });
  967. const firstPass = fs.readFileSync(file, 'utf-8');
  968. claude.install('global', { autoAllow: true });
  969. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  970. });
  971. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  972. const claude = getTarget('claude')!;
  973. const file = seedSettings('local', {
  974. hooks: {
  975. PostToolUse: [
  976. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  977. ],
  978. Stop: [
  979. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  980. ],
  981. },
  982. });
  983. claude.uninstall('local');
  984. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  985. // Both events emptied → the whole `hooks` object is removed.
  986. expect(after.hooks).toBeUndefined();
  987. });
  988. // ---- Front-load prompt hook (UserPromptSubmit) — #841 follow-up ----
  989. // Opt-in (default-yes in the installer) UserPromptSubmit hook that runs
  990. // `codegraph prompt-hook`. Must write/remove surgically, be idempotent, and
  991. // round-trip an opt-out — without disturbing the user's own hooks.
  992. const promptCommands = (s: any): string[] =>
  993. (s.hooks?.UserPromptSubmit ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  994. it('claude: install with promptHook:true writes the UserPromptSubmit hook (alongside permissions)', () => {
  995. const claude = getTarget('claude')!;
  996. claude.install('global', { autoAllow: true, promptHook: true });
  997. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  998. expect(promptCommands(s)).toContain('codegraph prompt-hook');
  999. expect(s.permissions?.allow).toContain('mcp__codegraph__*');
  1000. });
  1001. it('claude: install without promptHook does NOT add the hook', () => {
  1002. const claude = getTarget('claude')!;
  1003. claude.install('global', { autoAllow: true });
  1004. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1005. expect(promptCommands(s)).not.toContain('codegraph prompt-hook');
  1006. });
  1007. it('claude: install with promptHook:true is idempotent (no duplicate, byte-identical re-run)', () => {
  1008. const claude = getTarget('claude')!;
  1009. const file = path.join(tmpHome, '.claude', 'settings.json');
  1010. claude.install('global', { autoAllow: true, promptHook: true });
  1011. const first = fs.readFileSync(file, 'utf-8');
  1012. claude.install('global', { autoAllow: true, promptHook: true });
  1013. expect(fs.readFileSync(file, 'utf-8')).toBe(first);
  1014. const s = JSON.parse(first);
  1015. expect(promptCommands(s).filter((c: string) => c === 'codegraph prompt-hook')).toHaveLength(1);
  1016. });
  1017. it('claude: install with promptHook:false strips a hook a prior install wrote (opt-out round-trips)', () => {
  1018. const claude = getTarget('claude')!;
  1019. claude.install('global', { autoAllow: true, promptHook: true });
  1020. claude.install('global', { autoAllow: true, promptHook: false });
  1021. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1022. expect(promptCommands(s)).not.toContain('codegraph prompt-hook');
  1023. });
  1024. it('claude: writePromptHookEntry preserves a sibling UserPromptSubmit hook', () => {
  1025. const file = seedSettings('global', {
  1026. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'my-own-hook' }] }] },
  1027. });
  1028. expect(writePromptHookEntry('global').action).toBe('updated');
  1029. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1030. expect(promptCommands(s)).toEqual(['my-own-hook', 'codegraph prompt-hook']);
  1031. });
  1032. it('claude: uninstall removes the prompt hook but keeps the user\'s sibling', () => {
  1033. const file = seedSettings('global', {
  1034. hooks: {
  1035. UserPromptSubmit: [
  1036. { hooks: [{ type: 'command', command: 'codegraph prompt-hook' }] },
  1037. { hooks: [{ type: 'command', command: 'my-own-hook' }] },
  1038. ],
  1039. },
  1040. });
  1041. getTarget('claude')!.uninstall('global');
  1042. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1043. expect(promptCommands(s)).toEqual(['my-own-hook']);
  1044. });
  1045. it('claude: removePromptHookEntry leaves the legacy auto-sync hook untouched', () => {
  1046. const file = seedSettings('global', {
  1047. hooks: {
  1048. UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'codegraph prompt-hook' }] }],
  1049. Stop: [{ hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] }],
  1050. },
  1051. });
  1052. expect(removePromptHookEntry('global').action).toBe('removed');
  1053. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1054. expect(promptCommands(s)).not.toContain('codegraph prompt-hook');
  1055. const stopCmds = (s.hooks?.Stop ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  1056. expect(stopCmds).toContain('codegraph sync-if-dirty');
  1057. });
  1058. });
  1059. describe('Installer targets — registry', () => {
  1060. it('getTarget returns the right target for each id', () => {
  1061. expect(getTarget('claude')?.id).toBe('claude');
  1062. expect(getTarget('cursor')?.id).toBe('cursor');
  1063. expect(getTarget('codex')?.id).toBe('codex');
  1064. expect(getTarget('opencode')?.id).toBe('opencode');
  1065. expect(getTarget('hermes')?.id).toBe('hermes');
  1066. expect(getTarget('gemini')?.id).toBe('gemini');
  1067. expect(getTarget('antigravity')?.id).toBe('antigravity');
  1068. expect(getTarget('kiro')?.id).toBe('kiro');
  1069. expect(getTarget('not-a-real-target')).toBeUndefined();
  1070. });
  1071. it('resolveTargetFlag handles auto/all/none/csv', () => {
  1072. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  1073. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  1074. const csv = resolveTargetFlag('claude,cursor', 'global');
  1075. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  1076. });
  1077. it('resolveTargetFlag throws on unknown id', () => {
  1078. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  1079. });
  1080. });
  1081. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  1082. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  1083. const block = buildTomlTable('mcp_servers.codegraph', {
  1084. command: 'codegraph',
  1085. args: ['serve', '--mcp'],
  1086. });
  1087. expect(block).toContain('[mcp_servers.codegraph]');
  1088. expect(block).toContain('command = "codegraph"');
  1089. expect(block).toContain('args = ["serve", "--mcp"]');
  1090. });
  1091. it('upsert inserts into empty content', () => {
  1092. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1093. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1094. expect(action).toBe('inserted');
  1095. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  1096. });
  1097. it('upsert is idempotent — second call returns unchanged', () => {
  1098. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1099. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1100. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  1101. expect(second.action).toBe('unchanged');
  1102. expect(second.content).toBe(first.content);
  1103. });
  1104. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  1105. const existing = [
  1106. '[other_table]',
  1107. 'foo = "bar"',
  1108. '',
  1109. '[mcp_servers.codegraph]',
  1110. 'command = "old-codegraph"',
  1111. 'args = ["old"]',
  1112. '',
  1113. '[zzz]',
  1114. 'baz = "qux"',
  1115. '',
  1116. ].join('\n');
  1117. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  1118. command: 'codegraph',
  1119. args: ['serve', '--mcp'],
  1120. });
  1121. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  1122. expect(action).toBe('replaced');
  1123. expect(content).toContain('[other_table]');
  1124. expect(content).toContain('foo = "bar"');
  1125. expect(content).toContain('[zzz]');
  1126. expect(content).toContain('baz = "qux"');
  1127. expect(content).toContain('command = "codegraph"');
  1128. expect(content).not.toContain('old-codegraph');
  1129. });
  1130. it('removeTomlTable strips the block and preserves siblings', () => {
  1131. const existing = [
  1132. '[other_table]',
  1133. 'foo = "bar"',
  1134. '',
  1135. '[mcp_servers.codegraph]',
  1136. 'command = "codegraph"',
  1137. 'args = ["serve"]',
  1138. ].join('\n');
  1139. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1140. expect(action).toBe('removed');
  1141. expect(content).toContain('[other_table]');
  1142. expect(content).toContain('foo = "bar"');
  1143. expect(content).not.toContain('mcp_servers.codegraph');
  1144. });
  1145. it('removeTomlTable on missing table returns not-found, no content change', () => {
  1146. const existing = '[other]\nfoo = "bar"\n';
  1147. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1148. expect(action).toBe('not-found');
  1149. expect(content).toBe(existing);
  1150. });
  1151. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  1152. const existing = [
  1153. '[[foo]]',
  1154. 'name = "a"',
  1155. '',
  1156. '[[foo]]',
  1157. 'name = "b"',
  1158. '',
  1159. ].join('\n');
  1160. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1161. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1162. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  1163. expect(content).toContain('[mcp_servers.codegraph]');
  1164. });
  1165. it('upsert replaces the managed table without consuming trailing array-of-tables siblings', () => {
  1166. const historyTables = [
  1167. '[[history]]',
  1168. 'id = 1',
  1169. 'note = "keep first"',
  1170. '',
  1171. '[[history]]',
  1172. 'id = 2',
  1173. 'note = "keep second"',
  1174. '',
  1175. ].join('\n');
  1176. const existing = [
  1177. '[mcp_servers.codegraph]',
  1178. 'command = "old-codegraph"',
  1179. 'args = ["old"]',
  1180. '',
  1181. historyTables,
  1182. ].join('\n');
  1183. const block = buildTomlTable('mcp_servers.codegraph', {
  1184. command: 'codegraph',
  1185. args: ['serve', '--mcp'],
  1186. });
  1187. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1188. expect(action).toBe('replaced');
  1189. expect(content).toBe(`${block}\n\n${historyTables}`);
  1190. });
  1191. it('remove preserves trailing array-of-tables siblings byte-for-byte', () => {
  1192. const historyTables = [
  1193. '[[history]]',
  1194. 'id = 1',
  1195. 'note = "keep first"',
  1196. '',
  1197. '[[history]]',
  1198. 'id = 2',
  1199. 'note = "keep second"',
  1200. '',
  1201. ].join('\n');
  1202. const existing = [
  1203. '[mcp_servers.codegraph]',
  1204. 'command = "codegraph"',
  1205. 'args = ["serve", "--mcp"]',
  1206. '',
  1207. historyTables,
  1208. ].join('\n');
  1209. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1210. expect(action).toBe('removed');
  1211. expect(content).toBe(historyTables);
  1212. });
  1213. it.each([
  1214. ['table', '[ mcp_servers.other ]'],
  1215. ['array-of-tables', '[[ history ]]'],
  1216. ])('preserves a trailing %s header with inner whitespace', (_kind, siblingHeader) => {
  1217. const siblingTable = `${siblingHeader}\nvalue = "keep"\n`;
  1218. const existing = [
  1219. '[mcp_servers.codegraph]',
  1220. 'command = "old-codegraph"',
  1221. 'args = ["old"]',
  1222. '',
  1223. siblingTable,
  1224. ].join('\n');
  1225. const block = buildTomlTable('mcp_servers.codegraph', {
  1226. command: 'codegraph',
  1227. args: ['serve', '--mcp'],
  1228. });
  1229. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1230. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1231. expect(upserted.content).toBe(`${block}\n\n${siblingTable}`);
  1232. expect(removed.content).toBe(siblingTable);
  1233. });
  1234. it.each([
  1235. ['basic', '"""'],
  1236. ['literal', "'''"],
  1237. ])('ignores header-shaped text inside a multiline %s string', (_kind, delimiter) => {
  1238. const historyTable = '[[history]]\nid = 1\n';
  1239. const existing = [
  1240. '[mcp_servers.codegraph]',
  1241. 'command = "old-codegraph"',
  1242. 'args = [',
  1243. ` ${delimiter}first line`,
  1244. '[[not-a-table]]',
  1245. `last line${delimiter},`,
  1246. ' "serve",',
  1247. ']',
  1248. '',
  1249. historyTable,
  1250. ].join('\n');
  1251. const block = buildTomlTable('mcp_servers.codegraph', {
  1252. command: 'codegraph',
  1253. args: ['serve', '--mcp'],
  1254. });
  1255. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1256. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1257. expect(upserted.content).toBe(`${block}\n\n${historyTable}`);
  1258. expect(removed.content).toBe(historyTable);
  1259. });
  1260. });
  1261. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  1262. let tmpHome: string;
  1263. let tmpCwd: string;
  1264. let origCwd: string;
  1265. let homeRestore: { restore: () => void };
  1266. beforeEach(() => {
  1267. tmpHome = mkTmpDir('un-home');
  1268. tmpCwd = mkTmpDir('un-cwd');
  1269. origCwd = process.cwd();
  1270. process.chdir(tmpCwd);
  1271. homeRestore = setHome(tmpHome);
  1272. });
  1273. afterEach(() => {
  1274. homeRestore.restore();
  1275. process.chdir(origCwd);
  1276. fs.rmSync(tmpHome, { recursive: true, force: true });
  1277. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1278. });
  1279. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  1280. for (const t of ALL_TARGETS) {
  1281. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1282. }
  1283. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1284. for (const t of ALL_TARGETS) {
  1285. const r = reports.find((x) => x.id === t.id)!;
  1286. expect(r.status).toBe('removed');
  1287. expect(r.removedPaths.length).toBeGreaterThan(0);
  1288. // The actual config is gone afterward.
  1289. expect(t.detect('global').alreadyConfigured).toBe(false);
  1290. }
  1291. });
  1292. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  1293. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1294. for (const r of reports) {
  1295. expect(r.status).toBe('not-configured');
  1296. expect(r.removedPaths).toEqual([]);
  1297. }
  1298. });
  1299. it('reports removed only for agents that were actually configured', () => {
  1300. // Install on Claude only; the rest stay untouched.
  1301. getTarget('claude')!.install('global', { autoAllow: true });
  1302. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1303. const claude = reports.find((r) => r.id === 'claude')!;
  1304. expect(claude.status).toBe('removed');
  1305. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  1306. for (const r of reports.filter((x) => x.id !== 'claude')) {
  1307. expect(r.status).toBe('not-configured');
  1308. }
  1309. });
  1310. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  1311. const reports = uninstallTargets(ALL_TARGETS, 'local');
  1312. for (const t of ALL_TARGETS) {
  1313. const r = reports.find((x) => x.id === t.id)!;
  1314. if (t.supportsLocation('local')) {
  1315. expect(r.status).toBe('not-configured');
  1316. } else {
  1317. expect(r.status).toBe('unsupported');
  1318. expect(r.removedPaths).toEqual([]);
  1319. expect(r.notes[0]).toMatch(/global-only/);
  1320. }
  1321. }
  1322. });
  1323. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1324. for (const t of ALL_TARGETS) {
  1325. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1326. }
  1327. const first = uninstallTargets(ALL_TARGETS, 'global');
  1328. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1329. const second = uninstallTargets(ALL_TARGETS, 'global');
  1330. for (const r of second) {
  1331. expect(r.status).toBe('not-configured');
  1332. expect(r.removedPaths).toEqual([]);
  1333. }
  1334. });
  1335. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1336. getTarget('claude')!.install('global', { autoAllow: true });
  1337. getTarget('cursor')!.install('global', { autoAllow: true });
  1338. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1339. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1340. expect(reports[0].status).toBe('removed');
  1341. // Cursor was not in the subset — still configured.
  1342. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1343. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1344. });
  1345. });
  1346. describe('Installer — refreshTargets sweep (codegraph install --refresh)', () => {
  1347. let tmpHome: string;
  1348. let tmpCwd: string;
  1349. let origCwd: string;
  1350. let homeRestore: { restore: () => void };
  1351. beforeEach(() => {
  1352. tmpHome = mkTmpDir('rf-home');
  1353. tmpCwd = mkTmpDir('rf-cwd');
  1354. origCwd = process.cwd();
  1355. process.chdir(tmpCwd);
  1356. homeRestore = setHome(tmpHome);
  1357. });
  1358. afterEach(() => {
  1359. homeRestore.restore();
  1360. process.chdir(origCwd);
  1361. fs.rmSync(tmpHome, { recursive: true, force: true });
  1362. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1363. });
  1364. it('rewrites a stale instructions block a previous version left, and reports refreshed', () => {
  1365. const claude = getTarget('claude')!;
  1366. claude.install('global', { autoAllow: true });
  1367. // Simulate the file as an old install left it: same markers, the old
  1368. // multi-tool wording.
  1369. const claudeMd = path.join(tmpHome, '.claude', 'CLAUDE.md');
  1370. fs.writeFileSync(claudeMd, LEGACY_BLOCK + '\n');
  1371. const reports = refreshTargets([claude], 'global');
  1372. expect(reports[0].status).toBe('refreshed');
  1373. expect(reports[0].changedPaths).toContain(claudeMd);
  1374. const md = fs.readFileSync(claudeMd, 'utf-8');
  1375. expect(md).not.toContain('codegraph_search');
  1376. expect(md).toContain('codegraph_explore');
  1377. });
  1378. it('never performs a first install — unconfigured agents stay untouched', () => {
  1379. const reports = refreshTargets(ALL_TARGETS, 'global');
  1380. for (const t of ALL_TARGETS) {
  1381. const r = reports.find((x) => x.id === t.id)!;
  1382. expect(r.status).toBe(t.supportsLocation('global') ? 'not-configured' : 'unsupported');
  1383. expect(r.changedPaths).toEqual([]);
  1384. expect(t.detect('global').alreadyConfigured).toBe(false);
  1385. }
  1386. });
  1387. it('preserves the user\'s permission choices (refresh never writes permissions)', () => {
  1388. const claude = getTarget('claude')!;
  1389. claude.install('global', { autoAllow: true });
  1390. // The user has since trimmed the allowlist by hand.
  1391. const settingsPath = path.join(tmpHome, '.claude', 'settings.json');
  1392. const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1393. settings.permissions.allow = [];
  1394. fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
  1395. refreshTargets([claude], 'global');
  1396. const after = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1397. expect(after.permissions.allow).toEqual([]);
  1398. });
  1399. it('is idempotent — a second sweep on a current machine reports unchanged everywhere', () => {
  1400. for (const t of ALL_TARGETS) {
  1401. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1402. }
  1403. const first = refreshTargets(ALL_TARGETS, 'global');
  1404. // Fresh installs are already current, so even the first sweep may be
  1405. // all-unchanged; what matters is the second definitely is.
  1406. const second = refreshTargets(ALL_TARGETS, 'global');
  1407. for (const r of [...first, ...second]) {
  1408. expect(['unchanged', 'refreshed']).toContain(r.status);
  1409. }
  1410. for (const r of second) {
  1411. expect(r.status).toBe('unchanged');
  1412. expect(r.changedPaths).toEqual([]);
  1413. }
  1414. });
  1415. });
  1416. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1417. let tmpHome: string;
  1418. let tmpCwd: string;
  1419. let origCwd: string;
  1420. let homeRestore: { restore: () => void };
  1421. const cursor = getTarget('cursor')!;
  1422. beforeEach(() => {
  1423. tmpHome = mkTmpDir('cur-home');
  1424. tmpCwd = mkTmpDir('cur-cwd');
  1425. origCwd = process.cwd();
  1426. process.chdir(tmpCwd);
  1427. homeRestore = setHome(tmpHome);
  1428. });
  1429. afterEach(() => {
  1430. homeRestore.restore();
  1431. process.chdir(origCwd);
  1432. fs.rmSync(tmpHome, { recursive: true, force: true });
  1433. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1434. });
  1435. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1436. // The frontmatter a previous install wrote ahead of the marked block.
  1437. // `removeRulesEntry` recognizes it to decide whether the leftover .mdc
  1438. // is ours-to-delete or carries user content worth keeping.
  1439. const MDC_FRONTMATTER = [
  1440. '---',
  1441. 'description: CodeGraph MCP usage guide — when to use which tool',
  1442. 'alwaysApply: true',
  1443. '---',
  1444. '',
  1445. ].join('\n');
  1446. function plantLegacyRulesFile(extra = ''): void {
  1447. fs.mkdirSync(path.dirname(rulesFile()), { recursive: true });
  1448. fs.writeFileSync(rulesFile(), MDC_FRONTMATTER + LEGACY_BLOCK + '\n' + extra);
  1449. }
  1450. it('uninstall deletes a leftover codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1451. plantLegacyRulesFile();
  1452. expect(fs.existsSync(rulesFile())).toBe(true);
  1453. cursor.uninstall('local');
  1454. // The whole file — frontmatter included — is gone, not just the block.
  1455. expect(fs.existsSync(rulesFile())).toBe(false);
  1456. });
  1457. it('install self-heals a leftover codegraph.mdc (#529)', () => {
  1458. plantLegacyRulesFile();
  1459. const result = cursor.install('local', { autoAllow: true });
  1460. expect(fs.existsSync(rulesFile())).toBe(false);
  1461. expect(result.files.some((f) => f.path.endsWith('codegraph.mdc') && f.action === 'removed')).toBe(true);
  1462. });
  1463. it('uninstall preserves user content added outside the codegraph markers (strips only our block)', () => {
  1464. plantLegacyRulesFile('## My own rule\nkeep me\n');
  1465. cursor.uninstall('local');
  1466. expect(fs.existsSync(rulesFile())).toBe(true);
  1467. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1468. expect(after).toContain('keep me');
  1469. // Our tool-usage block is gone.
  1470. expect(after).not.toContain('codegraph_search');
  1471. expect(after).not.toContain('CODEGRAPH_START');
  1472. });
  1473. });
  1474. function listAllFiles(dir: string): string[] {
  1475. if (!fs.existsSync(dir)) return [];
  1476. const out: string[] = [];
  1477. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1478. const full = path.join(dir, entry.name);
  1479. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1480. else out.push(full);
  1481. }
  1482. return out;
  1483. }
  1484. // ---------------------------------------------------------------------------
  1485. // opencode global config path — XDG on every platform (#535)
  1486. //
  1487. // opencode resolves its config dir with `xdg-basedir`: XDG_CONFIG_HOME if
  1488. // set, else ~/.config — on ALL platforms, Windows included. It never reads
  1489. // %APPDATA%; we used to write there on Windows, so opencode never saw the
  1490. // entry. The suite-wide setHome() points APPDATA and XDG_CONFIG_HOME at the
  1491. // SAME directory (which is exactly how this bug stayed invisible), so these
  1492. // tests deliberately split them.
  1493. // ---------------------------------------------------------------------------
  1494. describe('Installer targets — opencode XDG config path (#535)', () => {
  1495. let tmpHome: string;
  1496. let tmpCwd: string;
  1497. let origCwd: string;
  1498. let homeRestore: { restore: () => void };
  1499. let appDataDir: string; // distinct from ~/.config, like real Windows
  1500. beforeEach(() => {
  1501. tmpHome = mkTmpDir('home');
  1502. tmpCwd = mkTmpDir('cwd');
  1503. origCwd = process.cwd();
  1504. process.chdir(tmpCwd);
  1505. homeRestore = setHome(tmpHome);
  1506. appDataDir = path.join(tmpHome, 'AppData', 'Roaming');
  1507. process.env.APPDATA = appDataDir; // realistic split: APPDATA ≠ ~/.config
  1508. delete process.env.XDG_CONFIG_HOME; // default resolution: ~/.config
  1509. });
  1510. afterEach(() => {
  1511. homeRestore.restore();
  1512. process.chdir(origCwd);
  1513. fs.rmSync(tmpHome, { recursive: true, force: true });
  1514. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1515. });
  1516. const xdgConfigFile = () => path.join(tmpHome, '.config', 'opencode', 'opencode.jsonc');
  1517. const legacyDir = () => path.join(appDataDir, 'opencode');
  1518. // NOTE: never match on an 'AppData' substring — on Windows os.tmpdir()
  1519. // itself lives under AppData\Local\Temp, so EVERY harness path contains
  1520. // it. Match on the legacy dir prefix instead.
  1521. const inLegacyDir = (p: string) => path.resolve(p).startsWith(path.resolve(legacyDir()) + path.sep);
  1522. it('global install writes to ~/.config/opencode, never %APPDATA% (#535)', () => {
  1523. const opencode = getTarget('opencode')!;
  1524. const result = opencode.install('global', { autoAllow: true });
  1525. const written = result.files.find((f) => f.path.endsWith('opencode.jsonc'))!;
  1526. expect(written.action).toBe('created');
  1527. expect(path.resolve(written.path)).toBe(path.resolve(xdgConfigFile()));
  1528. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1529. // Nothing of ours may land in the legacy location.
  1530. expect(fs.existsSync(legacyDir())).toBe(false);
  1531. });
  1532. it('greenfield: targets ~/.config/opencode even when the dir does not exist yet (#535)', () => {
  1533. // The rejected fallback design (#670) would send this install to
  1534. // %APPDATA% — where opencode would never find it. opencode creates
  1535. // ~/.config/opencode itself on first run; installing codegraph FIRST
  1536. // must land where opencode will look.
  1537. expect(fs.existsSync(path.join(tmpHome, '.config', 'opencode'))).toBe(false);
  1538. const opencode = getTarget('opencode')!;
  1539. const result = opencode.install('global', { autoAllow: true });
  1540. expect(path.resolve(result.files[0]!.path)).toBe(path.resolve(xdgConfigFile()));
  1541. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1542. expect(fs.existsSync(legacyDir())).toBe(false);
  1543. });
  1544. it('honors XDG_CONFIG_HOME for the global path, like opencode does', () => {
  1545. const custom = path.join(tmpHome, 'xdg-custom');
  1546. process.env.XDG_CONFIG_HOME = custom;
  1547. const opencode = getTarget('opencode')!;
  1548. const result = opencode.install('global', { autoAllow: true });
  1549. expect(path.resolve(result.files[0]!.path))
  1550. .toBe(path.resolve(path.join(custom, 'opencode', 'opencode.jsonc')));
  1551. });
  1552. it('install self-heals a pre-#535 %APPDATA% entry, preserving siblings and comments', () => {
  1553. // A previous codegraph version wrote into %APPDATA%/opencode. The user
  1554. // also has another MCP server and a comment there — those must survive.
  1555. fs.mkdirSync(legacyDir(), { recursive: true });
  1556. fs.writeFileSync(path.join(legacyDir(), 'opencode.jsonc'), [
  1557. '{',
  1558. ' // my servers',
  1559. ' "$schema": "https://opencode.ai/config.json",',
  1560. ' "mcp": {',
  1561. ' "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true },',
  1562. ' "other": { "type": "local", "command": ["other"], "enabled": true }',
  1563. ' }',
  1564. '}',
  1565. '',
  1566. ].join('\n'));
  1567. fs.writeFileSync(path.join(legacyDir(), 'AGENTS.md'), LEGACY_BLOCK + '\n');
  1568. const opencode = getTarget('opencode')!;
  1569. const result = opencode.install('global', { autoAllow: true });
  1570. // New entry in the right place…
  1571. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1572. // …stale entry swept out of the legacy file, siblings + comment intact.
  1573. const legacyText = fs.readFileSync(path.join(legacyDir(), 'opencode.jsonc'), 'utf-8');
  1574. expect(legacyText).not.toContain('codegraph');
  1575. expect(legacyText).toContain('"other"');
  1576. expect(legacyText).toContain('// my servers');
  1577. // …and the legacy AGENTS.md — block-only, so emptied — removed outright
  1578. // (removeMarkedSection unlinks a file it leaves empty).
  1579. expect(fs.existsSync(path.join(legacyDir(), 'AGENTS.md'))).toBe(false);
  1580. // Both cleanups are reported.
  1581. const removed = result.files.filter((f) => f.action === 'removed').map((f) => f.path);
  1582. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('opencode.jsonc'))).toBe(true);
  1583. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('AGENTS.md'))).toBe(true);
  1584. });
  1585. it('uninstall sweeps the legacy %APPDATA% entry too (no prior re-install needed)', () => {
  1586. // A user on the broken version goes straight to `codegraph uninstall`:
  1587. // the only entry that exists is the stale %APPDATA% one.
  1588. fs.mkdirSync(legacyDir(), { recursive: true });
  1589. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1590. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1591. const opencode = getTarget('opencode')!;
  1592. const result = opencode.uninstall('global');
  1593. expect(fs.readFileSync(path.join(legacyDir(), 'opencode.json'), 'utf-8')).not.toContain('codegraph');
  1594. expect(result.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1595. });
  1596. it('install after install sweeps only once — second run reports no legacy changes', () => {
  1597. fs.mkdirSync(legacyDir(), { recursive: true });
  1598. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1599. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1600. const opencode = getTarget('opencode')!;
  1601. const first = opencode.install('global', { autoAllow: true });
  1602. expect(first.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1603. const second = opencode.install('global', { autoAllow: true });
  1604. expect(second.files.some((f) => inLegacyDir(f.path))).toBe(false);
  1605. expect(second.files.find((f) => f.path.endsWith('opencode.jsonc'))!.action).toBe('unchanged');
  1606. });
  1607. it('detects opencode as installed from a legacy-only %APPDATA% dir (so install can heal it)', () => {
  1608. fs.mkdirSync(legacyDir(), { recursive: true });
  1609. const opencode = getTarget('opencode')!;
  1610. expect(opencode.detect('global').installed).toBe(true);
  1611. // But configuration state is read from the REAL path only.
  1612. expect(opencode.detect('global').alreadyConfigured).toBe(false);
  1613. });
  1614. });