installer-targets.test.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. /**
  2. * Multi-target installer tests.
  3. *
  4. * Each `AgentTarget` is exercised against the same contract:
  5. * - `install` writes the expected files
  6. * - re-running `install` is byte-identical (idempotent)
  7. * - sibling MCP servers / unrelated config is preserved
  8. * - `uninstall` reverses `install`
  9. * - `printConfig` returns parseable, non-empty content
  10. *
  11. * For agent-config destinations we redirect HOME to a tmpdir via
  12. * `os.homedir` spying, and CWD via `process.chdir` — same pattern as
  13. * the legacy `installer.test.ts`. No real `~/.claude/` etc. ever
  14. * touched.
  15. */
  16. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  17. import * as fs from 'fs';
  18. import * as path from 'path';
  19. import * as os from 'os';
  20. import { ALL_TARGETS, getTarget, resolveTargetFlag } from '../src/installer/targets/registry';
  21. import { uninstallTargets } from '../src/installer';
  22. import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  23. import { cleanupLegacyHooks } from '../src/installer/targets/claude';
  24. function mkTmpDir(label: string): string {
  25. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
  26. }
  27. // `os.homedir` is non-configurable on Node, so we redirect it via the
  28. // `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
  29. // `os.homedir()` reads first. Same trick the rest of the suite uses
  30. // when it needs a mock home.
  31. function setHome(dir: string): { restore: () => void } {
  32. const prev = {
  33. HOME: process.env.HOME,
  34. USERPROFILE: process.env.USERPROFILE,
  35. APPDATA: process.env.APPDATA,
  36. XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
  37. HERMES_HOME: process.env.HERMES_HOME,
  38. };
  39. process.env.HOME = dir;
  40. process.env.USERPROFILE = dir;
  41. process.env.APPDATA = path.join(dir, '.config');
  42. process.env.XDG_CONFIG_HOME = path.join(dir, '.config');
  43. delete process.env.HERMES_HOME;
  44. return {
  45. restore() {
  46. if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
  47. if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
  48. if (prev.APPDATA === undefined) delete process.env.APPDATA; else process.env.APPDATA = prev.APPDATA;
  49. if (prev.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = prev.XDG_CONFIG_HOME;
  50. if (prev.HERMES_HOME === undefined) delete process.env.HERMES_HOME; else process.env.HERMES_HOME = prev.HERMES_HOME;
  51. },
  52. };
  53. }
  54. describe('Installer targets — contract', () => {
  55. let tmpHome: string;
  56. let tmpCwd: string;
  57. let origCwd: string;
  58. let homeRestore: { restore: () => void };
  59. beforeEach(() => {
  60. tmpHome = mkTmpDir('home');
  61. tmpCwd = mkTmpDir('cwd');
  62. origCwd = process.cwd();
  63. process.chdir(tmpCwd);
  64. homeRestore = setHome(tmpHome);
  65. });
  66. afterEach(() => {
  67. homeRestore.restore();
  68. process.chdir(origCwd);
  69. fs.rmSync(tmpHome, { recursive: true, force: true });
  70. fs.rmSync(tmpCwd, { recursive: true, force: true });
  71. });
  72. for (const target of ALL_TARGETS) {
  73. describe(target.id, () => {
  74. const supportedLocations = (['global', 'local'] as const).filter((l) =>
  75. target.supportsLocation(l),
  76. );
  77. for (const location of supportedLocations) {
  78. describe(`location=${location}`, () => {
  79. it('install writes files; detect.alreadyConfigured becomes true', () => {
  80. expect(target.detect(location).alreadyConfigured).toBe(false);
  81. const result = target.install(location, { autoAllow: true });
  82. expect(result.files.length).toBeGreaterThan(0);
  83. for (const file of result.files) {
  84. if (file.action !== 'unchanged') {
  85. expect(fs.existsSync(file.path)).toBe(true);
  86. }
  87. }
  88. expect(target.detect(location).alreadyConfigured).toBe(true);
  89. });
  90. it('re-running install is idempotent (no actions other than unchanged)', () => {
  91. target.install(location, { autoAllow: true });
  92. const second = target.install(location, { autoAllow: true });
  93. for (const file of second.files) {
  94. expect(file.action).toBe('unchanged');
  95. }
  96. });
  97. it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
  98. // Plant a sibling entry in the same JSON config, install,
  99. // and verify the sibling survives. Skip for Codex (TOML)
  100. // and any target with no JSON config — they get covered
  101. // by their own dedicated tests below.
  102. const paths = target.describePaths(location);
  103. // Match .json or .jsonc — opencode prefers .jsonc.
  104. const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
  105. if (!jsonPath) return;
  106. // Seed pre-existing config.
  107. fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
  108. const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
  109. // opencode uses `mcp` not `mcpServers`. Match its shape too.
  110. if (target.id === 'opencode') {
  111. delete seed.mcpServers;
  112. seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
  113. }
  114. fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
  115. target.install(location, { autoAllow: true });
  116. const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
  117. if (target.id === 'opencode') {
  118. expect(after.mcp.other).toBeDefined();
  119. expect(after.mcp.codegraph).toBeDefined();
  120. } else {
  121. expect(after.mcpServers.other).toBeDefined();
  122. expect(after.mcpServers.codegraph).toBeDefined();
  123. }
  124. });
  125. it('uninstall reverses install (alreadyConfigured returns to false)', () => {
  126. target.install(location, { autoAllow: true });
  127. expect(target.detect(location).alreadyConfigured).toBe(true);
  128. target.uninstall(location);
  129. expect(target.detect(location).alreadyConfigured).toBe(false);
  130. });
  131. it('printConfig returns non-empty output without writing anything', () => {
  132. const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  133. const out = target.printConfig(location);
  134. expect(out.length).toBeGreaterThan(0);
  135. const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  136. expect(after.sort()).toEqual(before.sort());
  137. });
  138. });
  139. }
  140. });
  141. }
  142. });
  143. describe('Installer targets — partial-state idempotency', () => {
  144. let tmpHome: string;
  145. let tmpCwd: string;
  146. let origCwd: string;
  147. let homeRestore: { restore: () => void };
  148. beforeEach(() => {
  149. tmpHome = mkTmpDir('home');
  150. tmpCwd = mkTmpDir('cwd');
  151. origCwd = process.cwd();
  152. process.chdir(tmpCwd);
  153. homeRestore = setHome(tmpHome);
  154. });
  155. afterEach(() => {
  156. homeRestore.restore();
  157. process.chdir(origCwd);
  158. fs.rmSync(tmpHome, { recursive: true, force: true });
  159. fs.rmSync(tmpCwd, { recursive: true, force: true });
  160. });
  161. it('codex: install after only config.toml exists — second pass is fully unchanged', () => {
  162. const codex = getTarget('codex')!;
  163. // First install creates both files.
  164. codex.install('global', { autoAllow: false });
  165. // Delete the AGENTS.md to simulate partial state (user wiped one file).
  166. const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
  167. expect(fs.existsSync(agentsMd)).toBe(true);
  168. fs.unlinkSync(agentsMd);
  169. // Reinstall — TOML stays unchanged, AGENTS.md is recreated.
  170. const second = codex.install('global', { autoAllow: false });
  171. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  172. const mdEntry = second.files.find((f) => f.path.endsWith('AGENTS.md'))!;
  173. expect(tomlEntry.action).toBe('unchanged');
  174. expect(mdEntry.action).toBe('created');
  175. // Third install — both unchanged (full idempotency restored).
  176. const third = codex.install('global', { autoAllow: false });
  177. for (const f of third.files) expect(f.action).toBe('unchanged');
  178. });
  179. it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
  180. const opencode = getTarget('opencode')!;
  181. const dir = path.join(tmpHome, '.config', 'opencode');
  182. fs.mkdirSync(dir, { recursive: true });
  183. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  184. fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  185. const result = opencode.install('global', { autoAllow: true });
  186. const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
  187. expect(written).toBeDefined();
  188. expect(written.action).not.toBe('not-found');
  189. // The .json file is left alone.
  190. const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
  191. expect(jsonText).not.toContain('codegraph');
  192. });
  193. it('opencode: uses .json when only .json exists (no .jsonc)', () => {
  194. const opencode = getTarget('opencode')!;
  195. const dir = path.join(tmpHome, '.config', 'opencode');
  196. fs.mkdirSync(dir, { recursive: true });
  197. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  198. const result = opencode.install('global', { autoAllow: true });
  199. expect(result.files[0].path).toMatch(/opencode\.json$/);
  200. expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
  201. });
  202. it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
  203. const opencode = getTarget('opencode')!;
  204. const result = opencode.install('global', { autoAllow: true });
  205. expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
  206. expect(result.files[0].action).toBe('created');
  207. });
  208. it('opencode: preserves line and block comments through install + idempotent re-run', () => {
  209. const opencode = getTarget('opencode')!;
  210. const dir = path.join(tmpHome, '.config', 'opencode');
  211. fs.mkdirSync(dir, { recursive: true });
  212. const file = path.join(dir, 'opencode.jsonc');
  213. const original = [
  214. '{',
  215. ' // top-level note about my opencode setup',
  216. ' "$schema": "https://opencode.ai/config.json",',
  217. ' /* multi-line block comment',
  218. ' describing the providers section */',
  219. ' "providers": {',
  220. ' "anthropic": { "model": "claude-opus-4-7" } // pinned',
  221. ' }',
  222. '}',
  223. '',
  224. ].join('\n');
  225. fs.writeFileSync(file, original);
  226. opencode.install('global', { autoAllow: true });
  227. const afterInstall = fs.readFileSync(file, 'utf-8');
  228. expect(afterInstall).toContain('// top-level note about my opencode setup');
  229. expect(afterInstall).toContain('/* multi-line block comment');
  230. expect(afterInstall).toContain('// pinned');
  231. expect(afterInstall).toContain('"codegraph"');
  232. expect(afterInstall).toContain('"providers"');
  233. // Idempotent re-run reports unchanged, file is byte-identical.
  234. const second = opencode.install('global', { autoAllow: true });
  235. expect(second.files[0].action).toBe('unchanged');
  236. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  237. });
  238. it('opencode: install writes AGENTS.md with the marker-delimited codegraph block', () => {
  239. const opencode = getTarget('opencode')!;
  240. opencode.install('global', { autoAllow: true });
  241. const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
  242. expect(fs.existsSync(agentsMd)).toBe(true);
  243. const body = fs.readFileSync(agentsMd, 'utf-8');
  244. expect(body).toContain('<!-- CODEGRAPH_START -->');
  245. expect(body).toContain('<!-- CODEGRAPH_END -->');
  246. expect(body).toContain('codegraph_callers');
  247. });
  248. it('opencode: AGENTS.md install preserves pre-existing user content outside markers', () => {
  249. const opencode = getTarget('opencode')!;
  250. const dir = path.join(tmpHome, '.config', 'opencode');
  251. fs.mkdirSync(dir, { recursive: true });
  252. const agentsMd = path.join(dir, 'AGENTS.md');
  253. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  254. opencode.install('global', { autoAllow: true });
  255. const body = fs.readFileSync(agentsMd, 'utf-8');
  256. expect(body).toContain('# My personal opencode instructions');
  257. expect(body).toContain('Always respond in pirate.');
  258. expect(body).toContain('<!-- CODEGRAPH_START -->');
  259. });
  260. it('opencode: uninstall strips only the codegraph block from AGENTS.md', () => {
  261. const opencode = getTarget('opencode')!;
  262. const dir = path.join(tmpHome, '.config', 'opencode');
  263. fs.mkdirSync(dir, { recursive: true });
  264. const agentsMd = path.join(dir, 'AGENTS.md');
  265. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  266. opencode.install('global', { autoAllow: true });
  267. opencode.uninstall('global');
  268. const body = fs.readFileSync(agentsMd, 'utf-8');
  269. expect(body).toContain('# My personal opencode instructions');
  270. expect(body).toContain('Always respond in pirate.');
  271. expect(body).not.toContain('CODEGRAPH_START');
  272. expect(body).not.toContain('codegraph_callers');
  273. });
  274. it('opencode: local install writes ./opencode.jsonc and ./AGENTS.md in cwd', () => {
  275. const opencode = getTarget('opencode')!;
  276. const result = opencode.install('local', { autoAllow: true });
  277. const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
  278. // macOS realpath shenanigans (/var vs /private/var) — suffix match.
  279. expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
  280. expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
  281. });
  282. it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
  283. const hermes = getTarget('hermes')!;
  284. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  285. fs.mkdirSync(path.dirname(config), { recursive: true });
  286. fs.writeFileSync(config, [
  287. 'model:',
  288. ' default: qwen-3.7',
  289. 'mcp_servers:',
  290. ' other:',
  291. ' command: other',
  292. 'platform_toolsets:',
  293. ' cli:',
  294. ' - hermes-cli',
  295. ' discord:',
  296. ' - hermes-discord',
  297. '',
  298. ].join('\n'));
  299. const result = hermes.install('global', { autoAllow: true });
  300. expect(result.files[0].action).toBe('updated');
  301. const body = fs.readFileSync(config, 'utf-8');
  302. expect(body).toContain('model:\n default: qwen-3.7');
  303. expect(body).toContain('mcp_servers:\n other:\n command: other');
  304. expect(body).toContain(' codegraph:\n command: codegraph');
  305. expect(body).toContain(' - hermes-cli');
  306. expect(body).toContain(' - mcp-codegraph');
  307. expect(body).toContain(' discord:\n - hermes-discord');
  308. const second = hermes.install('global', { autoAllow: true });
  309. expect(second.files[0].action).toBe('unchanged');
  310. });
  311. it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
  312. const hermes = getTarget('hermes')!;
  313. const config = path.join(tmpHome, '.hermes', 'config.yaml');
  314. fs.mkdirSync(path.dirname(config), { recursive: true });
  315. hermes.install('global', { autoAllow: true });
  316. fs.appendFileSync(config, 'custom:\n keep: true\n');
  317. hermes.uninstall('global');
  318. const body = fs.readFileSync(config, 'utf-8');
  319. expect(body).not.toContain('codegraph:');
  320. expect(body).not.toContain('mcp-codegraph');
  321. expect(body).toContain('custom:\n keep: true');
  322. });
  323. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  324. const opencode = getTarget('opencode')!;
  325. const dir = path.join(tmpHome, '.config', 'opencode');
  326. fs.mkdirSync(dir, { recursive: true });
  327. const file = path.join(dir, 'opencode.jsonc');
  328. fs.writeFileSync(file, [
  329. '{',
  330. ' // important comment',
  331. ' "$schema": "https://opencode.ai/config.json",',
  332. ' "mcp": {',
  333. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  334. ' }',
  335. '}',
  336. '',
  337. ].join('\n'));
  338. opencode.install('global', { autoAllow: true });
  339. const afterInstall = fs.readFileSync(file, 'utf-8');
  340. expect(afterInstall).toContain('"codegraph"');
  341. expect(afterInstall).toContain('"other"');
  342. opencode.uninstall('global');
  343. const afterUninstall = fs.readFileSync(file, 'utf-8');
  344. expect(afterUninstall).not.toContain('codegraph');
  345. expect(afterUninstall).toContain('// important comment');
  346. expect(afterUninstall).toContain('"other"');
  347. });
  348. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  349. const codex = getTarget('codex')!;
  350. codex.install('global', { autoAllow: false });
  351. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  352. const original = fs.readFileSync(tomlPath, 'utf-8');
  353. // User edits the block to add a custom key.
  354. const edited = original.replace(
  355. 'args = ["serve", "--mcp"]',
  356. 'args = ["serve", "--mcp"]\nenabled = true',
  357. );
  358. fs.writeFileSync(tomlPath, edited);
  359. // Re-install: our serializer doesn't know `enabled = true`, so
  360. // the block no longer matches the canonical form — we'll
  361. // overwrite it. This is the documented contract: we own the
  362. // codegraph block exclusively.
  363. const second = codex.install('global', { autoAllow: false });
  364. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  365. expect(tomlEntry.action).toBe('updated');
  366. const after = fs.readFileSync(tomlPath, 'utf-8');
  367. expect(after).not.toContain('enabled = true');
  368. });
  369. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  370. const claude = getTarget('claude')!;
  371. const result = claude.install('local', { autoAllow: false });
  372. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  373. expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
  374. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  375. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  376. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  377. expect(cfg.mcpServers.codegraph).toBeDefined();
  378. });
  379. it('claude: global install targets ~/.claude.json (user scope)', () => {
  380. const claude = getTarget('claude')!;
  381. claude.install('global', { autoAllow: false });
  382. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  383. expect(cfg.mcpServers.codegraph).toBeDefined();
  384. });
  385. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  386. const claude = getTarget('claude')!;
  387. const legacy = path.join(tmpCwd, '.claude.json');
  388. fs.writeFileSync(
  389. legacy,
  390. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  391. );
  392. claude.install('local', { autoAllow: false });
  393. // codegraph now lives in .mcp.json; the legacy file (which held only
  394. // codegraph) is gone.
  395. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  396. expect(mcp.mcpServers.codegraph).toBeDefined();
  397. expect(fs.existsSync(legacy)).toBe(false);
  398. });
  399. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  400. const claude = getTarget('claude')!;
  401. const legacy = path.join(tmpCwd, '.claude.json');
  402. fs.writeFileSync(
  403. legacy,
  404. JSON.stringify({
  405. mcpServers: {
  406. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  407. other: { command: 'x' },
  408. },
  409. somethingElse: true,
  410. }, null, 2),
  411. );
  412. claude.install('local', { autoAllow: false });
  413. // Only codegraph is stripped from the legacy file; siblings survive.
  414. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  415. expect(after.mcpServers.codegraph).toBeUndefined();
  416. expect(after.mcpServers.other).toBeDefined();
  417. expect(after.somethingElse).toBe(true);
  418. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  419. expect(mcp.mcpServers.codegraph).toBeDefined();
  420. });
  421. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  422. const claude = getTarget('claude')!;
  423. // A user left with both the working .mcp.json and a stale .claude.json.
  424. fs.writeFileSync(
  425. path.join(tmpCwd, '.mcp.json'),
  426. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  427. );
  428. fs.writeFileSync(
  429. path.join(tmpCwd, '.claude.json'),
  430. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  431. );
  432. claude.uninstall('local');
  433. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  434. expect(mcp.mcpServers).toBeUndefined();
  435. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  436. expect(legacy.mcpServers.codegraph).toBeUndefined();
  437. expect(legacy.mcpServers.other).toBeDefined();
  438. });
  439. // ---- Legacy auto-sync hook cleanup ----
  440. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  441. // hooks to settings.json. Both subcommands were removed from the CLI,
  442. // so the Stop hook fails every turn ("unknown command
  443. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  444. // uninstall — without touching the user's unrelated hooks.
  445. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  446. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  447. fs.mkdirSync(dir, { recursive: true });
  448. const file = path.join(dir, 'settings.json');
  449. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  450. return file;
  451. }
  452. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  453. // unrelated GitKraken Stop hook the user added (matches the report).
  454. function legacyHookSettings(): Record<string, any> {
  455. return {
  456. hooks: {
  457. PostToolUse: [
  458. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  459. ],
  460. Stop: [
  461. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  462. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  463. ],
  464. },
  465. };
  466. }
  467. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  468. const claude = getTarget('claude')!;
  469. const file = seedSettings('global', legacyHookSettings());
  470. claude.install('global', { autoAllow: true });
  471. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  472. // The only PostToolUse group held mark-dirty → the event is gone.
  473. expect(after.hooks?.PostToolUse).toBeUndefined();
  474. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  475. (g.hooks ?? []).map((h: any) => h.command),
  476. );
  477. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  478. // The unrelated GitKraken hook survives untouched.
  479. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  480. // Permissions still written as normal alongside the cleanup.
  481. expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
  482. });
  483. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  484. const file = seedSettings('global', {
  485. hooks: {
  486. Stop: [
  487. {
  488. hooks: [
  489. { type: 'command', command: 'codegraph sync-if-dirty' },
  490. { type: 'command', command: 'gk ai hook run --host claude-code' },
  491. ],
  492. },
  493. ],
  494. },
  495. });
  496. expect(cleanupLegacyHooks('global').action).toBe('removed');
  497. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  498. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  499. 'gk ai hook run --host claude-code',
  500. ]);
  501. });
  502. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  503. const original =
  504. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  505. const file = seedSettings('global', JSON.parse(original));
  506. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  507. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  508. });
  509. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  510. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  511. });
  512. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  513. const claude = getTarget('claude')!;
  514. const file = seedSettings('global', legacyHookSettings());
  515. claude.install('global', { autoAllow: true });
  516. const firstPass = fs.readFileSync(file, 'utf-8');
  517. claude.install('global', { autoAllow: true });
  518. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  519. });
  520. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  521. const claude = getTarget('claude')!;
  522. const file = seedSettings('local', {
  523. hooks: {
  524. PostToolUse: [
  525. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  526. ],
  527. Stop: [
  528. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  529. ],
  530. },
  531. });
  532. claude.uninstall('local');
  533. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  534. // Both events emptied → the whole `hooks` object is removed.
  535. expect(after.hooks).toBeUndefined();
  536. });
  537. });
  538. describe('Installer targets — registry', () => {
  539. it('getTarget returns the right target for each id', () => {
  540. expect(getTarget('claude')?.id).toBe('claude');
  541. expect(getTarget('cursor')?.id).toBe('cursor');
  542. expect(getTarget('codex')?.id).toBe('codex');
  543. expect(getTarget('opencode')?.id).toBe('opencode');
  544. expect(getTarget('hermes')?.id).toBe('hermes');
  545. expect(getTarget('not-a-real-target')).toBeUndefined();
  546. });
  547. it('resolveTargetFlag handles auto/all/none/csv', () => {
  548. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  549. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  550. const csv = resolveTargetFlag('claude,cursor', 'global');
  551. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  552. });
  553. it('resolveTargetFlag throws on unknown id', () => {
  554. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  555. });
  556. });
  557. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  558. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  559. const block = buildTomlTable('mcp_servers.codegraph', {
  560. command: 'codegraph',
  561. args: ['serve', '--mcp'],
  562. });
  563. expect(block).toContain('[mcp_servers.codegraph]');
  564. expect(block).toContain('command = "codegraph"');
  565. expect(block).toContain('args = ["serve", "--mcp"]');
  566. });
  567. it('upsert inserts into empty content', () => {
  568. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  569. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  570. expect(action).toBe('inserted');
  571. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  572. });
  573. it('upsert is idempotent — second call returns unchanged', () => {
  574. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  575. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  576. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  577. expect(second.action).toBe('unchanged');
  578. expect(second.content).toBe(first.content);
  579. });
  580. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  581. const existing = [
  582. '[other_table]',
  583. 'foo = "bar"',
  584. '',
  585. '[mcp_servers.codegraph]',
  586. 'command = "old-codegraph"',
  587. 'args = ["old"]',
  588. '',
  589. '[zzz]',
  590. 'baz = "qux"',
  591. '',
  592. ].join('\n');
  593. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  594. command: 'codegraph',
  595. args: ['serve', '--mcp'],
  596. });
  597. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  598. expect(action).toBe('replaced');
  599. expect(content).toContain('[other_table]');
  600. expect(content).toContain('foo = "bar"');
  601. expect(content).toContain('[zzz]');
  602. expect(content).toContain('baz = "qux"');
  603. expect(content).toContain('command = "codegraph"');
  604. expect(content).not.toContain('old-codegraph');
  605. });
  606. it('removeTomlTable strips the block and preserves siblings', () => {
  607. const existing = [
  608. '[other_table]',
  609. 'foo = "bar"',
  610. '',
  611. '[mcp_servers.codegraph]',
  612. 'command = "codegraph"',
  613. 'args = ["serve"]',
  614. ].join('\n');
  615. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  616. expect(action).toBe('removed');
  617. expect(content).toContain('[other_table]');
  618. expect(content).toContain('foo = "bar"');
  619. expect(content).not.toContain('mcp_servers.codegraph');
  620. });
  621. it('removeTomlTable on missing table returns not-found, no content change', () => {
  622. const existing = '[other]\nfoo = "bar"\n';
  623. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  624. expect(action).toBe('not-found');
  625. expect(content).toBe(existing);
  626. });
  627. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  628. const existing = [
  629. '[[foo]]',
  630. 'name = "a"',
  631. '',
  632. '[[foo]]',
  633. 'name = "b"',
  634. '',
  635. ].join('\n');
  636. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  637. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  638. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  639. expect(content).toContain('[mcp_servers.codegraph]');
  640. });
  641. });
  642. describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
  643. let tmpHome: string;
  644. let tmpCwd: string;
  645. let origCwd: string;
  646. let homeRestore: { restore: () => void };
  647. beforeEach(() => {
  648. tmpHome = mkTmpDir('un-home');
  649. tmpCwd = mkTmpDir('un-cwd');
  650. origCwd = process.cwd();
  651. process.chdir(tmpCwd);
  652. homeRestore = setHome(tmpHome);
  653. });
  654. afterEach(() => {
  655. homeRestore.restore();
  656. process.chdir(origCwd);
  657. fs.rmSync(tmpHome, { recursive: true, force: true });
  658. fs.rmSync(tmpCwd, { recursive: true, force: true });
  659. });
  660. it('sweeps every agent it was installed on and reports removed for each (global)', () => {
  661. for (const t of ALL_TARGETS) {
  662. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  663. }
  664. const reports = uninstallTargets(ALL_TARGETS, 'global');
  665. for (const t of ALL_TARGETS) {
  666. const r = reports.find((x) => x.id === t.id)!;
  667. expect(r.status).toBe('removed');
  668. expect(r.removedPaths.length).toBeGreaterThan(0);
  669. // The actual config is gone afterward.
  670. expect(t.detect('global').alreadyConfigured).toBe(false);
  671. }
  672. });
  673. it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
  674. const reports = uninstallTargets(ALL_TARGETS, 'global');
  675. for (const r of reports) {
  676. expect(r.status).toBe('not-configured');
  677. expect(r.removedPaths).toEqual([]);
  678. }
  679. });
  680. it('reports removed only for agents that were actually configured', () => {
  681. // Install on Claude only; the rest stay untouched.
  682. getTarget('claude')!.install('global', { autoAllow: true });
  683. const reports = uninstallTargets(ALL_TARGETS, 'global');
  684. const claude = reports.find((r) => r.id === 'claude')!;
  685. expect(claude.status).toBe('removed');
  686. expect(claude.displayName).toBe(getTarget('claude')!.displayName);
  687. for (const r of reports.filter((x) => x.id !== 'claude')) {
  688. expect(r.status).toBe('not-configured');
  689. }
  690. });
  691. it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
  692. const reports = uninstallTargets(ALL_TARGETS, 'local');
  693. for (const t of ALL_TARGETS) {
  694. const r = reports.find((x) => x.id === t.id)!;
  695. if (t.supportsLocation('local')) {
  696. expect(r.status).toBe('not-configured');
  697. } else {
  698. expect(r.status).toBe('unsupported');
  699. expect(r.removedPaths).toEqual([]);
  700. expect(r.notes[0]).toMatch(/global-only/);
  701. }
  702. }
  703. });
  704. it('is idempotent — a second sweep finds nothing left to remove', () => {
  705. for (const t of ALL_TARGETS) {
  706. if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
  707. }
  708. const first = uninstallTargets(ALL_TARGETS, 'global');
  709. expect(first.some((r) => r.status === 'removed')).toBe(true);
  710. const second = uninstallTargets(ALL_TARGETS, 'global');
  711. for (const r of second) {
  712. expect(r.status).toBe('not-configured');
  713. expect(r.removedPaths).toEqual([]);
  714. }
  715. });
  716. it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
  717. getTarget('claude')!.install('global', { autoAllow: true });
  718. getTarget('cursor')!.install('global', { autoAllow: true });
  719. const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
  720. expect(reports.map((r) => r.id)).toEqual(['claude']);
  721. expect(reports[0].status).toBe('removed');
  722. // Cursor was not in the subset — still configured.
  723. expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
  724. expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
  725. });
  726. });
  727. describe('Installer — Cursor rules file cleanup on uninstall', () => {
  728. let tmpHome: string;
  729. let tmpCwd: string;
  730. let origCwd: string;
  731. let homeRestore: { restore: () => void };
  732. const cursor = getTarget('cursor')!;
  733. beforeEach(() => {
  734. tmpHome = mkTmpDir('cur-home');
  735. tmpCwd = mkTmpDir('cur-cwd');
  736. origCwd = process.cwd();
  737. process.chdir(tmpCwd);
  738. homeRestore = setHome(tmpHome);
  739. });
  740. afterEach(() => {
  741. homeRestore.restore();
  742. process.chdir(origCwd);
  743. fs.rmSync(tmpHome, { recursive: true, force: true });
  744. fs.rmSync(tmpCwd, { recursive: true, force: true });
  745. });
  746. const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
  747. it('deletes the dedicated codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
  748. cursor.install('local', { autoAllow: true });
  749. expect(fs.existsSync(rulesFile())).toBe(true);
  750. cursor.uninstall('local');
  751. // The whole file — frontmatter included — is gone, not just the block.
  752. expect(fs.existsSync(rulesFile())).toBe(false);
  753. expect(cursor.detect('local').alreadyConfigured).toBe(false);
  754. });
  755. it('preserves user content added outside the codegraph markers (strips only our block)', () => {
  756. cursor.install('local', { autoAllow: true });
  757. const withUserContent =
  758. fs.readFileSync(rulesFile(), 'utf-8') + '\n## My own rule\nkeep me\n';
  759. fs.writeFileSync(rulesFile(), withUserContent);
  760. cursor.uninstall('local');
  761. expect(fs.existsSync(rulesFile())).toBe(true);
  762. const after = fs.readFileSync(rulesFile(), 'utf-8');
  763. expect(after).toContain('keep me');
  764. // Our tool-usage block is gone.
  765. expect(after).not.toContain('codegraph_search');
  766. expect(after).not.toContain('CODEGRAPH_START');
  767. });
  768. });
  769. function listAllFiles(dir: string): string[] {
  770. if (!fs.existsSync(dir)) return [];
  771. const out: string[] = [];
  772. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  773. const full = path.join(dir, entry.name);
  774. if (entry.isDirectory()) out.push(...listAllFiles(full));
  775. else out.push(full);
  776. }
  777. return out;
  778. }