installer-targets.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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 { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
  22. import { cleanupLegacyHooks } from '../src/installer/targets/claude';
  23. function mkTmpDir(label: string): string {
  24. return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
  25. }
  26. // `os.homedir` is non-configurable on Node, so we redirect it via the
  27. // `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
  28. // `os.homedir()` reads first. Same trick the rest of the suite uses
  29. // when it needs a mock home.
  30. function setHome(dir: string): { restore: () => void } {
  31. const prev = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
  32. process.env.HOME = dir;
  33. process.env.USERPROFILE = dir;
  34. return {
  35. restore() {
  36. if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
  37. if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
  38. },
  39. };
  40. }
  41. describe('Installer targets — contract', () => {
  42. let tmpHome: string;
  43. let tmpCwd: string;
  44. let origCwd: string;
  45. let homeRestore: { restore: () => void };
  46. beforeEach(() => {
  47. tmpHome = mkTmpDir('home');
  48. tmpCwd = mkTmpDir('cwd');
  49. origCwd = process.cwd();
  50. process.chdir(tmpCwd);
  51. homeRestore = setHome(tmpHome);
  52. });
  53. afterEach(() => {
  54. homeRestore.restore();
  55. process.chdir(origCwd);
  56. fs.rmSync(tmpHome, { recursive: true, force: true });
  57. fs.rmSync(tmpCwd, { recursive: true, force: true });
  58. });
  59. for (const target of ALL_TARGETS) {
  60. describe(target.id, () => {
  61. const supportedLocations = (['global', 'local'] as const).filter((l) =>
  62. target.supportsLocation(l),
  63. );
  64. for (const location of supportedLocations) {
  65. describe(`location=${location}`, () => {
  66. it('install writes files; detect.alreadyConfigured becomes true', () => {
  67. expect(target.detect(location).alreadyConfigured).toBe(false);
  68. const result = target.install(location, { autoAllow: true });
  69. expect(result.files.length).toBeGreaterThan(0);
  70. for (const file of result.files) {
  71. if (file.action !== 'unchanged') {
  72. expect(fs.existsSync(file.path)).toBe(true);
  73. }
  74. }
  75. expect(target.detect(location).alreadyConfigured).toBe(true);
  76. });
  77. it('re-running install is idempotent (no actions other than unchanged)', () => {
  78. target.install(location, { autoAllow: true });
  79. const second = target.install(location, { autoAllow: true });
  80. for (const file of second.files) {
  81. expect(file.action).toBe('unchanged');
  82. }
  83. });
  84. it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
  85. // Plant a sibling entry in the same JSON config, install,
  86. // and verify the sibling survives. Skip for Codex (TOML)
  87. // and any target with no JSON config — they get covered
  88. // by their own dedicated tests below.
  89. const paths = target.describePaths(location);
  90. // Match .json or .jsonc — opencode prefers .jsonc.
  91. const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
  92. if (!jsonPath) return;
  93. // Seed pre-existing config.
  94. fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
  95. const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
  96. // opencode uses `mcp` not `mcpServers`. Match its shape too.
  97. if (target.id === 'opencode') {
  98. delete seed.mcpServers;
  99. seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
  100. }
  101. fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
  102. target.install(location, { autoAllow: true });
  103. const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
  104. if (target.id === 'opencode') {
  105. expect(after.mcp.other).toBeDefined();
  106. expect(after.mcp.codegraph).toBeDefined();
  107. } else {
  108. expect(after.mcpServers.other).toBeDefined();
  109. expect(after.mcpServers.codegraph).toBeDefined();
  110. }
  111. });
  112. it('uninstall reverses install (alreadyConfigured returns to false)', () => {
  113. target.install(location, { autoAllow: true });
  114. expect(target.detect(location).alreadyConfigured).toBe(true);
  115. target.uninstall(location);
  116. expect(target.detect(location).alreadyConfigured).toBe(false);
  117. });
  118. it('printConfig returns non-empty output without writing anything', () => {
  119. const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  120. const out = target.printConfig(location);
  121. expect(out.length).toBeGreaterThan(0);
  122. const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
  123. expect(after.sort()).toEqual(before.sort());
  124. });
  125. });
  126. }
  127. });
  128. }
  129. });
  130. describe('Installer targets — partial-state idempotency', () => {
  131. let tmpHome: string;
  132. let tmpCwd: string;
  133. let origCwd: string;
  134. let homeRestore: { restore: () => void };
  135. beforeEach(() => {
  136. tmpHome = mkTmpDir('home');
  137. tmpCwd = mkTmpDir('cwd');
  138. origCwd = process.cwd();
  139. process.chdir(tmpCwd);
  140. homeRestore = setHome(tmpHome);
  141. });
  142. afterEach(() => {
  143. homeRestore.restore();
  144. process.chdir(origCwd);
  145. fs.rmSync(tmpHome, { recursive: true, force: true });
  146. fs.rmSync(tmpCwd, { recursive: true, force: true });
  147. });
  148. it('codex: install after only config.toml exists — second pass is fully unchanged', () => {
  149. const codex = getTarget('codex')!;
  150. // First install creates both files.
  151. codex.install('global', { autoAllow: false });
  152. // Delete the AGENTS.md to simulate partial state (user wiped one file).
  153. const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
  154. expect(fs.existsSync(agentsMd)).toBe(true);
  155. fs.unlinkSync(agentsMd);
  156. // Reinstall — TOML stays unchanged, AGENTS.md is recreated.
  157. const second = codex.install('global', { autoAllow: false });
  158. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  159. const mdEntry = second.files.find((f) => f.path.endsWith('AGENTS.md'))!;
  160. expect(tomlEntry.action).toBe('unchanged');
  161. expect(mdEntry.action).toBe('created');
  162. // Third install — both unchanged (full idempotency restored).
  163. const third = codex.install('global', { autoAllow: false });
  164. for (const f of third.files) expect(f.action).toBe('unchanged');
  165. });
  166. it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
  167. const opencode = getTarget('opencode')!;
  168. const dir = path.join(tmpHome, '.config', 'opencode');
  169. fs.mkdirSync(dir, { recursive: true });
  170. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  171. fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  172. const result = opencode.install('global', { autoAllow: true });
  173. const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
  174. expect(written).toBeDefined();
  175. expect(written.action).not.toBe('not-found');
  176. // The .json file is left alone.
  177. const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
  178. expect(jsonText).not.toContain('codegraph');
  179. });
  180. it('opencode: uses .json when only .json exists (no .jsonc)', () => {
  181. const opencode = getTarget('opencode')!;
  182. const dir = path.join(tmpHome, '.config', 'opencode');
  183. fs.mkdirSync(dir, { recursive: true });
  184. fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
  185. const result = opencode.install('global', { autoAllow: true });
  186. expect(result.files[0].path).toMatch(/opencode\.json$/);
  187. expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
  188. });
  189. it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
  190. const opencode = getTarget('opencode')!;
  191. const result = opencode.install('global', { autoAllow: true });
  192. expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
  193. expect(result.files[0].action).toBe('created');
  194. });
  195. it('opencode: preserves line and block comments through install + idempotent re-run', () => {
  196. const opencode = getTarget('opencode')!;
  197. const dir = path.join(tmpHome, '.config', 'opencode');
  198. fs.mkdirSync(dir, { recursive: true });
  199. const file = path.join(dir, 'opencode.jsonc');
  200. const original = [
  201. '{',
  202. ' // top-level note about my opencode setup',
  203. ' "$schema": "https://opencode.ai/config.json",',
  204. ' /* multi-line block comment',
  205. ' describing the providers section */',
  206. ' "providers": {',
  207. ' "anthropic": { "model": "claude-opus-4-7" } // pinned',
  208. ' }',
  209. '}',
  210. '',
  211. ].join('\n');
  212. fs.writeFileSync(file, original);
  213. opencode.install('global', { autoAllow: true });
  214. const afterInstall = fs.readFileSync(file, 'utf-8');
  215. expect(afterInstall).toContain('// top-level note about my opencode setup');
  216. expect(afterInstall).toContain('/* multi-line block comment');
  217. expect(afterInstall).toContain('// pinned');
  218. expect(afterInstall).toContain('"codegraph"');
  219. expect(afterInstall).toContain('"providers"');
  220. // Idempotent re-run reports unchanged, file is byte-identical.
  221. const second = opencode.install('global', { autoAllow: true });
  222. expect(second.files[0].action).toBe('unchanged');
  223. expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
  224. });
  225. it('opencode: install writes AGENTS.md with the marker-delimited codegraph block', () => {
  226. const opencode = getTarget('opencode')!;
  227. opencode.install('global', { autoAllow: true });
  228. const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
  229. expect(fs.existsSync(agentsMd)).toBe(true);
  230. const body = fs.readFileSync(agentsMd, 'utf-8');
  231. expect(body).toContain('<!-- CODEGRAPH_START -->');
  232. expect(body).toContain('<!-- CODEGRAPH_END -->');
  233. expect(body).toContain('codegraph_callers');
  234. });
  235. it('opencode: AGENTS.md install preserves pre-existing user content outside markers', () => {
  236. const opencode = getTarget('opencode')!;
  237. const dir = path.join(tmpHome, '.config', 'opencode');
  238. fs.mkdirSync(dir, { recursive: true });
  239. const agentsMd = path.join(dir, 'AGENTS.md');
  240. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  241. opencode.install('global', { autoAllow: true });
  242. const body = fs.readFileSync(agentsMd, 'utf-8');
  243. expect(body).toContain('# My personal opencode instructions');
  244. expect(body).toContain('Always respond in pirate.');
  245. expect(body).toContain('<!-- CODEGRAPH_START -->');
  246. });
  247. it('opencode: uninstall strips only the codegraph block from AGENTS.md', () => {
  248. const opencode = getTarget('opencode')!;
  249. const dir = path.join(tmpHome, '.config', 'opencode');
  250. fs.mkdirSync(dir, { recursive: true });
  251. const agentsMd = path.join(dir, 'AGENTS.md');
  252. fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
  253. opencode.install('global', { autoAllow: true });
  254. opencode.uninstall('global');
  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).not.toContain('CODEGRAPH_START');
  259. expect(body).not.toContain('codegraph_callers');
  260. });
  261. it('opencode: local install writes ./opencode.jsonc and ./AGENTS.md in cwd', () => {
  262. const opencode = getTarget('opencode')!;
  263. const result = opencode.install('local', { autoAllow: true });
  264. const paths = result.files.map((f) => f.path);
  265. // macOS realpath shenanigans (/var vs /private/var) — suffix match.
  266. expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
  267. expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
  268. });
  269. it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
  270. const opencode = getTarget('opencode')!;
  271. const dir = path.join(tmpHome, '.config', 'opencode');
  272. fs.mkdirSync(dir, { recursive: true });
  273. const file = path.join(dir, 'opencode.jsonc');
  274. fs.writeFileSync(file, [
  275. '{',
  276. ' // important comment',
  277. ' "$schema": "https://opencode.ai/config.json",',
  278. ' "mcp": {',
  279. ' "other": { "type": "local", "command": ["x"], "enabled": true }',
  280. ' }',
  281. '}',
  282. '',
  283. ].join('\n'));
  284. opencode.install('global', { autoAllow: true });
  285. const afterInstall = fs.readFileSync(file, 'utf-8');
  286. expect(afterInstall).toContain('"codegraph"');
  287. expect(afterInstall).toContain('"other"');
  288. opencode.uninstall('global');
  289. const afterUninstall = fs.readFileSync(file, 'utf-8');
  290. expect(afterUninstall).not.toContain('codegraph');
  291. expect(afterUninstall).toContain('// important comment');
  292. expect(afterUninstall).toContain('"other"');
  293. });
  294. it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
  295. const codex = getTarget('codex')!;
  296. codex.install('global', { autoAllow: false });
  297. const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
  298. const original = fs.readFileSync(tomlPath, 'utf-8');
  299. // User edits the block to add a custom key.
  300. const edited = original.replace(
  301. 'args = ["serve", "--mcp"]',
  302. 'args = ["serve", "--mcp"]\nenabled = true',
  303. );
  304. fs.writeFileSync(tomlPath, edited);
  305. // Re-install: our serializer doesn't know `enabled = true`, so
  306. // the block no longer matches the canonical form — we'll
  307. // overwrite it. This is the documented contract: we own the
  308. // codegraph block exclusively.
  309. const second = codex.install('global', { autoAllow: false });
  310. const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
  311. expect(tomlEntry.action).toBe('updated');
  312. const after = fs.readFileSync(tomlPath, 'utf-8');
  313. expect(after).not.toContain('enabled = true');
  314. });
  315. it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
  316. const claude = getTarget('claude')!;
  317. const result = claude.install('local', { autoAllow: false });
  318. // The MCP entry lands in ./.mcp.json — the file Claude Code reads.
  319. expect(result.files.some((f) => f.path.endsWith('/.mcp.json'))).toBe(true);
  320. expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
  321. expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
  322. const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  323. expect(cfg.mcpServers.codegraph).toBeDefined();
  324. });
  325. it('claude: global install targets ~/.claude.json (user scope)', () => {
  326. const claude = getTarget('claude')!;
  327. claude.install('global', { autoAllow: false });
  328. const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
  329. expect(cfg.mcpServers.codegraph).toBeDefined();
  330. });
  331. it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
  332. const claude = getTarget('claude')!;
  333. const legacy = path.join(tmpCwd, '.claude.json');
  334. fs.writeFileSync(
  335. legacy,
  336. JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
  337. );
  338. claude.install('local', { autoAllow: false });
  339. // codegraph now lives in .mcp.json; the legacy file (which held only
  340. // codegraph) is gone.
  341. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  342. expect(mcp.mcpServers.codegraph).toBeDefined();
  343. expect(fs.existsSync(legacy)).toBe(false);
  344. });
  345. it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
  346. const claude = getTarget('claude')!;
  347. const legacy = path.join(tmpCwd, '.claude.json');
  348. fs.writeFileSync(
  349. legacy,
  350. JSON.stringify({
  351. mcpServers: {
  352. codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
  353. other: { command: 'x' },
  354. },
  355. somethingElse: true,
  356. }, null, 2),
  357. );
  358. claude.install('local', { autoAllow: false });
  359. // Only codegraph is stripped from the legacy file; siblings survive.
  360. const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
  361. expect(after.mcpServers.codegraph).toBeUndefined();
  362. expect(after.mcpServers.other).toBeDefined();
  363. expect(after.somethingElse).toBe(true);
  364. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  365. expect(mcp.mcpServers.codegraph).toBeDefined();
  366. });
  367. it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
  368. const claude = getTarget('claude')!;
  369. // A user left with both the working .mcp.json and a stale .claude.json.
  370. fs.writeFileSync(
  371. path.join(tmpCwd, '.mcp.json'),
  372. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
  373. );
  374. fs.writeFileSync(
  375. path.join(tmpCwd, '.claude.json'),
  376. JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
  377. );
  378. claude.uninstall('local');
  379. const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
  380. expect(mcp.mcpServers).toBeUndefined();
  381. const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
  382. expect(legacy.mcpServers.codegraph).toBeUndefined();
  383. expect(legacy.mcpServers.other).toBeDefined();
  384. });
  385. // ---- Legacy auto-sync hook cleanup ----
  386. // Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
  387. // hooks to settings.json. Both subcommands were removed from the CLI,
  388. // so the Stop hook fails every turn ("unknown command
  389. // 'sync-if-dirty'"). The installer must strip them on upgrade and
  390. // uninstall — without touching the user's unrelated hooks.
  391. function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
  392. const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
  393. fs.mkdirSync(dir, { recursive: true });
  394. const file = path.join(dir, 'settings.json');
  395. fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
  396. return file;
  397. }
  398. // Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
  399. // unrelated GitKraken Stop hook the user added (matches the report).
  400. function legacyHookSettings(): Record<string, any> {
  401. return {
  402. hooks: {
  403. PostToolUse: [
  404. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
  405. ],
  406. Stop: [
  407. { hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
  408. { hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
  409. ],
  410. },
  411. };
  412. }
  413. it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
  414. const claude = getTarget('claude')!;
  415. const file = seedSettings('global', legacyHookSettings());
  416. claude.install('global', { autoAllow: true });
  417. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  418. // The only PostToolUse group held mark-dirty → the event is gone.
  419. expect(after.hooks?.PostToolUse).toBeUndefined();
  420. const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
  421. (g.hooks ?? []).map((h: any) => h.command),
  422. );
  423. expect(stopCommands).not.toContain('codegraph sync-if-dirty');
  424. // The unrelated GitKraken hook survives untouched.
  425. expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
  426. // Permissions still written as normal alongside the cleanup.
  427. expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
  428. });
  429. it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
  430. const file = seedSettings('global', {
  431. hooks: {
  432. Stop: [
  433. {
  434. hooks: [
  435. { type: 'command', command: 'codegraph sync-if-dirty' },
  436. { type: 'command', command: 'gk ai hook run --host claude-code' },
  437. ],
  438. },
  439. ],
  440. },
  441. });
  442. expect(cleanupLegacyHooks('global').action).toBe('removed');
  443. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  444. expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
  445. 'gk ai hook run --host claude-code',
  446. ]);
  447. });
  448. it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
  449. const original =
  450. JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
  451. const file = seedSettings('global', JSON.parse(original));
  452. expect(cleanupLegacyHooks('global').action).toBe('unchanged');
  453. expect(fs.readFileSync(file, 'utf-8')).toBe(original);
  454. });
  455. it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
  456. expect(cleanupLegacyHooks('global').action).toBe('not-found');
  457. });
  458. it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
  459. const claude = getTarget('claude')!;
  460. const file = seedSettings('global', legacyHookSettings());
  461. claude.install('global', { autoAllow: true });
  462. const firstPass = fs.readFileSync(file, 'utf-8');
  463. claude.install('global', { autoAllow: true });
  464. expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
  465. });
  466. it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
  467. const claude = getTarget('claude')!;
  468. const file = seedSettings('local', {
  469. hooks: {
  470. PostToolUse: [
  471. { matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
  472. ],
  473. Stop: [
  474. { hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
  475. ],
  476. },
  477. });
  478. claude.uninstall('local');
  479. const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
  480. // Both events emptied → the whole `hooks` object is removed.
  481. expect(after.hooks).toBeUndefined();
  482. });
  483. });
  484. describe('Installer targets — registry', () => {
  485. it('getTarget returns the right target for each id', () => {
  486. expect(getTarget('claude')?.id).toBe('claude');
  487. expect(getTarget('cursor')?.id).toBe('cursor');
  488. expect(getTarget('codex')?.id).toBe('codex');
  489. expect(getTarget('opencode')?.id).toBe('opencode');
  490. expect(getTarget('not-a-real-target')).toBeUndefined();
  491. });
  492. it('resolveTargetFlag handles auto/all/none/csv', () => {
  493. expect(resolveTargetFlag('none', 'global')).toEqual([]);
  494. expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
  495. const csv = resolveTargetFlag('claude,cursor', 'global');
  496. expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
  497. });
  498. it('resolveTargetFlag throws on unknown id', () => {
  499. expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
  500. });
  501. });
  502. describe('Installer targets — TOML serializer (Codex backbone)', () => {
  503. it('builds a [mcp_servers.codegraph] block with command + args', () => {
  504. const block = buildTomlTable('mcp_servers.codegraph', {
  505. command: 'codegraph',
  506. args: ['serve', '--mcp'],
  507. });
  508. expect(block).toContain('[mcp_servers.codegraph]');
  509. expect(block).toContain('command = "codegraph"');
  510. expect(block).toContain('args = ["serve", "--mcp"]');
  511. });
  512. it('upsert inserts into empty content', () => {
  513. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  514. const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
  515. expect(action).toBe('inserted');
  516. expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
  517. });
  518. it('upsert is idempotent — second call returns unchanged', () => {
  519. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  520. const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
  521. const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
  522. expect(second.action).toBe('unchanged');
  523. expect(second.content).toBe(first.content);
  524. });
  525. it('upsert replaces an existing block in place, preserving sibling tables', () => {
  526. const existing = [
  527. '[other_table]',
  528. 'foo = "bar"',
  529. '',
  530. '[mcp_servers.codegraph]',
  531. 'command = "old-codegraph"',
  532. 'args = ["old"]',
  533. '',
  534. '[zzz]',
  535. 'baz = "qux"',
  536. '',
  537. ].join('\n');
  538. const newBlock = buildTomlTable('mcp_servers.codegraph', {
  539. command: 'codegraph',
  540. args: ['serve', '--mcp'],
  541. });
  542. const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
  543. expect(action).toBe('replaced');
  544. expect(content).toContain('[other_table]');
  545. expect(content).toContain('foo = "bar"');
  546. expect(content).toContain('[zzz]');
  547. expect(content).toContain('baz = "qux"');
  548. expect(content).toContain('command = "codegraph"');
  549. expect(content).not.toContain('old-codegraph');
  550. });
  551. it('removeTomlTable strips the block and preserves siblings', () => {
  552. const existing = [
  553. '[other_table]',
  554. 'foo = "bar"',
  555. '',
  556. '[mcp_servers.codegraph]',
  557. 'command = "codegraph"',
  558. 'args = ["serve"]',
  559. ].join('\n');
  560. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  561. expect(action).toBe('removed');
  562. expect(content).toContain('[other_table]');
  563. expect(content).toContain('foo = "bar"');
  564. expect(content).not.toContain('mcp_servers.codegraph');
  565. });
  566. it('removeTomlTable on missing table returns not-found, no content change', () => {
  567. const existing = '[other]\nfoo = "bar"\n';
  568. const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
  569. expect(action).toBe('not-found');
  570. expect(content).toBe(existing);
  571. });
  572. it('upsert preserves an array-of-tables sibling [[foo]]', () => {
  573. const existing = [
  574. '[[foo]]',
  575. 'name = "a"',
  576. '',
  577. '[[foo]]',
  578. 'name = "b"',
  579. '',
  580. ].join('\n');
  581. const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
  582. const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
  583. expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
  584. expect(content).toContain('[mcp_servers.codegraph]');
  585. });
  586. });
  587. function listAllFiles(dir: string): string[] {
  588. if (!fs.existsSync(dir)) return [];
  589. const out: string[] = [];
  590. for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
  591. const full = path.join(dir, entry.name);
  592. if (entry.isDirectory()) out.push(...listAllFiles(full));
  593. else out.push(full);
  594. }
  595. return out;
  596. }