1
0

installer-targets.test.ts 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  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 } from '../src/installer';
  22. import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  23. import { cleanupLegacyHooks } 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('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  760. const claude = getTarget('claude')!;
  761. const result = claude.install('local', { autoAllow: false });
  762. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  763. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  764. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  765. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  766. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  767. expect(cfg.mcpServers.codegraph).toBeDefined();
  768. });
  769. it('claude: install creates the CLAUDE.md codegraph block (#704)', () => {
  770. const claude = getTarget('claude')!;
  771. const result = claude.install('local', { autoAllow: false });
  772. const claudeMd = path.join(tmpCwd, '.claude', 'CLAUDE.md');
  773. expect(fs.existsSync(claudeMd)).toBe(true);
  774. const body = fs.readFileSync(claudeMd, 'utf-8');
  775. expect(body).toContain('## CodeGraph');
  776. expect(body).toContain('codegraph explore');
  777. expect(result.files.find((f) => f.path.endsWith('CLAUDE.md'))?.action).toBe('created');
  778. });
  779. it('claude: install replaces a legacy CLAUDE.md codegraph block, keeping user content', () => {
  780. const claude = getTarget('claude')!;
  781. const claudeMd = path.join(tmpCwd, '.claude', 'CLAUDE.md');
  782. fs.mkdirSync(path.dirname(claudeMd), { recursive: true });
  783. fs.writeFileSync(claudeMd, `# My project rules\n\nUse tabs.\n\n${LEGACY_BLOCK}\n`);
  784. const result = claude.install('local', { autoAllow: false });
  785. const body = fs.readFileSync(claudeMd, 'utf-8');
  786. expect(body).toContain('# My project rules');
  787. expect(body).toContain('Use tabs.');
  788. expect(body).not.toContain('Prefer `codegraph_search`');
  789. expect(body).toContain('codegraph explore');
  790. expect(result.files.find((f) => f.path.endsWith('CLAUDE.md'))?.action).toBe('updated');
  791. });
  792. it('claude: global install targets ~/.claude.json (user scope)', () => {
  793. const claude = getTarget('claude')!;
  794. claude.install('global', { autoAllow: false });
  795. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  796. expect(cfg.mcpServers.codegraph).toBeDefined();
  797. });
  798. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  799. const claude = getTarget('claude')!;
  800. const legacy = path.join(tmpCwd, '.claude.json');
  801. fs.writeFileSync(
  802. legacy,
  803. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  804. );
  805. claude.install('local', { autoAllow: false });
  806. // codegraph now lives in .mcp.json; the legacy file (which held only
  807. // codegraph) is gone.
  808. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  809. expect(mcp.mcpServers.codegraph).toBeDefined();
  810. expect(fs.existsSync(legacy)).toBe(false);
  811. });
  812. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  813. const claude = getTarget('claude')!;
  814. const legacy = path.join(tmpCwd, '.claude.json');
  815. fs.writeFileSync(
  816. legacy,
  817. JSON.stringify({
  818. mcpServers: {
  819. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  820. other: { command: 'x' },
  821. },
  822. somethingElse: true,
  823. }, null, 2),
  824. );
  825. claude.install('local', { autoAllow: false });
  826. // Only codegraph is stripped from the legacy file; siblings survive.
  827. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  828. expect(after.mcpServers.codegraph).toBeUndefined();
  829. expect(after.mcpServers.other).toBeDefined();
  830. expect(after.somethingElse).toBe(true);
  831. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  832. expect(mcp.mcpServers.codegraph).toBeDefined();
  833. });
  834. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  835. const claude = getTarget('claude')!;
  836. // A user left with both the working .mcp.json and a stale .claude.json.
  837. fs.writeFileSync(
  838. path.join(tmpCwd, '.mcp.json'),
  839. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  840. );
  841. fs.writeFileSync(
  842. path.join(tmpCwd, '.claude.json'),
  843. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  844. );
  845. claude.uninstall('local');
  846. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  847. expect(mcp.mcpServers).toBeUndefined();
  848. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  849. expect(legacy.mcpServers.codegraph).toBeUndefined();
  850. expect(legacy.mcpServers.other).toBeDefined();
  851. });
  852. // ---- Legacy auto-sync hook cleanup ----
  853. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  854. // hooks to settings.json. Both subcommands were removed from the CLI,
  855. // so the Stop hook fails every turn ("unknown command
  856. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  857. // uninstall — without touching the user's unrelated hooks.
  858. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  859. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  860. fs.mkdirSync(dir, { recursive: true });
  861. const file = path.join(dir, 'settings.json');
  862. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  863. return file;
  864. }
  865. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  866. // unrelated GitKraken Stop hook the user added (matches the report).
  867. function legacyHookSettings(): Record<string, any> {
  868. return {
  869. hooks: {
  870. PostToolUse: [
  871. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  872. ],
  873. Stop: [
  874. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  875. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  876. ],
  877. },
  878. };
  879. }
  880. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  881. const claude = getTarget('claude')!;
  882. const file = seedSettings('global', legacyHookSettings());
  883. claude.install('global', { autoAllow: true });
  884. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  885. // The only PostToolUse group held mark-dirty → the event is gone.
  886. expect(after.hooks?.PostToolUse).toBeUndefined();
  887. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  888. (g.hooks ?? []).map((h: any) => h.command),
  889. );
  890. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  891. // The unrelated GitKraken hook survives untouched.
  892. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  893. // Permissions still written as normal alongside the cleanup.
  894. expect(after.permissions?.allow).toContain('mcp__codegraph__*');
  895. });
  896. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  897. const file = seedSettings('global', {
  898. hooks: {
  899. Stop: [
  900. {
  901. hooks: [
  902. { type: 'command', command: 'codegraph sync-if-dirty' },
  903. { type: 'command', command: 'gk ai hook run --host claude-code' },
  904. ],
  905. },
  906. ],
  907. },
  908. });
  909. expect(cleanupLegacyHooks('global').action).toBe('removed');
  910. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  911. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  912. 'gk ai hook run --host claude-code',
  913. ]);
  914. });
  915. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  916. const original =
  917. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  918. const file = seedSettings('global', JSON.parse(original));
  919. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  920. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  921. });
  922. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  923. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  924. });
  925. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  926. const claude = getTarget('claude')!;
  927. const file = seedSettings('global', legacyHookSettings());
  928. claude.install('global', { autoAllow: true });
  929. const firstPass = fs.readFileSync(file, 'utf-8');
  930. claude.install('global', { autoAllow: true });
  931. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  932. });
  933. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  934. const claude = getTarget('claude')!;
  935. const file = seedSettings('local', {
  936. hooks: {
  937. PostToolUse: [
  938. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  939. ],
  940. Stop: [
  941. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  942. ],
  943. },
  944. });
  945. claude.uninstall('local');
  946. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  947. // Both events emptied → the whole `hooks` object is removed.
  948. expect(after.hooks).toBeUndefined();
  949. });
  950. });
  951. describe('Installer targets — registry', () => {
  952. it('getTarget returns the right target for each id', () => {
  953. expect(getTarget('claude')?.id).toBe('claude');
  954. expect(getTarget('cursor')?.id).toBe('cursor');
  955. expect(getTarget('codex')?.id).toBe('codex');
  956. expect(getTarget('opencode')?.id).toBe('opencode');
  957. expect(getTarget('hermes')?.id).toBe('hermes');
  958. expect(getTarget('gemini')?.id).toBe('gemini');
  959. expect(getTarget('antigravity')?.id).toBe('antigravity');
  960. expect(getTarget('kiro')?.id).toBe('kiro');
  961. expect(getTarget('not-a-real-target')).toBeUndefined();
  962. });
  963. it('resolveTargetFlag handles auto/all/none/csv', () => {
  964. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  965. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  966. const csv = resolveTargetFlag('claude,cursor', 'global');
  967. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  968. });
  969. it('resolveTargetFlag throws on unknown id', () => {
  970. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  971. });
  972. });
  973. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  974. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  975. const block = buildTomlTable('mcp_servers.codegraph', {
  976. command: 'codegraph',
  977. args: ['serve', '--mcp'],
  978. });
  979. expect(block).toContain('[mcp_servers.codegraph]');
  980. expect(block).toContain('command = "codegraph"');
  981. expect(block).toContain('args = ["serve", "--mcp"]');
  982. });
  983. it('upsert inserts into empty content', () => {
  984. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  985. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  986. expect(action).toBe('inserted');
  987. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  988. });
  989. it('upsert is idempotent — second call returns unchanged', () => {
  990. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  991. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  992. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  993. expect(second.action).toBe('unchanged');
  994. expect(second.content).toBe(first.content);
  995. });
  996. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  997. const existing = [
  998. '[other_table]',
  999. 'foo = "bar"',
  1000. '',
  1001. '[mcp_servers.codegraph]',
  1002. 'command = "old-codegraph"',
  1003. 'args = ["old"]',
  1004. '',
  1005. '[zzz]',
  1006. 'baz = "qux"',
  1007. '',
  1008. ].join('\n');
  1009. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  1010. command: 'codegraph',
  1011. args: ['serve', '--mcp'],
  1012. });
  1013. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  1014. expect(action).toBe('replaced');
  1015. expect(content).toContain('[other_table]');
  1016. expect(content).toContain('foo = "bar"');
  1017. expect(content).toContain('[zzz]');
  1018. expect(content).toContain('baz = "qux"');
  1019. expect(content).toContain('command = "codegraph"');
  1020. expect(content).not.toContain('old-codegraph');
  1021. });
  1022. it('removeTomlTable strips the block and preserves siblings', () => {
  1023. const existing = [
  1024. '[other_table]',
  1025. 'foo = "bar"',
  1026. '',
  1027. '[mcp_servers.codegraph]',
  1028. 'command = "codegraph"',
  1029. 'args = ["serve"]',
  1030. ].join('\n');
  1031. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1032. expect(action).toBe('removed');
  1033. expect(content).toContain('[other_table]');
  1034. expect(content).toContain('foo = "bar"');
  1035. expect(content).not.toContain('mcp_servers.codegraph');
  1036. });
  1037. it('removeTomlTable on missing table returns not-found, no content change', () => {
  1038. const existing = '[other]\nfoo = "bar"\n';
  1039. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1040. expect(action).toBe('not-found');
  1041. expect(content).toBe(existing);
  1042. });
  1043. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  1044. const existing = [
  1045. '[[foo]]',
  1046. 'name = "a"',
  1047. '',
  1048. '[[foo]]',
  1049. 'name = "b"',
  1050. '',
  1051. ].join('\n');
  1052. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1053. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1054. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  1055. expect(content).toContain('[mcp_servers.codegraph]');
  1056. });
  1057. });
  1058. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  1059. let tmpHome: string;
  1060. let tmpCwd: string;
  1061. let origCwd: string;
  1062. let homeRestore: { restore: () => void };
  1063. beforeEach(() => {
  1064. tmpHome = mkTmpDir('un-home');
  1065. tmpCwd = mkTmpDir('un-cwd');
  1066. origCwd = process.cwd();
  1067. process.chdir(tmpCwd);
  1068. homeRestore = setHome(tmpHome);
  1069. });
  1070. afterEach(() => {
  1071. homeRestore.restore();
  1072. process.chdir(origCwd);
  1073. fs.rmSync(tmpHome, { recursive: true, force: true });
  1074. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1075. });
  1076. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  1077. for (const t of ALL_TARGETS) {
  1078. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1079. }
  1080. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1081. for (const t of ALL_TARGETS) {
  1082. const r = reports.find((x) => x.id === t.id)!;
  1083. expect(r.status).toBe('removed');
  1084. expect(r.removedPaths.length).toBeGreaterThan(0);
  1085. // The actual config is gone afterward.
  1086. expect(t.detect('global').alreadyConfigured).toBe(false);
  1087. }
  1088. });
  1089. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  1090. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1091. for (const r of reports) {
  1092. expect(r.status).toBe('not-configured');
  1093. expect(r.removedPaths).toEqual([]);
  1094. }
  1095. });
  1096. it('reports removed only for agents that were actually configured', () => {
  1097. // Install on Claude only; the rest stay untouched.
  1098. getTarget('claude')!.install('global', { autoAllow: true });
  1099. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1100. const claude = reports.find((r) => r.id === 'claude')!;
  1101. expect(claude.status).toBe('removed');
  1102. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  1103. for (const r of reports.filter((x) => x.id !== 'claude')) {
  1104. expect(r.status).toBe('not-configured');
  1105. }
  1106. });
  1107. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  1108. const reports = uninstallTargets(ALL_TARGETS, 'local');
  1109. for (const t of ALL_TARGETS) {
  1110. const r = reports.find((x) => x.id === t.id)!;
  1111. if (t.supportsLocation('local')) {
  1112. expect(r.status).toBe('not-configured');
  1113. } else {
  1114. expect(r.status).toBe('unsupported');
  1115. expect(r.removedPaths).toEqual([]);
  1116. expect(r.notes[0]).toMatch(/global-only/);
  1117. }
  1118. }
  1119. });
  1120. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1121. for (const t of ALL_TARGETS) {
  1122. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1123. }
  1124. const first = uninstallTargets(ALL_TARGETS, 'global');
  1125. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1126. const second = uninstallTargets(ALL_TARGETS, 'global');
  1127. for (const r of second) {
  1128. expect(r.status).toBe('not-configured');
  1129. expect(r.removedPaths).toEqual([]);
  1130. }
  1131. });
  1132. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1133. getTarget('claude')!.install('global', { autoAllow: true });
  1134. getTarget('cursor')!.install('global', { autoAllow: true });
  1135. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1136. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1137. expect(reports[0].status).toBe('removed');
  1138. // Cursor was not in the subset — still configured.
  1139. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1140. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1141. });
  1142. });
  1143. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1144. let tmpHome: string;
  1145. let tmpCwd: string;
  1146. let origCwd: string;
  1147. let homeRestore: { restore: () => void };
  1148. const cursor = getTarget('cursor')!;
  1149. beforeEach(() => {
  1150. tmpHome = mkTmpDir('cur-home');
  1151. tmpCwd = mkTmpDir('cur-cwd');
  1152. origCwd = process.cwd();
  1153. process.chdir(tmpCwd);
  1154. homeRestore = setHome(tmpHome);
  1155. });
  1156. afterEach(() => {
  1157. homeRestore.restore();
  1158. process.chdir(origCwd);
  1159. fs.rmSync(tmpHome, { recursive: true, force: true });
  1160. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1161. });
  1162. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1163. // The frontmatter a previous install wrote ahead of the marked block.
  1164. // `removeRulesEntry` recognizes it to decide whether the leftover .mdc
  1165. // is ours-to-delete or carries user content worth keeping.
  1166. const MDC_FRONTMATTER = [
  1167. '---',
  1168. 'description: CodeGraph MCP usage guide — when to use which tool',
  1169. 'alwaysApply: true',
  1170. '---',
  1171. '',
  1172. ].join('\n');
  1173. function plantLegacyRulesFile(extra = ''): void {
  1174. fs.mkdirSync(path.dirname(rulesFile()), { recursive: true });
  1175. fs.writeFileSync(rulesFile(), MDC_FRONTMATTER + LEGACY_BLOCK + '\n' + extra);
  1176. }
  1177. it('uninstall deletes a leftover codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1178. plantLegacyRulesFile();
  1179. expect(fs.existsSync(rulesFile())).toBe(true);
  1180. cursor.uninstall('local');
  1181. // The whole file — frontmatter included — is gone, not just the block.
  1182. expect(fs.existsSync(rulesFile())).toBe(false);
  1183. });
  1184. it('install self-heals a leftover codegraph.mdc (#529)', () => {
  1185. plantLegacyRulesFile();
  1186. const result = cursor.install('local', { autoAllow: true });
  1187. expect(fs.existsSync(rulesFile())).toBe(false);
  1188. expect(result.files.some((f) => f.path.endsWith('codegraph.mdc') && f.action === 'removed')).toBe(true);
  1189. });
  1190. it('uninstall preserves user content added outside the codegraph markers (strips only our block)', () => {
  1191. plantLegacyRulesFile('## My own rule\nkeep me\n');
  1192. cursor.uninstall('local');
  1193. expect(fs.existsSync(rulesFile())).toBe(true);
  1194. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1195. expect(after).toContain('keep me');
  1196. // Our tool-usage block is gone.
  1197. expect(after).not.toContain('codegraph_search');
  1198. expect(after).not.toContain('CODEGRAPH_START');
  1199. });
  1200. });
  1201. function listAllFiles(dir: string): string[] {
  1202. if (!fs.existsSync(dir)) return [];
  1203. const out: string[] = [];
  1204. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1205. const full = path.join(dir, entry.name);
  1206. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1207. else out.push(full);
  1208. }
  1209. return out;
  1210. }
  1211. // ---------------------------------------------------------------------------
  1212. // opencode global config path — XDG on every platform (#535)
  1213. //
  1214. // opencode resolves its config dir with `xdg-basedir`: XDG_CONFIG_HOME if
  1215. // set, else ~/.config — on ALL platforms, Windows included. It never reads
  1216. // %APPDATA%; we used to write there on Windows, so opencode never saw the
  1217. // entry. The suite-wide setHome() points APPDATA and XDG_CONFIG_HOME at the
  1218. // SAME directory (which is exactly how this bug stayed invisible), so these
  1219. // tests deliberately split them.
  1220. // ---------------------------------------------------------------------------
  1221. describe('Installer targets — opencode XDG config path (#535)', () => {
  1222. let tmpHome: string;
  1223. let tmpCwd: string;
  1224. let origCwd: string;
  1225. let homeRestore: { restore: () => void };
  1226. let appDataDir: string; // distinct from ~/.config, like real Windows
  1227. beforeEach(() => {
  1228. tmpHome = mkTmpDir('home');
  1229. tmpCwd = mkTmpDir('cwd');
  1230. origCwd = process.cwd();
  1231. process.chdir(tmpCwd);
  1232. homeRestore = setHome(tmpHome);
  1233. appDataDir = path.join(tmpHome, 'AppData', 'Roaming');
  1234. process.env.APPDATA = appDataDir; // realistic split: APPDATA ≠ ~/.config
  1235. delete process.env.XDG_CONFIG_HOME; // default resolution: ~/.config
  1236. });
  1237. afterEach(() => {
  1238. homeRestore.restore();
  1239. process.chdir(origCwd);
  1240. fs.rmSync(tmpHome, { recursive: true, force: true });
  1241. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1242. });
  1243. const xdgConfigFile = () => path.join(tmpHome, '.config', 'opencode', 'opencode.jsonc');
  1244. const legacyDir = () => path.join(appDataDir, 'opencode');
  1245. // NOTE: never match on an 'AppData' substring — on Windows os.tmpdir()
  1246. // itself lives under AppData\Local\Temp, so EVERY harness path contains
  1247. // it. Match on the legacy dir prefix instead.
  1248. const inLegacyDir = (p: string) => path.resolve(p).startsWith(path.resolve(legacyDir()) + path.sep);
  1249. it('global install writes to ~/.config/opencode, never %APPDATA% (#535)', () => {
  1250. const opencode = getTarget('opencode')!;
  1251. const result = opencode.install('global', { autoAllow: true });
  1252. const written = result.files.find((f) => f.path.endsWith('opencode.jsonc'))!;
  1253. expect(written.action).toBe('created');
  1254. expect(path.resolve(written.path)).toBe(path.resolve(xdgConfigFile()));
  1255. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1256. // Nothing of ours may land in the legacy location.
  1257. expect(fs.existsSync(legacyDir())).toBe(false);
  1258. });
  1259. it('greenfield: targets ~/.config/opencode even when the dir does not exist yet (#535)', () => {
  1260. // The rejected fallback design (#670) would send this install to
  1261. // %APPDATA% — where opencode would never find it. opencode creates
  1262. // ~/.config/opencode itself on first run; installing codegraph FIRST
  1263. // must land where opencode will look.
  1264. expect(fs.existsSync(path.join(tmpHome, '.config', 'opencode'))).toBe(false);
  1265. const opencode = getTarget('opencode')!;
  1266. const result = opencode.install('global', { autoAllow: true });
  1267. expect(path.resolve(result.files[0]!.path)).toBe(path.resolve(xdgConfigFile()));
  1268. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1269. expect(fs.existsSync(legacyDir())).toBe(false);
  1270. });
  1271. it('honors XDG_CONFIG_HOME for the global path, like opencode does', () => {
  1272. const custom = path.join(tmpHome, 'xdg-custom');
  1273. process.env.XDG_CONFIG_HOME = custom;
  1274. const opencode = getTarget('opencode')!;
  1275. const result = opencode.install('global', { autoAllow: true });
  1276. expect(path.resolve(result.files[0]!.path))
  1277. .toBe(path.resolve(path.join(custom, 'opencode', 'opencode.jsonc')));
  1278. });
  1279. it('install self-heals a pre-#535 %APPDATA% entry, preserving siblings and comments', () => {
  1280. // A previous codegraph version wrote into %APPDATA%/opencode. The user
  1281. // also has another MCP server and a comment there — those must survive.
  1282. fs.mkdirSync(legacyDir(), { recursive: true });
  1283. fs.writeFileSync(path.join(legacyDir(), 'opencode.jsonc'), [
  1284. '{',
  1285. ' // my servers',
  1286. ' "$schema": "https://opencode.ai/config.json",',
  1287. ' "mcp": {',
  1288. ' "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true },',
  1289. ' "other": { "type": "local", "command": ["other"], "enabled": true }',
  1290. ' }',
  1291. '}',
  1292. '',
  1293. ].join('\n'));
  1294. fs.writeFileSync(path.join(legacyDir(), 'AGENTS.md'), LEGACY_BLOCK + '\n');
  1295. const opencode = getTarget('opencode')!;
  1296. const result = opencode.install('global', { autoAllow: true });
  1297. // New entry in the right place…
  1298. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1299. // …stale entry swept out of the legacy file, siblings + comment intact.
  1300. const legacyText = fs.readFileSync(path.join(legacyDir(), 'opencode.jsonc'), 'utf-8');
  1301. expect(legacyText).not.toContain('codegraph');
  1302. expect(legacyText).toContain('"other"');
  1303. expect(legacyText).toContain('// my servers');
  1304. // …and the legacy AGENTS.md — block-only, so emptied — removed outright
  1305. // (removeMarkedSection unlinks a file it leaves empty).
  1306. expect(fs.existsSync(path.join(legacyDir(), 'AGENTS.md'))).toBe(false);
  1307. // Both cleanups are reported.
  1308. const removed = result.files.filter((f) => f.action === 'removed').map((f) => f.path);
  1309. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('opencode.jsonc'))).toBe(true);
  1310. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('AGENTS.md'))).toBe(true);
  1311. });
  1312. it('uninstall sweeps the legacy %APPDATA% entry too (no prior re-install needed)', () => {
  1313. // A user on the broken version goes straight to `codegraph uninstall`:
  1314. // the only entry that exists is the stale %APPDATA% one.
  1315. fs.mkdirSync(legacyDir(), { recursive: true });
  1316. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1317. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1318. const opencode = getTarget('opencode')!;
  1319. const result = opencode.uninstall('global');
  1320. expect(fs.readFileSync(path.join(legacyDir(), 'opencode.json'), 'utf-8')).not.toContain('codegraph');
  1321. expect(result.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1322. });
  1323. it('install after install sweeps only once — second run reports no legacy changes', () => {
  1324. fs.mkdirSync(legacyDir(), { recursive: true });
  1325. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1326. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1327. const opencode = getTarget('opencode')!;
  1328. const first = opencode.install('global', { autoAllow: true });
  1329. expect(first.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1330. const second = opencode.install('global', { autoAllow: true });
  1331. expect(second.files.some((f) => inLegacyDir(f.path))).toBe(false);
  1332. expect(second.files.find((f) => f.path.endsWith('opencode.jsonc'))!.action).toBe('unchanged');
  1333. });
  1334. it('detects opencode as installed from a legacy-only %APPDATA% dir (so install can heal it)', () => {
  1335. fs.mkdirSync(legacyDir(), { recursive: true });
  1336. const opencode = getTarget('opencode')!;
  1337. expect(opencode.detect('global').installed).toBe(true);
  1338. // But configuration state is read from the REAL path only.
  1339. expect(opencode.detect('global').alreadyConfigured).toBe(false);
  1340. });
  1341. });