installer-targets.test.ts 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  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. // Platform-aware since #1466: Windows writes `codegraph.cmd prompt-hook`
  993. // (Git Bash applies no PATHEXT, so the bare form is exit 127 there), and
  994. // install self-heals the other platform's spelling in place.
  995. const HOOK_CMD = process.platform === 'win32' ? 'codegraph.cmd prompt-hook' : 'codegraph prompt-hook';
  996. const OTHER_PLATFORM_HOOK_CMD = process.platform === 'win32' ? 'codegraph prompt-hook' : 'codegraph.cmd prompt-hook';
  997. const promptCommands = (s: any): string[] =>
  998. (s.hooks?.UserPromptSubmit ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  999. it('claude: install with promptHook:true writes the UserPromptSubmit hook (alongside permissions)', () => {
  1000. const claude = getTarget('claude')!;
  1001. claude.install('global', { autoAllow: true, promptHook: true });
  1002. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1003. expect(promptCommands(s)).toContain(HOOK_CMD);
  1004. expect(s.permissions?.allow).toContain('mcp__codegraph__*');
  1005. });
  1006. it('claude: install without promptHook does NOT add the hook', () => {
  1007. const claude = getTarget('claude')!;
  1008. claude.install('global', { autoAllow: true });
  1009. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1010. expect(promptCommands(s)).not.toContain(HOOK_CMD);
  1011. });
  1012. it('claude: install with promptHook:true is idempotent (no duplicate, byte-identical re-run)', () => {
  1013. const claude = getTarget('claude')!;
  1014. const file = path.join(tmpHome, '.claude', 'settings.json');
  1015. claude.install('global', { autoAllow: true, promptHook: true });
  1016. const first = fs.readFileSync(file, 'utf-8');
  1017. claude.install('global', { autoAllow: true, promptHook: true });
  1018. expect(fs.readFileSync(file, 'utf-8')).toBe(first);
  1019. const s = JSON.parse(first);
  1020. expect(promptCommands(s).filter((c: string) => c === HOOK_CMD)).toHaveLength(1);
  1021. });
  1022. it('claude: install with promptHook:false strips a hook a prior install wrote (opt-out round-trips)', () => {
  1023. const claude = getTarget('claude')!;
  1024. claude.install('global', { autoAllow: true, promptHook: true });
  1025. claude.install('global', { autoAllow: true, promptHook: false });
  1026. const s = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude', 'settings.json'), 'utf-8'));
  1027. expect(promptCommands(s)).not.toContain(HOOK_CMD);
  1028. });
  1029. it('claude: writePromptHookEntry preserves a sibling UserPromptSubmit hook', () => {
  1030. const file = seedSettings('global', {
  1031. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: 'my-own-hook' }] }] },
  1032. });
  1033. expect(writePromptHookEntry('global').action).toBe('updated');
  1034. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1035. expect(promptCommands(s)).toEqual(['my-own-hook', HOOK_CMD]);
  1036. });
  1037. it('claude: writePromptHookEntry migrates the other platform\'s spelling in place (#1466 self-heal)', () => {
  1038. const file = seedSettings('global', {
  1039. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: OTHER_PLATFORM_HOOK_CMD }] }] },
  1040. });
  1041. expect(writePromptHookEntry('global').action).toBe('updated');
  1042. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1043. expect(promptCommands(s)).toEqual([HOOK_CMD]);
  1044. // A re-run after migration is byte-identical.
  1045. const healed = fs.readFileSync(file, 'utf-8');
  1046. expect(writePromptHookEntry('global').action).toBe('unchanged');
  1047. expect(fs.readFileSync(file, 'utf-8')).toBe(healed);
  1048. });
  1049. it('claude: writePromptHookEntry leaves an npx-form hook untouched (no duplicate, no rewrite)', () => {
  1050. const npxCmd = 'npx @colbymchenry/codegraph prompt-hook';
  1051. const file = seedSettings('global', {
  1052. hooks: { UserPromptSubmit: [{ hooks: [{ type: 'command', command: npxCmd }] }] },
  1053. });
  1054. expect(writePromptHookEntry('global').action).toBe('unchanged');
  1055. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1056. expect(promptCommands(s)).toEqual([npxCmd]);
  1057. });
  1058. it('claude: uninstall removes the prompt hook but keeps the user\'s sibling', () => {
  1059. const file = seedSettings('global', {
  1060. hooks: {
  1061. UserPromptSubmit: [
  1062. { hooks: [{ type: 'command', command: HOOK_CMD }] },
  1063. { hooks: [{ type: 'command', command: 'my-own-hook' }] },
  1064. ],
  1065. },
  1066. });
  1067. getTarget('claude')!.uninstall('global');
  1068. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1069. expect(promptCommands(s)).toEqual(['my-own-hook']);
  1070. });
  1071. it('claude: removePromptHookEntry removes the other platform\'s spelling too', () => {
  1072. const file = seedSettings('global', {
  1073. hooks: {
  1074. UserPromptSubmit: [{ hooks: [{ type: 'command', command: OTHER_PLATFORM_HOOK_CMD }] }],
  1075. },
  1076. });
  1077. expect(removePromptHookEntry('global').action).toBe('removed');
  1078. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1079. expect(promptCommands(s)).toEqual([]);
  1080. });
  1081. it('claude: removePromptHookEntry leaves the legacy auto-sync hook untouched', () => {
  1082. const file = seedSettings('global', {
  1083. hooks: {
  1084. UserPromptSubmit: [{ hooks: [{ type: 'command', command: HOOK_CMD }] }],
  1085. Stop: [{ hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] }],
  1086. },
  1087. });
  1088. expect(removePromptHookEntry('global').action).toBe('removed');
  1089. const s = JSON.parse(fs.readFileSync(file, 'utf-8'));
  1090. expect(promptCommands(s)).not.toContain(HOOK_CMD);
  1091. const stopCmds = (s.hooks?.Stop ?? []).flatMap((g: any) => (g.hooks ?? []).map((h: any) => h.command));
  1092. expect(stopCmds).toContain('codegraph sync-if-dirty');
  1093. });
  1094. });
  1095. describe('Installer targets — registry', () => {
  1096. it('getTarget returns the right target for each id', () => {
  1097. expect(getTarget('claude')?.id).toBe('claude');
  1098. expect(getTarget('cursor')?.id).toBe('cursor');
  1099. expect(getTarget('codex')?.id).toBe('codex');
  1100. expect(getTarget('opencode')?.id).toBe('opencode');
  1101. expect(getTarget('hermes')?.id).toBe('hermes');
  1102. expect(getTarget('gemini')?.id).toBe('gemini');
  1103. expect(getTarget('antigravity')?.id).toBe('antigravity');
  1104. expect(getTarget('kiro')?.id).toBe('kiro');
  1105. expect(getTarget('not-a-real-target')).toBeUndefined();
  1106. });
  1107. it('resolveTargetFlag handles auto/all/none/csv', () => {
  1108. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  1109. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  1110. const csv = resolveTargetFlag('claude,cursor', 'global');
  1111. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  1112. });
  1113. it('resolveTargetFlag throws on unknown id', () => {
  1114. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  1115. });
  1116. });
  1117. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  1118. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  1119. const block = buildTomlTable('mcp_servers.codegraph', {
  1120. command: 'codegraph',
  1121. args: ['serve', '--mcp'],
  1122. });
  1123. expect(block).toContain('[mcp_servers.codegraph]');
  1124. expect(block).toContain('command = "codegraph"');
  1125. expect(block).toContain('args = ["serve", "--mcp"]');
  1126. });
  1127. it('upsert inserts into empty content', () => {
  1128. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1129. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1130. expect(action).toBe('inserted');
  1131. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  1132. });
  1133. it('upsert is idempotent — second call returns unchanged', () => {
  1134. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1135. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  1136. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  1137. expect(second.action).toBe('unchanged');
  1138. expect(second.content).toBe(first.content);
  1139. });
  1140. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  1141. const existing = [
  1142. '[other_table]',
  1143. 'foo = "bar"',
  1144. '',
  1145. '[mcp_servers.codegraph]',
  1146. 'command = "old-codegraph"',
  1147. 'args = ["old"]',
  1148. '',
  1149. '[zzz]',
  1150. 'baz = "qux"',
  1151. '',
  1152. ].join('\n');
  1153. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  1154. command: 'codegraph',
  1155. args: ['serve', '--mcp'],
  1156. });
  1157. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  1158. expect(action).toBe('replaced');
  1159. expect(content).toContain('[other_table]');
  1160. expect(content).toContain('foo = "bar"');
  1161. expect(content).toContain('[zzz]');
  1162. expect(content).toContain('baz = "qux"');
  1163. expect(content).toContain('command = "codegraph"');
  1164. expect(content).not.toContain('old-codegraph');
  1165. });
  1166. it('removeTomlTable strips the block and preserves siblings', () => {
  1167. const existing = [
  1168. '[other_table]',
  1169. 'foo = "bar"',
  1170. '',
  1171. '[mcp_servers.codegraph]',
  1172. 'command = "codegraph"',
  1173. 'args = ["serve"]',
  1174. ].join('\n');
  1175. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1176. expect(action).toBe('removed');
  1177. expect(content).toContain('[other_table]');
  1178. expect(content).toContain('foo = "bar"');
  1179. expect(content).not.toContain('mcp_servers.codegraph');
  1180. });
  1181. it('removeTomlTable on missing table returns not-found, no content change', () => {
  1182. const existing = '[other]\nfoo = "bar"\n';
  1183. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1184. expect(action).toBe('not-found');
  1185. expect(content).toBe(existing);
  1186. });
  1187. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  1188. const existing = [
  1189. '[[foo]]',
  1190. 'name = "a"',
  1191. '',
  1192. '[[foo]]',
  1193. 'name = "b"',
  1194. '',
  1195. ].join('\n');
  1196. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  1197. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1198. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  1199. expect(content).toContain('[mcp_servers.codegraph]');
  1200. });
  1201. it('upsert replaces the managed table without consuming trailing array-of-tables siblings', () => {
  1202. const historyTables = [
  1203. '[[history]]',
  1204. 'id = 1',
  1205. 'note = "keep first"',
  1206. '',
  1207. '[[history]]',
  1208. 'id = 2',
  1209. 'note = "keep second"',
  1210. '',
  1211. ].join('\n');
  1212. const existing = [
  1213. '[mcp_servers.codegraph]',
  1214. 'command = "old-codegraph"',
  1215. 'args = ["old"]',
  1216. '',
  1217. historyTables,
  1218. ].join('\n');
  1219. const block = buildTomlTable('mcp_servers.codegraph', {
  1220. command: 'codegraph',
  1221. args: ['serve', '--mcp'],
  1222. });
  1223. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1224. expect(action).toBe('replaced');
  1225. expect(content).toBe(`${block}\n\n${historyTables}`);
  1226. });
  1227. it('remove preserves trailing array-of-tables siblings byte-for-byte', () => {
  1228. const historyTables = [
  1229. '[[history]]',
  1230. 'id = 1',
  1231. 'note = "keep first"',
  1232. '',
  1233. '[[history]]',
  1234. 'id = 2',
  1235. 'note = "keep second"',
  1236. '',
  1237. ].join('\n');
  1238. const existing = [
  1239. '[mcp_servers.codegraph]',
  1240. 'command = "codegraph"',
  1241. 'args = ["serve", "--mcp"]',
  1242. '',
  1243. historyTables,
  1244. ].join('\n');
  1245. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  1246. expect(action).toBe('removed');
  1247. expect(content).toBe(historyTables);
  1248. });
  1249. it.each([
  1250. ['table', '[ mcp_servers.other ]'],
  1251. ['array-of-tables', '[[ history ]]'],
  1252. ])('preserves a trailing %s header with inner whitespace', (_kind, siblingHeader) => {
  1253. const siblingTable = `${siblingHeader}\nvalue = "keep"\n`;
  1254. const existing = [
  1255. '[mcp_servers.codegraph]',
  1256. 'command = "old-codegraph"',
  1257. 'args = ["old"]',
  1258. '',
  1259. siblingTable,
  1260. ].join('\n');
  1261. const block = buildTomlTable('mcp_servers.codegraph', {
  1262. command: 'codegraph',
  1263. args: ['serve', '--mcp'],
  1264. });
  1265. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1266. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1267. expect(upserted.content).toBe(`${block}\n\n${siblingTable}`);
  1268. expect(removed.content).toBe(siblingTable);
  1269. });
  1270. it.each([
  1271. ['basic', '"""'],
  1272. ['literal', "'''"],
  1273. ])('ignores header-shaped text inside a multiline %s string', (_kind, delimiter) => {
  1274. const historyTable = '[[history]]\nid = 1\n';
  1275. const existing = [
  1276. '[mcp_servers.codegraph]',
  1277. 'command = "old-codegraph"',
  1278. 'args = [',
  1279. ` ${delimiter}first line`,
  1280. '[[not-a-table]]',
  1281. `last line${delimiter},`,
  1282. ' "serve",',
  1283. ']',
  1284. '',
  1285. historyTable,
  1286. ].join('\n');
  1287. const block = buildTomlTable('mcp_servers.codegraph', {
  1288. command: 'codegraph',
  1289. args: ['serve', '--mcp'],
  1290. });
  1291. const upserted = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  1292. const removed = removeTomlTable(existing, 'mcp_servers.codegraph');
  1293. expect(upserted.content).toBe(`${block}\n\n${historyTable}`);
  1294. expect(removed.content).toBe(historyTable);
  1295. });
  1296. });
  1297. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  1298. let tmpHome: string;
  1299. let tmpCwd: string;
  1300. let origCwd: string;
  1301. let homeRestore: { restore: () => void };
  1302. beforeEach(() => {
  1303. tmpHome = mkTmpDir('un-home');
  1304. tmpCwd = mkTmpDir('un-cwd');
  1305. origCwd = process.cwd();
  1306. process.chdir(tmpCwd);
  1307. homeRestore = setHome(tmpHome);
  1308. });
  1309. afterEach(() => {
  1310. homeRestore.restore();
  1311. process.chdir(origCwd);
  1312. fs.rmSync(tmpHome, { recursive: true, force: true });
  1313. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1314. });
  1315. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  1316. for (const t of ALL_TARGETS) {
  1317. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1318. }
  1319. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1320. for (const t of ALL_TARGETS) {
  1321. const r = reports.find((x) => x.id === t.id)!;
  1322. expect(r.status).toBe('removed');
  1323. expect(r.removedPaths.length).toBeGreaterThan(0);
  1324. // The actual config is gone afterward.
  1325. expect(t.detect('global').alreadyConfigured).toBe(false);
  1326. }
  1327. });
  1328. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  1329. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1330. for (const r of reports) {
  1331. expect(r.status).toBe('not-configured');
  1332. expect(r.removedPaths).toEqual([]);
  1333. }
  1334. });
  1335. it('reports removed only for agents that were actually configured', () => {
  1336. // Install on Claude only; the rest stay untouched.
  1337. getTarget('claude')!.install('global', { autoAllow: true });
  1338. const reports = uninstallTargets(ALL_TARGETS, 'global');
  1339. const claude = reports.find((r) => r.id === 'claude')!;
  1340. expect(claude.status).toBe('removed');
  1341. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  1342. for (const r of reports.filter((x) => x.id !== 'claude')) {
  1343. expect(r.status).toBe('not-configured');
  1344. }
  1345. });
  1346. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  1347. const reports = uninstallTargets(ALL_TARGETS, 'local');
  1348. for (const t of ALL_TARGETS) {
  1349. const r = reports.find((x) => x.id === t.id)!;
  1350. if (t.supportsLocation('local')) {
  1351. expect(r.status).toBe('not-configured');
  1352. } else {
  1353. expect(r.status).toBe('unsupported');
  1354. expect(r.removedPaths).toEqual([]);
  1355. expect(r.notes[0]).toMatch(/global-only/);
  1356. }
  1357. }
  1358. });
  1359. it('is idempotent — a second sweep finds nothing left to remove', () => {
  1360. for (const t of ALL_TARGETS) {
  1361. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1362. }
  1363. const first = uninstallTargets(ALL_TARGETS, 'global');
  1364. expect(first.some((r) => r.status === 'removed')).toBe(true);
  1365. const second = uninstallTargets(ALL_TARGETS, 'global');
  1366. for (const r of second) {
  1367. expect(r.status).toBe('not-configured');
  1368. expect(r.removedPaths).toEqual([]);
  1369. }
  1370. });
  1371. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  1372. getTarget('claude')!.install('global', { autoAllow: true });
  1373. getTarget('cursor')!.install('global', { autoAllow: true });
  1374. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  1375. expect(reports.map((r) => r.id)).toEqual(['claude']);
  1376. expect(reports[0].status).toBe('removed');
  1377. // Cursor was not in the subset — still configured.
  1378. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  1379. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  1380. });
  1381. });
  1382. describe('Installer — refreshTargets sweep (codegraph install --refresh)', () => {
  1383. let tmpHome: string;
  1384. let tmpCwd: string;
  1385. let origCwd: string;
  1386. let homeRestore: { restore: () => void };
  1387. beforeEach(() => {
  1388. tmpHome = mkTmpDir('rf-home');
  1389. tmpCwd = mkTmpDir('rf-cwd');
  1390. origCwd = process.cwd();
  1391. process.chdir(tmpCwd);
  1392. homeRestore = setHome(tmpHome);
  1393. });
  1394. afterEach(() => {
  1395. homeRestore.restore();
  1396. process.chdir(origCwd);
  1397. fs.rmSync(tmpHome, { recursive: true, force: true });
  1398. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1399. });
  1400. it('rewrites a stale instructions block a previous version left, and reports refreshed', () => {
  1401. const claude = getTarget('claude')!;
  1402. claude.install('global', { autoAllow: true });
  1403. // Simulate the file as an old install left it: same markers, the old
  1404. // multi-tool wording.
  1405. const claudeMd = path.join(tmpHome, '.claude', 'CLAUDE.md');
  1406. fs.writeFileSync(claudeMd, LEGACY_BLOCK + '\n');
  1407. const reports = refreshTargets([claude], 'global');
  1408. expect(reports[0].status).toBe('refreshed');
  1409. expect(reports[0].changedPaths).toContain(claudeMd);
  1410. const md = fs.readFileSync(claudeMd, 'utf-8');
  1411. expect(md).not.toContain('codegraph_search');
  1412. expect(md).toContain('codegraph_explore');
  1413. });
  1414. it('never performs a first install — unconfigured agents stay untouched', () => {
  1415. const reports = refreshTargets(ALL_TARGETS, 'global');
  1416. for (const t of ALL_TARGETS) {
  1417. const r = reports.find((x) => x.id === t.id)!;
  1418. expect(r.status).toBe(t.supportsLocation('global') ? 'not-configured' : 'unsupported');
  1419. expect(r.changedPaths).toEqual([]);
  1420. expect(t.detect('global').alreadyConfigured).toBe(false);
  1421. }
  1422. });
  1423. it('preserves the user\'s permission choices (refresh never writes permissions)', () => {
  1424. const claude = getTarget('claude')!;
  1425. claude.install('global', { autoAllow: true });
  1426. // The user has since trimmed the allowlist by hand.
  1427. const settingsPath = path.join(tmpHome, '.claude', 'settings.json');
  1428. const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1429. settings.permissions.allow = [];
  1430. fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
  1431. refreshTargets([claude], 'global');
  1432. const after = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'));
  1433. expect(after.permissions.allow).toEqual([]);
  1434. });
  1435. it('is idempotent — a second sweep on a current machine reports unchanged everywhere', () => {
  1436. for (const t of ALL_TARGETS) {
  1437. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  1438. }
  1439. const first = refreshTargets(ALL_TARGETS, 'global');
  1440. // Fresh installs are already current, so even the first sweep may be
  1441. // all-unchanged; what matters is the second definitely is.
  1442. const second = refreshTargets(ALL_TARGETS, 'global');
  1443. for (const r of [...first, ...second]) {
  1444. expect(['unchanged', 'refreshed']).toContain(r.status);
  1445. }
  1446. for (const r of second) {
  1447. expect(r.status).toBe('unchanged');
  1448. expect(r.changedPaths).toEqual([]);
  1449. }
  1450. });
  1451. });
  1452. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  1453. let tmpHome: string;
  1454. let tmpCwd: string;
  1455. let origCwd: string;
  1456. let homeRestore: { restore: () => void };
  1457. const cursor = getTarget('cursor')!;
  1458. beforeEach(() => {
  1459. tmpHome = mkTmpDir('cur-home');
  1460. tmpCwd = mkTmpDir('cur-cwd');
  1461. origCwd = process.cwd();
  1462. process.chdir(tmpCwd);
  1463. homeRestore = setHome(tmpHome);
  1464. });
  1465. afterEach(() => {
  1466. homeRestore.restore();
  1467. process.chdir(origCwd);
  1468. fs.rmSync(tmpHome, { recursive: true, force: true });
  1469. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1470. });
  1471. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  1472. // The frontmatter a previous install wrote ahead of the marked block.
  1473. // `removeRulesEntry` recognizes it to decide whether the leftover .mdc
  1474. // is ours-to-delete or carries user content worth keeping.
  1475. const MDC_FRONTMATTER = [
  1476. '---',
  1477. 'description: CodeGraph MCP usage guide — when to use which tool',
  1478. 'alwaysApply: true',
  1479. '---',
  1480. '',
  1481. ].join('\n');
  1482. function plantLegacyRulesFile(extra = ''): void {
  1483. fs.mkdirSync(path.dirname(rulesFile()), { recursive: true });
  1484. fs.writeFileSync(rulesFile(), MDC_FRONTMATTER + LEGACY_BLOCK + '\n' + extra);
  1485. }
  1486. it('uninstall deletes a leftover codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  1487. plantLegacyRulesFile();
  1488. expect(fs.existsSync(rulesFile())).toBe(true);
  1489. cursor.uninstall('local');
  1490. // The whole file — frontmatter included — is gone, not just the block.
  1491. expect(fs.existsSync(rulesFile())).toBe(false);
  1492. });
  1493. it('install self-heals a leftover codegraph.mdc (#529)', () => {
  1494. plantLegacyRulesFile();
  1495. const result = cursor.install('local', { autoAllow: true });
  1496. expect(fs.existsSync(rulesFile())).toBe(false);
  1497. expect(result.files.some((f) => f.path.endsWith('codegraph.mdc') && f.action === 'removed')).toBe(true);
  1498. });
  1499. it('uninstall preserves user content added outside the codegraph markers (strips only our block)', () => {
  1500. plantLegacyRulesFile('## My own rule\nkeep me\n');
  1501. cursor.uninstall('local');
  1502. expect(fs.existsSync(rulesFile())).toBe(true);
  1503. const after = fs.readFileSync(rulesFile(), 'utf-8');
  1504. expect(after).toContain('keep me');
  1505. // Our tool-usage block is gone.
  1506. expect(after).not.toContain('codegraph_search');
  1507. expect(after).not.toContain('CODEGRAPH_START');
  1508. });
  1509. });
  1510. function listAllFiles(dir: string): string[] {
  1511. if (!fs.existsSync(dir)) return [];
  1512. const out: string[] = [];
  1513. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  1514. const full = path.join(dir, entry.name);
  1515. if (entry.isDirectory()) out.push(...listAllFiles(full));
  1516. else out.push(full);
  1517. }
  1518. return out;
  1519. }
  1520. // ---------------------------------------------------------------------------
  1521. // opencode global config path — XDG on every platform (#535)
  1522. //
  1523. // opencode resolves its config dir with `xdg-basedir`: XDG_CONFIG_HOME if
  1524. // set, else ~/.config — on ALL platforms, Windows included. It never reads
  1525. // %APPDATA%; we used to write there on Windows, so opencode never saw the
  1526. // entry. The suite-wide setHome() points APPDATA and XDG_CONFIG_HOME at the
  1527. // SAME directory (which is exactly how this bug stayed invisible), so these
  1528. // tests deliberately split them.
  1529. // ---------------------------------------------------------------------------
  1530. describe('Installer targets — opencode XDG config path (#535)', () => {
  1531. let tmpHome: string;
  1532. let tmpCwd: string;
  1533. let origCwd: string;
  1534. let homeRestore: { restore: () => void };
  1535. let appDataDir: string; // distinct from ~/.config, like real Windows
  1536. beforeEach(() => {
  1537. tmpHome = mkTmpDir('home');
  1538. tmpCwd = mkTmpDir('cwd');
  1539. origCwd = process.cwd();
  1540. process.chdir(tmpCwd);
  1541. homeRestore = setHome(tmpHome);
  1542. appDataDir = path.join(tmpHome, 'AppData', 'Roaming');
  1543. process.env.APPDATA = appDataDir; // realistic split: APPDATA ≠ ~/.config
  1544. delete process.env.XDG_CONFIG_HOME; // default resolution: ~/.config
  1545. });
  1546. afterEach(() => {
  1547. homeRestore.restore();
  1548. process.chdir(origCwd);
  1549. fs.rmSync(tmpHome, { recursive: true, force: true });
  1550. fs.rmSync(tmpCwd, { recursive: true, force: true });
  1551. });
  1552. const xdgConfigFile = () => path.join(tmpHome, '.config', 'opencode', 'opencode.jsonc');
  1553. const legacyDir = () => path.join(appDataDir, 'opencode');
  1554. // NOTE: never match on an 'AppData' substring — on Windows os.tmpdir()
  1555. // itself lives under AppData\Local\Temp, so EVERY harness path contains
  1556. // it. Match on the legacy dir prefix instead.
  1557. const inLegacyDir = (p: string) => path.resolve(p).startsWith(path.resolve(legacyDir()) + path.sep);
  1558. it('global install writes to ~/.config/opencode, never %APPDATA% (#535)', () => {
  1559. const opencode = getTarget('opencode')!;
  1560. const result = opencode.install('global', { autoAllow: true });
  1561. const written = result.files.find((f) => f.path.endsWith('opencode.jsonc'))!;
  1562. expect(written.action).toBe('created');
  1563. expect(path.resolve(written.path)).toBe(path.resolve(xdgConfigFile()));
  1564. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1565. // Nothing of ours may land in the legacy location.
  1566. expect(fs.existsSync(legacyDir())).toBe(false);
  1567. });
  1568. it('greenfield: targets ~/.config/opencode even when the dir does not exist yet (#535)', () => {
  1569. // The rejected fallback design (#670) would send this install to
  1570. // %APPDATA% — where opencode would never find it. opencode creates
  1571. // ~/.config/opencode itself on first run; installing codegraph FIRST
  1572. // must land where opencode will look.
  1573. expect(fs.existsSync(path.join(tmpHome, '.config', 'opencode'))).toBe(false);
  1574. const opencode = getTarget('opencode')!;
  1575. const result = opencode.install('global', { autoAllow: true });
  1576. expect(path.resolve(result.files[0]!.path)).toBe(path.resolve(xdgConfigFile()));
  1577. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1578. expect(fs.existsSync(legacyDir())).toBe(false);
  1579. });
  1580. it('honors XDG_CONFIG_HOME for the global path, like opencode does', () => {
  1581. const custom = path.join(tmpHome, 'xdg-custom');
  1582. process.env.XDG_CONFIG_HOME = custom;
  1583. const opencode = getTarget('opencode')!;
  1584. const result = opencode.install('global', { autoAllow: true });
  1585. expect(path.resolve(result.files[0]!.path))
  1586. .toBe(path.resolve(path.join(custom, 'opencode', 'opencode.jsonc')));
  1587. });
  1588. it('install self-heals a pre-#535 %APPDATA% entry, preserving siblings and comments', () => {
  1589. // A previous codegraph version wrote into %APPDATA%/opencode. The user
  1590. // also has another MCP server and a comment there — those must survive.
  1591. fs.mkdirSync(legacyDir(), { recursive: true });
  1592. fs.writeFileSync(path.join(legacyDir(), 'opencode.jsonc'), [
  1593. '{',
  1594. ' // my servers',
  1595. ' "$schema": "https://opencode.ai/config.json",',
  1596. ' "mcp": {',
  1597. ' "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true },',
  1598. ' "other": { "type": "local", "command": ["other"], "enabled": true }',
  1599. ' }',
  1600. '}',
  1601. '',
  1602. ].join('\n'));
  1603. fs.writeFileSync(path.join(legacyDir(), 'AGENTS.md'), LEGACY_BLOCK + '\n');
  1604. const opencode = getTarget('opencode')!;
  1605. const result = opencode.install('global', { autoAllow: true });
  1606. // New entry in the right place…
  1607. expect(fs.existsSync(xdgConfigFile())).toBe(true);
  1608. // …stale entry swept out of the legacy file, siblings + comment intact.
  1609. const legacyText = fs.readFileSync(path.join(legacyDir(), 'opencode.jsonc'), 'utf-8');
  1610. expect(legacyText).not.toContain('codegraph');
  1611. expect(legacyText).toContain('"other"');
  1612. expect(legacyText).toContain('// my servers');
  1613. // …and the legacy AGENTS.md — block-only, so emptied — removed outright
  1614. // (removeMarkedSection unlinks a file it leaves empty).
  1615. expect(fs.existsSync(path.join(legacyDir(), 'AGENTS.md'))).toBe(false);
  1616. // Both cleanups are reported.
  1617. const removed = result.files.filter((f) => f.action === 'removed').map((f) => f.path);
  1618. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('opencode.jsonc'))).toBe(true);
  1619. expect(removed.some((p) => inLegacyDir(p) && p.endsWith('AGENTS.md'))).toBe(true);
  1620. });
  1621. it('uninstall sweeps the legacy %APPDATA% entry too (no prior re-install needed)', () => {
  1622. // A user on the broken version goes straight to `codegraph uninstall`:
  1623. // the only entry that exists is the stale %APPDATA% one.
  1624. fs.mkdirSync(legacyDir(), { recursive: true });
  1625. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1626. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1627. const opencode = getTarget('opencode')!;
  1628. const result = opencode.uninstall('global');
  1629. expect(fs.readFileSync(path.join(legacyDir(), 'opencode.json'), 'utf-8')).not.toContain('codegraph');
  1630. expect(result.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1631. });
  1632. it('install after install sweeps only once — second run reports no legacy changes', () => {
  1633. fs.mkdirSync(legacyDir(), { recursive: true });
  1634. fs.writeFileSync(path.join(legacyDir(), 'opencode.json'),
  1635. '{\n "mcp": {\n "codegraph": { "type": "local", "command": ["codegraph", "serve", "--mcp"], "enabled": true }\n }\n}\n');
  1636. const opencode = getTarget('opencode')!;
  1637. const first = opencode.install('global', { autoAllow: true });
  1638. expect(first.files.some((f) => f.action === 'removed' && inLegacyDir(f.path))).toBe(true);
  1639. const second = opencode.install('global', { autoAllow: true });
  1640. expect(second.files.some((f) => inLegacyDir(f.path))).toBe(false);
  1641. expect(second.files.find((f) => f.path.endsWith('opencode.jsonc'))!.action).toBe('unchanged');
  1642. });
  1643. it('detects opencode as installed from a legacy-only %APPDATA% dir (so install can heal it)', () => {
  1644. fs.mkdirSync(legacyDir(), { recursive: true });
  1645. const opencode = getTarget('opencode')!;
  1646. expect(opencode.detect('global').installed).toBe(true);
  1647. // But configuration state is read from the REAL path only.
  1648. expect(opencode.detect('global').alreadyConfigured).toBe(false);
  1649. });
  1650. });