codegraph.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. #!/usr/bin/env node
  2. /**
  3. * CodeGraph CLI
  4. *
  5. * Command-line interface for CodeGraph code intelligence.
  6. *
  7. * Usage:
  8. * codegraph Run interactive installer (when no args)
  9. * codegraph install Run interactive installer
  10. * codegraph init [path] Initialize CodeGraph in a project
  11. * codegraph uninit [path] Remove CodeGraph from a project
  12. * codegraph index [path] Index all files in the project
  13. * codegraph sync [path] Sync changes since last index
  14. * codegraph status [path] Show index status
  15. * codegraph query <search> Search for symbols
  16. * codegraph files [options] Show project file structure
  17. * codegraph context <task> Build context for a task
  18. * codegraph affected [files] Find test files affected by changes
  19. * codegraph mark-dirty [path] Mark project as needing sync (hooks)
  20. * codegraph sync-if-dirty [path] Sync if marked dirty (hooks)
  21. *
  22. * Note: Git hooks have been removed. CodeGraph sync is triggered automatically
  23. * through codegraph's Claude Code hooks integration.
  24. */
  25. import { Command } from 'commander';
  26. import * as path from 'path';
  27. import * as fs from 'fs';
  28. import { spawn } from 'child_process';
  29. import { getCodeGraphDir, findNearestCodeGraphRoot, isInitialized } from '../directory';
  30. // Lazy-load heavy modules (CodeGraph, runInstaller) to keep CLI startup fast.
  31. async function loadCodeGraph(): Promise<typeof import('../index')> {
  32. try {
  33. return await import('../index');
  34. } catch (err) {
  35. const msg = err instanceof Error ? err.message : String(err);
  36. console.error('\x1b[31m✗\x1b[0m Failed to load CodeGraph modules.');
  37. console.error(`\n Node: ${process.version} Platform: ${process.platform} ${process.arch}`);
  38. console.error(`\n Error: ${msg}`);
  39. console.error('\n Try reinstalling with: npm install -g @colbymchenry/codegraph\n');
  40. process.exit(1);
  41. }
  42. }
  43. type IndexProgress = import('../index').IndexProgress;
  44. // Check if running with no arguments - run installer
  45. if (process.argv.length === 2) {
  46. import('../installer').then(({ runInstaller }) =>
  47. runInstaller()
  48. ).catch((err) => {
  49. console.error('Installation failed:', err instanceof Error ? err.message : String(err));
  50. process.exit(1);
  51. });
  52. } else {
  53. // Normal CLI flow
  54. main();
  55. }
  56. process.on('uncaughtException', (error) => {
  57. console.error('[CodeGraph] Uncaught exception:', error);
  58. });
  59. process.on('unhandledRejection', (reason) => {
  60. console.error('[CodeGraph] Unhandled rejection:', reason);
  61. });
  62. function main() {
  63. const program = new Command();
  64. // Version from package.json
  65. const packageJson = JSON.parse(
  66. fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf-8')
  67. );
  68. // =============================================================================
  69. // ANSI Color Helpers (avoid chalk ESM issues)
  70. // =============================================================================
  71. const colors = {
  72. reset: '\x1b[0m',
  73. bold: '\x1b[1m',
  74. dim: '\x1b[2m',
  75. red: '\x1b[31m',
  76. green: '\x1b[32m',
  77. yellow: '\x1b[33m',
  78. blue: '\x1b[34m',
  79. cyan: '\x1b[36m',
  80. white: '\x1b[37m',
  81. gray: '\x1b[90m',
  82. };
  83. const chalk = {
  84. bold: (s: string) => `${colors.bold}${s}${colors.reset}`,
  85. dim: (s: string) => `${colors.dim}${s}${colors.reset}`,
  86. red: (s: string) => `${colors.red}${s}${colors.reset}`,
  87. green: (s: string) => `${colors.green}${s}${colors.reset}`,
  88. yellow: (s: string) => `${colors.yellow}${s}${colors.reset}`,
  89. blue: (s: string) => `${colors.blue}${s}${colors.reset}`,
  90. cyan: (s: string) => `${colors.cyan}${s}${colors.reset}`,
  91. white: (s: string) => `${colors.white}${s}${colors.reset}`,
  92. gray: (s: string) => `${colors.gray}${s}${colors.reset}`,
  93. };
  94. program
  95. .name('codegraph')
  96. .description('Code intelligence and knowledge graph for any codebase')
  97. .version(packageJson.version);
  98. // =============================================================================
  99. // Helper Functions
  100. // =============================================================================
  101. /**
  102. * Resolve project path from argument or current directory
  103. * Walks up parent directories to find nearest initialized CodeGraph project
  104. * (must have .codegraph/codegraph.db, not just .codegraph/lessons.db)
  105. */
  106. function resolveProjectPath(pathArg?: string): string {
  107. const absolutePath = path.resolve(pathArg || process.cwd());
  108. // If exact path is initialized (has codegraph.db), use it
  109. if (isInitialized(absolutePath)) {
  110. return absolutePath;
  111. }
  112. // Walk up to find nearest parent with CodeGraph initialized
  113. // Note: findNearestCodeGraphRoot finds any .codegraph folder, but we need one with codegraph.db
  114. let current = absolutePath;
  115. const root = path.parse(current).root;
  116. while (current !== root) {
  117. const parent = path.dirname(current);
  118. if (parent === current) break;
  119. current = parent;
  120. if (isInitialized(current)) {
  121. return current;
  122. }
  123. }
  124. // Not found - return original path (will fail later with helpful error)
  125. return absolutePath;
  126. }
  127. /**
  128. * Format a number with commas
  129. */
  130. function formatNumber(n: number): string {
  131. return n.toLocaleString();
  132. }
  133. /**
  134. * Format duration in milliseconds to human readable
  135. */
  136. function formatDuration(ms: number): string {
  137. if (ms < 1000) {
  138. return `${ms}ms`;
  139. }
  140. const seconds = ms / 1000;
  141. if (seconds < 60) {
  142. return `${seconds.toFixed(1)}s`;
  143. }
  144. const minutes = Math.floor(seconds / 60);
  145. const remainingSeconds = seconds % 60;
  146. return `${minutes}m ${remainingSeconds.toFixed(0)}s`;
  147. }
  148. /**
  149. * Create a progress bar string
  150. */
  151. function progressBar(current: number, total: number, width: number = 30): string {
  152. const percent = total > 0 ? current / total : 0;
  153. const filled = Math.round(width * percent);
  154. const empty = width - filled;
  155. const bar = chalk.green('█'.repeat(filled)) + chalk.gray('░'.repeat(empty));
  156. const percentStr = `${Math.round(percent * 100)}%`.padStart(4);
  157. return `${bar} ${percentStr}`;
  158. }
  159. /**
  160. * Print a progress update (overwrites current line)
  161. */
  162. function printProgress(progress: IndexProgress): void {
  163. const phaseNames: Record<string, string> = {
  164. scanning: 'Scanning files',
  165. parsing: 'Parsing code',
  166. storing: 'Storing data',
  167. resolving: 'Resolving refs',
  168. };
  169. const phaseName = phaseNames[progress.phase] || progress.phase;
  170. const bar = progressBar(progress.current, progress.total);
  171. const file = progress.currentFile ? chalk.dim(` ${progress.currentFile}`) : '';
  172. // Clear line and print progress
  173. process.stdout.write(`\r${chalk.cyan(phaseName)}: ${bar}${file}`.padEnd(100));
  174. }
  175. /**
  176. * Print success message
  177. */
  178. function success(message: string): void {
  179. console.log(chalk.green('✓') + ' ' + message);
  180. }
  181. /**
  182. * Print error message
  183. */
  184. function error(message: string): void {
  185. console.error(chalk.red('✗') + ' ' + message);
  186. }
  187. /**
  188. * Print info message
  189. */
  190. function info(message: string): void {
  191. console.log(chalk.blue('ℹ') + ' ' + message);
  192. }
  193. /**
  194. * Print warning message
  195. */
  196. function warn(message: string): void {
  197. console.log(chalk.yellow('⚠') + ' ' + message);
  198. }
  199. // =============================================================================
  200. // Commands
  201. // =============================================================================
  202. /**
  203. * codegraph init [path]
  204. */
  205. program
  206. .command('init [path]')
  207. .description('Initialize CodeGraph in a project directory')
  208. .option('-i, --index', 'Run initial indexing after initialization')
  209. .action(async (pathArg: string | undefined, options: { index?: boolean }) => {
  210. const projectPath = resolveProjectPath(pathArg);
  211. console.log(chalk.bold('\nInitializing CodeGraph...\n'));
  212. try {
  213. // Check if already initialized
  214. if (isInitialized(projectPath)) {
  215. warn(`CodeGraph already initialized in ${projectPath}`);
  216. info('Use "codegraph index" to re-index or "codegraph sync" to update');
  217. return;
  218. }
  219. // Initialize
  220. const { default: CodeGraph } = await loadCodeGraph();
  221. const cg = await CodeGraph.init(projectPath, {
  222. index: false, // We'll handle indexing ourselves for progress
  223. });
  224. success(`Initialized CodeGraph in ${projectPath}`);
  225. info(`Created .codegraph/ directory`);
  226. // Run initial index if requested
  227. if (options.index) {
  228. console.log('\nIndexing project...\n');
  229. const result = await cg.indexAll({
  230. onProgress: printProgress,
  231. });
  232. // Clear progress line
  233. process.stdout.write('\r' + ' '.repeat(100) + '\r');
  234. if (result.success) {
  235. success(`Indexed ${formatNumber(result.filesIndexed)} files`);
  236. info(`Created ${formatNumber(result.nodesCreated)} nodes and ${formatNumber(result.edgesCreated)} edges`);
  237. info(`Completed in ${formatDuration(result.durationMs)}`);
  238. } else {
  239. warn(`Indexing completed with ${result.errors.length} errors`);
  240. }
  241. } else {
  242. info('Run "codegraph index" to index the project');
  243. }
  244. cg.destroy();
  245. } catch (err) {
  246. error(`Failed to initialize: ${err instanceof Error ? err.message : String(err)}`);
  247. process.exit(1);
  248. }
  249. });
  250. /**
  251. * codegraph uninit [path]
  252. */
  253. program
  254. .command('uninit [path]')
  255. .description('Remove CodeGraph from a project (deletes .codegraph/ directory)')
  256. .option('-f, --force', 'Skip confirmation prompt')
  257. .action(async (pathArg: string | undefined, options: { force?: boolean }) => {
  258. const projectPath = resolveProjectPath(pathArg);
  259. try {
  260. if (!isInitialized(projectPath)) {
  261. warn(`CodeGraph is not initialized in ${projectPath}`);
  262. return;
  263. }
  264. if (!options.force) {
  265. // Confirm with user
  266. const readline = await import('readline');
  267. const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  268. const answer = await new Promise<string>((resolve) => {
  269. rl.question(
  270. chalk.yellow('⚠ This will permanently delete all CodeGraph data. Continue? (y/N) '),
  271. resolve
  272. );
  273. });
  274. rl.close();
  275. if (answer.toLowerCase() !== 'y') {
  276. info('Cancelled');
  277. return;
  278. }
  279. }
  280. const { default: CodeGraph } = await loadCodeGraph();
  281. const cg = CodeGraph.openSync(projectPath);
  282. cg.uninitialize();
  283. success(`Removed CodeGraph from ${projectPath}`);
  284. } catch (err) {
  285. error(`Failed to uninitialize: ${err instanceof Error ? err.message : String(err)}`);
  286. process.exit(1);
  287. }
  288. });
  289. /**
  290. * codegraph index [path]
  291. */
  292. program
  293. .command('index [path]')
  294. .description('Index all files in the project')
  295. .option('-f, --force', 'Force full re-index even if already indexed')
  296. .option('-q, --quiet', 'Suppress progress output')
  297. .action(async (pathArg: string | undefined, options: { force?: boolean; quiet?: boolean }) => {
  298. const projectPath = resolveProjectPath(pathArg);
  299. try {
  300. if (!isInitialized(projectPath)) {
  301. error(`CodeGraph not initialized in ${projectPath}`);
  302. info('Run "codegraph init" first');
  303. process.exit(1);
  304. }
  305. const { default: CodeGraph } = await loadCodeGraph();
  306. const cg = await CodeGraph.open(projectPath);
  307. if (!options.quiet) {
  308. console.log(chalk.bold('\nIndexing project...\n'));
  309. }
  310. // Clear existing data if force
  311. if (options.force) {
  312. cg.clear();
  313. if (!options.quiet) {
  314. info('Cleared existing index');
  315. }
  316. }
  317. const result = await cg.indexAll({
  318. onProgress: options.quiet ? undefined : printProgress,
  319. });
  320. // Clear progress line
  321. if (!options.quiet) {
  322. process.stdout.write('\r' + ' '.repeat(100) + '\r');
  323. }
  324. if (result.success) {
  325. if (!options.quiet) {
  326. success(`Indexed ${formatNumber(result.filesIndexed)} files`);
  327. info(`Created ${formatNumber(result.nodesCreated)} nodes and ${formatNumber(result.edgesCreated)} edges`);
  328. info(`Completed in ${formatDuration(result.durationMs)}`);
  329. }
  330. } else {
  331. if (!options.quiet) {
  332. warn(`Indexing completed with ${result.errors.length} errors`);
  333. for (const err of result.errors.slice(0, 5)) {
  334. console.log(chalk.dim(` - ${err.message}`));
  335. }
  336. if (result.errors.length > 5) {
  337. console.log(chalk.dim(` ... and ${result.errors.length - 5} more`));
  338. }
  339. }
  340. process.exit(1);
  341. }
  342. cg.destroy();
  343. } catch (err) {
  344. error(`Failed to index: ${err instanceof Error ? err.message : String(err)}`);
  345. process.exit(1);
  346. }
  347. });
  348. /**
  349. * codegraph sync [path]
  350. */
  351. program
  352. .command('sync [path]')
  353. .description('Sync changes since last index')
  354. .option('-q, --quiet', 'Suppress output (for git hooks)')
  355. .action(async (pathArg: string | undefined, options: { quiet?: boolean }) => {
  356. const projectPath = resolveProjectPath(pathArg);
  357. try {
  358. if (!isInitialized(projectPath)) {
  359. if (!options.quiet) {
  360. error(`CodeGraph not initialized in ${projectPath}`);
  361. }
  362. process.exit(1);
  363. }
  364. const { default: CodeGraph } = await loadCodeGraph();
  365. const cg = await CodeGraph.open(projectPath);
  366. const result = await cg.sync({
  367. onProgress: options.quiet ? undefined : printProgress,
  368. });
  369. // Clear progress line
  370. if (!options.quiet) {
  371. process.stdout.write('\r' + ' '.repeat(100) + '\r');
  372. }
  373. const totalChanges = result.filesAdded + result.filesModified + result.filesRemoved;
  374. if (!options.quiet) {
  375. if (totalChanges === 0) {
  376. success('Already up to date');
  377. } else {
  378. success(`Synced ${formatNumber(totalChanges)} changed files`);
  379. if (result.filesAdded > 0) {
  380. info(` Added: ${result.filesAdded}`);
  381. }
  382. if (result.filesModified > 0) {
  383. info(` Modified: ${result.filesModified}`);
  384. }
  385. if (result.filesRemoved > 0) {
  386. info(` Removed: ${result.filesRemoved}`);
  387. }
  388. info(`Updated ${formatNumber(result.nodesUpdated)} nodes in ${formatDuration(result.durationMs)}`);
  389. }
  390. }
  391. cg.destroy();
  392. } catch (err) {
  393. if (!options.quiet) {
  394. error(`Failed to sync: ${err instanceof Error ? err.message : String(err)}`);
  395. }
  396. process.exit(1);
  397. }
  398. });
  399. /**
  400. * codegraph status [path]
  401. */
  402. program
  403. .command('status [path]')
  404. .description('Show index status and statistics')
  405. .option('-j, --json', 'Output as JSON')
  406. .action(async (pathArg: string | undefined, options: { json?: boolean }) => {
  407. const projectPath = resolveProjectPath(pathArg);
  408. try {
  409. if (!isInitialized(projectPath)) {
  410. if (options.json) {
  411. console.log(JSON.stringify({ initialized: false, projectPath }));
  412. return;
  413. }
  414. console.log(chalk.bold('\nCodeGraph Status\n'));
  415. info(`Project: ${projectPath}`);
  416. warn('Not initialized');
  417. info('Run "codegraph init" to initialize');
  418. return;
  419. }
  420. const { default: CodeGraph } = await loadCodeGraph();
  421. const cg = await CodeGraph.open(projectPath);
  422. const stats = cg.getStats();
  423. const changes = cg.getChangedFiles();
  424. // JSON output mode
  425. if (options.json) {
  426. console.log(JSON.stringify({
  427. initialized: true,
  428. projectPath,
  429. fileCount: stats.fileCount,
  430. nodeCount: stats.nodeCount,
  431. edgeCount: stats.edgeCount,
  432. dbSizeBytes: stats.dbSizeBytes,
  433. nodesByKind: stats.nodesByKind,
  434. languages: Object.entries(stats.filesByLanguage).filter(([, count]) => count > 0).map(([lang]) => lang),
  435. pendingChanges: {
  436. added: changes.added.length,
  437. modified: changes.modified.length,
  438. removed: changes.removed.length,
  439. },
  440. }));
  441. cg.destroy();
  442. return;
  443. }
  444. console.log(chalk.bold('\nCodeGraph Status\n'));
  445. // Project info
  446. console.log(chalk.cyan('Project:'), projectPath);
  447. console.log();
  448. // Index stats
  449. console.log(chalk.bold('Index Statistics:'));
  450. console.log(` Files: ${formatNumber(stats.fileCount)}`);
  451. console.log(` Nodes: ${formatNumber(stats.nodeCount)}`);
  452. console.log(` Edges: ${formatNumber(stats.edgeCount)}`);
  453. console.log(` DB Size: ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
  454. console.log();
  455. // Node breakdown
  456. console.log(chalk.bold('Nodes by Kind:'));
  457. const nodesByKind = Object.entries(stats.nodesByKind)
  458. .filter(([, count]) => count > 0)
  459. .sort((a, b) => b[1] - a[1]);
  460. for (const [kind, count] of nodesByKind) {
  461. console.log(` ${kind.padEnd(15)} ${formatNumber(count)}`);
  462. }
  463. console.log();
  464. // Language breakdown
  465. console.log(chalk.bold('Files by Language:'));
  466. const filesByLang = Object.entries(stats.filesByLanguage)
  467. .filter(([, count]) => count > 0)
  468. .sort((a, b) => b[1] - a[1]);
  469. for (const [lang, count] of filesByLang) {
  470. console.log(` ${lang.padEnd(15)} ${formatNumber(count)}`);
  471. }
  472. console.log();
  473. // Pending changes
  474. const totalChanges = changes.added.length + changes.modified.length + changes.removed.length;
  475. if (totalChanges > 0) {
  476. console.log(chalk.bold('Pending Changes:'));
  477. if (changes.added.length > 0) {
  478. console.log(` Added: ${changes.added.length} files`);
  479. }
  480. if (changes.modified.length > 0) {
  481. console.log(` Modified: ${changes.modified.length} files`);
  482. }
  483. if (changes.removed.length > 0) {
  484. console.log(` Removed: ${changes.removed.length} files`);
  485. }
  486. info('Run "codegraph sync" to update the index');
  487. } else {
  488. success('Index is up to date');
  489. }
  490. console.log();
  491. cg.destroy();
  492. } catch (err) {
  493. error(`Failed to get status: ${err instanceof Error ? err.message : String(err)}`);
  494. process.exit(1);
  495. }
  496. });
  497. /**
  498. * codegraph query <search>
  499. */
  500. program
  501. .command('query <search>')
  502. .description('Search for symbols in the codebase')
  503. .option('-p, --path <path>', 'Project path')
  504. .option('-l, --limit <number>', 'Maximum results', '10')
  505. .option('-k, --kind <kind>', 'Filter by node kind (function, class, etc.)')
  506. .option('-j, --json', 'Output as JSON')
  507. .action(async (search: string, options: { path?: string; limit?: string; kind?: string; json?: boolean }) => {
  508. const projectPath = resolveProjectPath(options.path);
  509. try {
  510. if (!isInitialized(projectPath)) {
  511. error(`CodeGraph not initialized in ${projectPath}`);
  512. process.exit(1);
  513. }
  514. const { default: CodeGraph } = await loadCodeGraph();
  515. const cg = await CodeGraph.open(projectPath);
  516. const limit = parseInt(options.limit || '10', 10);
  517. const results = cg.searchNodes(search, {
  518. limit,
  519. kinds: options.kind ? [options.kind as any] : undefined,
  520. });
  521. if (options.json) {
  522. console.log(JSON.stringify(results, null, 2));
  523. } else {
  524. if (results.length === 0) {
  525. info(`No results found for "${search}"`);
  526. } else {
  527. console.log(chalk.bold(`\nSearch Results for "${search}":\n`));
  528. for (const result of results) {
  529. const node = result.node;
  530. const location = `${node.filePath}:${node.startLine}`;
  531. const score = chalk.dim(`(${(result.score * 100).toFixed(0)}%)`);
  532. console.log(
  533. chalk.cyan(node.kind.padEnd(12)) +
  534. chalk.white(node.name) +
  535. ' ' + score
  536. );
  537. console.log(chalk.dim(` ${location}`));
  538. if (node.signature) {
  539. console.log(chalk.dim(` ${node.signature}`));
  540. }
  541. console.log();
  542. }
  543. }
  544. }
  545. cg.destroy();
  546. } catch (err) {
  547. error(`Search failed: ${err instanceof Error ? err.message : String(err)}`);
  548. process.exit(1);
  549. }
  550. });
  551. /**
  552. * codegraph files [path]
  553. */
  554. program
  555. .command('files')
  556. .description('Show project file structure from the index')
  557. .option('-p, --path <path>', 'Project path')
  558. .option('--filter <dir>', 'Filter to files under this directory')
  559. .option('--pattern <glob>', 'Filter files matching this glob pattern')
  560. .option('--format <format>', 'Output format (tree, flat, grouped)', 'tree')
  561. .option('--max-depth <number>', 'Maximum directory depth for tree format')
  562. .option('--no-metadata', 'Hide file metadata (language, symbol count)')
  563. .option('-j, --json', 'Output as JSON')
  564. .action(async (options: {
  565. path?: string;
  566. filter?: string;
  567. pattern?: string;
  568. format?: string;
  569. maxDepth?: string;
  570. metadata?: boolean;
  571. json?: boolean;
  572. }) => {
  573. const projectPath = resolveProjectPath(options.path);
  574. try {
  575. if (!isInitialized(projectPath)) {
  576. error(`CodeGraph not initialized in ${projectPath}`);
  577. process.exit(1);
  578. }
  579. const { default: CodeGraph } = await loadCodeGraph();
  580. const cg = await CodeGraph.open(projectPath);
  581. let files = cg.getFiles();
  582. if (files.length === 0) {
  583. info('No files indexed. Run "codegraph index" first.');
  584. cg.destroy();
  585. return;
  586. }
  587. // Filter by path prefix
  588. if (options.filter) {
  589. const filter = options.filter;
  590. files = files.filter(f => f.path.startsWith(filter) || f.path.startsWith('./' + filter));
  591. }
  592. // Filter by glob pattern
  593. if (options.pattern) {
  594. const regex = globToRegex(options.pattern);
  595. files = files.filter(f => regex.test(f.path));
  596. }
  597. if (files.length === 0) {
  598. info('No files found matching the criteria.');
  599. cg.destroy();
  600. return;
  601. }
  602. // JSON output
  603. if (options.json) {
  604. const output = files.map(f => ({
  605. path: f.path,
  606. language: f.language,
  607. nodeCount: f.nodeCount,
  608. size: f.size,
  609. }));
  610. console.log(JSON.stringify(output, null, 2));
  611. cg.destroy();
  612. return;
  613. }
  614. const includeMetadata = options.metadata !== false;
  615. const format = options.format || 'tree';
  616. const maxDepth = options.maxDepth ? parseInt(options.maxDepth, 10) : undefined;
  617. // Format output
  618. switch (format) {
  619. case 'flat':
  620. console.log(chalk.bold(`\nFiles (${files.length}):\n`));
  621. for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
  622. if (includeMetadata) {
  623. console.log(` ${file.path} ${chalk.dim(`(${file.language}, ${file.nodeCount} symbols)`)}`);
  624. } else {
  625. console.log(` ${file.path}`);
  626. }
  627. }
  628. break;
  629. case 'grouped':
  630. console.log(chalk.bold(`\nFiles by Language (${files.length} total):\n`));
  631. const byLang = new Map<string, typeof files>();
  632. for (const file of files) {
  633. const existing = byLang.get(file.language) || [];
  634. existing.push(file);
  635. byLang.set(file.language, existing);
  636. }
  637. const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
  638. for (const [lang, langFiles] of sortedLangs) {
  639. console.log(chalk.cyan(`${lang} (${langFiles.length}):`));
  640. for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
  641. if (includeMetadata) {
  642. console.log(` ${file.path} ${chalk.dim(`(${file.nodeCount} symbols)`)}`);
  643. } else {
  644. console.log(` ${file.path}`);
  645. }
  646. }
  647. console.log();
  648. }
  649. break;
  650. case 'tree':
  651. default:
  652. console.log(chalk.bold(`\nProject Structure (${files.length} files):\n`));
  653. printFileTree(files, includeMetadata, maxDepth, chalk);
  654. break;
  655. }
  656. console.log();
  657. cg.destroy();
  658. } catch (err) {
  659. error(`Failed to list files: ${err instanceof Error ? err.message : String(err)}`);
  660. process.exit(1);
  661. }
  662. });
  663. /**
  664. * Convert glob pattern to regex
  665. */
  666. function globToRegex(pattern: string): RegExp {
  667. const escaped = pattern
  668. .replace(/[.+^${}()|[\]\\]/g, '\\$&')
  669. .replace(/\*\*/g, '{{GLOBSTAR}}')
  670. .replace(/\*/g, '[^/]*')
  671. .replace(/\?/g, '[^/]')
  672. .replace(/\{\{GLOBSTAR\}\}/g, '.*');
  673. return new RegExp(escaped);
  674. }
  675. /**
  676. * Print files as a tree
  677. */
  678. function printFileTree(
  679. files: { path: string; language: string; nodeCount: number }[],
  680. includeMetadata: boolean,
  681. maxDepth: number | undefined,
  682. chalk: { dim: (s: string) => string; cyan: (s: string) => string }
  683. ): void {
  684. interface TreeNode {
  685. name: string;
  686. children: Map<string, TreeNode>;
  687. file?: { language: string; nodeCount: number };
  688. }
  689. const root: TreeNode = { name: '', children: new Map() };
  690. for (const file of files) {
  691. const parts = file.path.split('/');
  692. let current = root;
  693. for (let i = 0; i < parts.length; i++) {
  694. const part = parts[i];
  695. if (!part) continue;
  696. if (!current.children.has(part)) {
  697. current.children.set(part, { name: part, children: new Map() });
  698. }
  699. current = current.children.get(part)!;
  700. if (i === parts.length - 1) {
  701. current.file = { language: file.language, nodeCount: file.nodeCount };
  702. }
  703. }
  704. }
  705. const renderNode = (node: TreeNode, prefix: string, isLast: boolean, depth: number): void => {
  706. if (maxDepth !== undefined && depth > maxDepth) return;
  707. const connector = isLast ? '└── ' : '├── ';
  708. const childPrefix = isLast ? ' ' : '│ ';
  709. if (node.name) {
  710. let line = prefix + connector + node.name;
  711. if (node.file && includeMetadata) {
  712. line += chalk.dim(` (${node.file.language}, ${node.file.nodeCount} symbols)`);
  713. }
  714. console.log(line);
  715. }
  716. const children = [...node.children.values()];
  717. children.sort((a, b) => {
  718. const aIsDir = a.children.size > 0 && !a.file;
  719. const bIsDir = b.children.size > 0 && !b.file;
  720. if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;
  721. return a.name.localeCompare(b.name);
  722. });
  723. for (let i = 0; i < children.length; i++) {
  724. const child = children[i]!;
  725. const nextPrefix = node.name ? prefix + childPrefix : prefix;
  726. renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
  727. }
  728. };
  729. renderNode(root, '', true, 0);
  730. }
  731. /**
  732. * codegraph context <task>
  733. */
  734. program
  735. .command('context <task>')
  736. .description('Build context for a task (outputs markdown)')
  737. .option('-p, --path <path>', 'Project path')
  738. .option('-n, --max-nodes <number>', 'Maximum nodes to include', '50')
  739. .option('-c, --max-code <number>', 'Maximum code blocks', '10')
  740. .option('--no-code', 'Exclude code blocks')
  741. .option('-f, --format <format>', 'Output format (markdown, json)', 'markdown')
  742. .action(async (task: string, options: {
  743. path?: string;
  744. maxNodes?: string;
  745. maxCode?: string;
  746. code?: boolean;
  747. format?: string;
  748. }) => {
  749. const projectPath = resolveProjectPath(options.path);
  750. try {
  751. if (!isInitialized(projectPath)) {
  752. error(`CodeGraph not initialized in ${projectPath}`);
  753. process.exit(1);
  754. }
  755. const { default: CodeGraph } = await loadCodeGraph();
  756. const cg = await CodeGraph.open(projectPath);
  757. const context = await cg.buildContext(task, {
  758. maxNodes: parseInt(options.maxNodes || '50', 10),
  759. maxCodeBlocks: parseInt(options.maxCode || '10', 10),
  760. includeCode: options.code !== false,
  761. format: options.format as 'markdown' | 'json',
  762. });
  763. // Output the context
  764. console.log(context);
  765. cg.destroy();
  766. } catch (err) {
  767. error(`Failed to build context: ${err instanceof Error ? err.message : String(err)}`);
  768. process.exit(1);
  769. }
  770. });
  771. /**
  772. * codegraph serve
  773. */
  774. program
  775. .command('serve')
  776. .description('Start CodeGraph as an MCP server for AI assistants')
  777. .option('-p, --path <path>', 'Project path (optional for MCP mode, uses rootUri from client)')
  778. .option('--mcp', 'Run as MCP server (stdio transport)')
  779. .action(async (options: { path?: string; mcp?: boolean }) => {
  780. const projectPath = options.path ? resolveProjectPath(options.path) : undefined;
  781. try {
  782. if (options.mcp) {
  783. // Start MCP server - it handles initialization lazily based on rootUri from client
  784. const { MCPServer } = await import('../mcp/index');
  785. const server = new MCPServer(projectPath);
  786. await server.start();
  787. // Server will run until terminated
  788. } else {
  789. // Default: show info about MCP mode.
  790. // Use stderr so stdout stays clean for any piped/stdio usage.
  791. console.error(chalk.bold('\nCodeGraph MCP Server\n'));
  792. console.error(chalk.blue('ℹ') + ' Use --mcp flag to start the MCP server');
  793. console.error('\nTo use with Claude Code, add to your MCP configuration:');
  794. console.error(chalk.dim(`
  795. {
  796. "mcpServers": {
  797. "codegraph": {
  798. "command": "codegraph",
  799. "args": ["serve", "--mcp"]
  800. }
  801. }
  802. }
  803. `));
  804. console.error('Available tools:');
  805. console.error(chalk.cyan(' codegraph_search') + ' - Search for code symbols');
  806. console.error(chalk.cyan(' codegraph_context') + ' - Build context for a task');
  807. console.error(chalk.cyan(' codegraph_callers') + ' - Find callers of a symbol');
  808. console.error(chalk.cyan(' codegraph_callees') + ' - Find what a symbol calls');
  809. console.error(chalk.cyan(' codegraph_impact') + ' - Analyze impact of changes');
  810. console.error(chalk.cyan(' codegraph_node') + ' - Get symbol details');
  811. console.error(chalk.cyan(' codegraph_files') + ' - Get project file structure');
  812. console.error(chalk.cyan(' codegraph_status') + ' - Get index status');
  813. }
  814. } catch (err) {
  815. error(`Failed to start server: ${err instanceof Error ? err.message : String(err)}`);
  816. process.exit(1);
  817. }
  818. });
  819. /**
  820. * codegraph visualize [path]
  821. */
  822. program
  823. .command('visualize [path]')
  824. .description('Open interactive graph visualization in your browser')
  825. .option('-p, --port <port>', 'Port to listen on (default: auto)', parseInt)
  826. .option('--no-open', 'Do not open browser automatically')
  827. .action(async (pathArg: string | undefined, options: { port?: number; open?: boolean }) => {
  828. const projectPath = resolveProjectPath(pathArg);
  829. try {
  830. if (!isInitialized(projectPath)) {
  831. error(`CodeGraph not initialized in ${projectPath}`);
  832. info('Run "codegraph init -i" first');
  833. process.exit(1);
  834. }
  835. const { default: CodeGraph } = await loadCodeGraph();
  836. const cg = await CodeGraph.open(projectPath);
  837. const stats = cg.getStats();
  838. console.log(chalk.bold('\n CodeGraph Explorer\n'));
  839. info(`Project: ${projectPath}`);
  840. info(`Indexed: ${formatNumber(stats.nodeCount)} nodes, ${formatNumber(stats.edgeCount)} edges, ${formatNumber(stats.fileCount)} files\n`);
  841. const { VisualizerServer } = await import('../visualizer/server');
  842. const server = new VisualizerServer(cg);
  843. const { url } = await server.start({ port: options.port, openBrowser: options.open !== false });
  844. success(`Visualizer running at ${chalk.cyan(url)}`);
  845. console.log(chalk.dim(' Press Ctrl+C to stop\n'));
  846. // Open browser
  847. if (options.open !== false) {
  848. const openCmd = process.platform === 'darwin' ? 'open' :
  849. process.platform === 'win32' ? 'start' : 'xdg-open';
  850. spawn(openCmd, [url], { detached: true, stdio: 'ignore' }).unref();
  851. }
  852. // Handle shutdown — force exit on second Ctrl+C
  853. let shuttingDown = false;
  854. const shutdown = () => {
  855. if (shuttingDown) {
  856. process.exit(1);
  857. }
  858. shuttingDown = true;
  859. console.log(chalk.dim('\n Shutting down...'));
  860. server.stop().then(() => {
  861. cg.close();
  862. process.exit(0);
  863. }).catch(() => process.exit(1));
  864. // Force exit after 2s if graceful shutdown hangs
  865. setTimeout(() => process.exit(1), 2000).unref();
  866. };
  867. process.on('SIGINT', shutdown);
  868. process.on('SIGTERM', shutdown);
  869. } catch (err) {
  870. error(`Failed to start visualizer: ${err instanceof Error ? err.message : String(err)}`);
  871. process.exit(1);
  872. }
  873. });
  874. /**
  875. * codegraph mark-dirty [path]
  876. *
  877. * Touches .codegraph/.dirty to signal that files have changed.
  878. * Used by Claude Code PostToolUse hooks to batch syncs.
  879. * Runs silently and always exits 0.
  880. */
  881. program
  882. .command('mark-dirty [path]')
  883. .description('Mark project as needing sync (used by Claude Code hooks)')
  884. .action(async (pathArg: string | undefined) => {
  885. try {
  886. const startPath = path.resolve(pathArg || process.cwd());
  887. const projectRoot = findNearestCodeGraphRoot(startPath);
  888. if (!projectRoot) {
  889. // No .codegraph/ found — exit silently
  890. process.exit(0);
  891. }
  892. const dirtyPath = path.join(getCodeGraphDir(projectRoot), '.dirty');
  893. fs.writeFileSync(dirtyPath, Date.now().toString(), 'utf-8');
  894. } catch {
  895. // Never fail — this runs in the background during edits
  896. }
  897. process.exit(0);
  898. });
  899. /**
  900. * codegraph sync-if-dirty [path]
  901. *
  902. * Checks if .codegraph/.dirty exists and, if so, spawns a detached
  903. * background process to run `codegraph sync`. The hook process exits
  904. * immediately so Claude Code's Stop hook never blocks.
  905. *
  906. * Removes the marker BEFORE spawning so edits during sync
  907. * create a new marker for the next Stop event.
  908. * Runs silently and always exits 0.
  909. */
  910. program
  911. .command('sync-if-dirty [path]')
  912. .description('Sync if project was marked dirty (used by Claude Code hooks)')
  913. .action(async (pathArg: string | undefined) => {
  914. try {
  915. const startPath = path.resolve(pathArg || process.cwd());
  916. const projectRoot = findNearestCodeGraphRoot(startPath);
  917. if (!projectRoot) {
  918. process.exit(0);
  919. }
  920. const dirtyPath = path.join(getCodeGraphDir(projectRoot!), '.dirty');
  921. // No marker → nothing to do (sub-ms exit)
  922. if (!fs.existsSync(dirtyPath)) {
  923. process.exit(0);
  924. }
  925. // Remove marker FIRST so edits during sync create a new one
  926. try { fs.unlinkSync(dirtyPath); } catch { /* ignore */ }
  927. // If not fully initialized (no DB), exit
  928. if (!isInitialized(projectRoot!)) {
  929. process.exit(0);
  930. }
  931. // Spawn sync as a detached background process
  932. // so this hook exits immediately and doesn't block Claude Code.
  933. // Uses process.argv[0]/[1] (e.g. node /path/to/codegraph.js) so it
  934. // works whether invoked via global install, npx, or directly.
  935. const child = spawn(
  936. process.argv[0]!,
  937. [process.argv[1]!, 'sync', '--quiet', projectRoot!],
  938. {
  939. detached: true,
  940. stdio: 'ignore',
  941. windowsHide: true,
  942. }
  943. );
  944. child.unref();
  945. } catch {
  946. // Never fail — this runs at the end of Claude responses
  947. }
  948. process.exit(0);
  949. });
  950. /**
  951. * codegraph unlock [path]
  952. */
  953. program
  954. .command('unlock [path]')
  955. .description('Remove a stale lock file that is blocking indexing')
  956. .action(async (pathArg: string | undefined) => {
  957. const projectPath = resolveProjectPath(pathArg);
  958. try {
  959. if (!isInitialized(projectPath)) {
  960. error(`CodeGraph not initialized in ${projectPath}`);
  961. return;
  962. }
  963. const lockPath = path.join(getCodeGraphDir(projectPath), 'codegraph.lock');
  964. if (!fs.existsSync(lockPath)) {
  965. info('No lock file found — nothing to do');
  966. return;
  967. }
  968. fs.unlinkSync(lockPath);
  969. success('Removed lock file. You can now run indexing again.');
  970. } catch (err) {
  971. error(`Failed to remove lock: ${err instanceof Error ? err.message : String(err)}`);
  972. process.exit(1);
  973. }
  974. });
  975. /**
  976. * codegraph affected [files...]
  977. *
  978. * Find test files affected by the given source files.
  979. * Traces dependency edges transitively to find test files that depend on changed code.
  980. *
  981. * Usage:
  982. * git diff --name-only | codegraph affected --stdin
  983. * codegraph affected src/lib/components/Editor.svelte src/routes/+page.svelte
  984. */
  985. program
  986. .command('affected [files...]')
  987. .description('Find test files affected by changed source files')
  988. .option('-p, --path <path>', 'Project path')
  989. .option('--stdin', 'Read file list from stdin (one per line)')
  990. .option('-d, --depth <number>', 'Max dependency traversal depth', '5')
  991. .option('-f, --filter <glob>', 'Custom glob filter for test files (e.g. "e2e/*.spec.ts")')
  992. .option('-j, --json', 'Output as JSON')
  993. .option('-q, --quiet', 'Only output file paths, no decoration')
  994. .action(async (fileArgs: string[], options: { path?: string; stdin?: boolean; depth?: string; filter?: string; json?: boolean; quiet?: boolean }) => {
  995. const projectPath = resolveProjectPath(options.path);
  996. try {
  997. if (!isInitialized(projectPath)) {
  998. error(`CodeGraph not initialized in ${projectPath}`);
  999. process.exit(1);
  1000. }
  1001. // Collect changed files from args or stdin
  1002. let changedFiles: string[] = [...(fileArgs || [])];
  1003. if (options.stdin) {
  1004. const stdinData = fs.readFileSync(0, 'utf-8');
  1005. const stdinFiles = stdinData.split('\n').map(f => f.trim()).filter(Boolean);
  1006. changedFiles.push(...stdinFiles);
  1007. }
  1008. if (changedFiles.length === 0) {
  1009. if (!options.quiet) info('No files provided. Use file arguments or --stdin.');
  1010. process.exit(0);
  1011. }
  1012. const { default: CodeGraph } = await loadCodeGraph();
  1013. const cg = await CodeGraph.open(projectPath);
  1014. const maxDepth = parseInt(options.depth || '5', 10);
  1015. // Common test file patterns
  1016. const defaultTestPatterns = [
  1017. /\.spec\./,
  1018. /\.test\./,
  1019. /\/__tests__\//,
  1020. /\/tests?\//,
  1021. /\/e2e\//,
  1022. /\/spec\//,
  1023. ];
  1024. // Custom filter pattern
  1025. let customFilter: RegExp | null = null;
  1026. if (options.filter) {
  1027. // Convert glob to regex: ** → .+, * → [^/]*, . → \.
  1028. const regex = options.filter
  1029. .replace(/[+[\]{}()^$|\\]/g, '\\$&')
  1030. .replace(/\./g, '\\.')
  1031. .replace(/\*\*/g, '.+')
  1032. .replace(/\*/g, '[^/]*');
  1033. customFilter = new RegExp(regex);
  1034. }
  1035. function isTestFile(filePath: string): boolean {
  1036. if (customFilter) return customFilter.test(filePath);
  1037. return defaultTestPatterns.some(p => p.test(filePath));
  1038. }
  1039. // BFS to find all transitive dependents of changed files, filtered to test files
  1040. const affectedTests = new Set<string>();
  1041. const allDependents = new Set<string>();
  1042. for (const file of changedFiles) {
  1043. // If the changed file is itself a test file, include it
  1044. if (isTestFile(file)) {
  1045. affectedTests.add(file);
  1046. continue;
  1047. }
  1048. // BFS through dependents
  1049. const queue: Array<{ file: string; depth: number }> = [{ file, depth: 0 }];
  1050. const visited = new Set<string>();
  1051. visited.add(file);
  1052. while (queue.length > 0) {
  1053. const current = queue.shift()!;
  1054. if (current.depth >= maxDepth) continue;
  1055. const dependents = cg.getFileDependents(current.file);
  1056. for (const dep of dependents) {
  1057. if (visited.has(dep)) continue;
  1058. visited.add(dep);
  1059. allDependents.add(dep);
  1060. if (isTestFile(dep)) {
  1061. affectedTests.add(dep);
  1062. } else {
  1063. queue.push({ file: dep, depth: current.depth + 1 });
  1064. }
  1065. }
  1066. }
  1067. }
  1068. const sortedTests = Array.from(affectedTests).sort();
  1069. // Output
  1070. if (options.json) {
  1071. console.log(JSON.stringify({
  1072. changedFiles,
  1073. affectedTests: sortedTests,
  1074. totalDependentsTraversed: allDependents.size,
  1075. }, null, 2));
  1076. } else if (options.quiet) {
  1077. for (const t of sortedTests) console.log(t);
  1078. } else {
  1079. if (sortedTests.length === 0) {
  1080. info('No test files affected by the changed files.');
  1081. } else {
  1082. console.log(chalk.bold(`\nAffected test files (${sortedTests.length}):\n`));
  1083. for (const t of sortedTests) {
  1084. console.log(' ' + chalk.cyan(t));
  1085. }
  1086. console.log();
  1087. }
  1088. }
  1089. cg.destroy();
  1090. } catch (err) {
  1091. error(`Affected analysis failed: ${err instanceof Error ? err.message : String(err)}`);
  1092. process.exit(1);
  1093. }
  1094. });
  1095. /**
  1096. * codegraph install
  1097. */
  1098. program
  1099. .command('install')
  1100. .description('Run interactive installer for Claude Code integration')
  1101. .action(async () => {
  1102. const { runInstaller } = await import('../installer');
  1103. await runInstaller();
  1104. });
  1105. // Parse and run
  1106. program.parse();
  1107. } // end main()