codegraph.ts 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501
  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 uninstall Remove CodeGraph from your agents
  11. * codegraph init [path] Initialize CodeGraph in a project
  12. * codegraph uninit [path] Remove CodeGraph from a project
  13. * codegraph index [path] Index all files in the project
  14. * codegraph sync [path] Sync changes since last index
  15. * codegraph status [path] Show index status
  16. * codegraph query <search> Search for symbols
  17. * codegraph files [options] Show project file structure
  18. * codegraph context <task> Build context for a task
  19. * codegraph callers <symbol> Find what calls a function/method
  20. * codegraph callees <symbol> Find what a function/method calls
  21. * codegraph impact <symbol> Analyze what code is affected by changing a symbol
  22. * codegraph affected [files] Find test files affected by changes
  23. * codegraph upgrade [version] Update CodeGraph to the latest release
  24. */
  25. // FIRST import, before anything else loads: capture process.ppid while our
  26. // launcher is (almost certainly) still alive. A launcher killed mid-startup
  27. // otherwise blinds the PPID watchdog forever (#1185) — see early-ppid.ts.
  28. import '../mcp/early-ppid';
  29. // Persist V8 compile artifacts across runs (Node ≥22.8). Every invocation —
  30. // and every worker thread, which re-requires the whole extraction module
  31. // graph — skips recompiling unchanged sources. Worth hundreds of ms of
  32. // worker-boot latency per bulk index; harmless no-op when unavailable.
  33. try {
  34. // eslint-disable-next-line @typescript-eslint/no-require-imports
  35. (require('node:module') as { enableCompileCache?: () => void }).enableCompileCache?.();
  36. } catch { /* cache is best-effort */ }
  37. import { Command } from 'commander';
  38. import * as path from 'path';
  39. import * as fs from 'fs';
  40. import { getCodeGraphDir, isInitialized, unsafeIndexRootReason, findNearestCodeGraphRoot, planFrontload, hasStructuralKeyword, extractCodeTokens } from '../directory';
  41. import { extractProseCandidates } from '../search/identifier-segments';
  42. import { detectWorktreeIndexMismatch, worktreeMismatchWarning } from '../sync/worktree';
  43. import { createShimmerProgress } from '../ui/shimmer-progress';
  44. import { getGlyphs } from '../ui/glyphs';
  45. import { ansiColorsEnabled } from '../ui/color';
  46. import { buildNode25BlockBanner, buildNodeTooOldBanner, MIN_NODE_MAJOR } from './node-version-check';
  47. import { installFatalHandlers } from './fatal-handler';
  48. import { relaunchWithWasmRuntimeFlagsIfNeeded } from '../extraction/wasm-runtime-flags';
  49. import { installCommandSupervision } from './command-supervision';
  50. import { EXTRACTION_VERSION } from '../extraction/extraction-version';
  51. import { getTelemetry, TELEMETRY_DOCS, recordIndexEvent } from '../telemetry';
  52. // Decided once, before `--color`/`--no-color` are stripped from argv below
  53. // (#1281). Piped/redirected stdout, NO_COLOR, or --no-color -> plain output.
  54. const COLORS_ENABLED = ansiColorsEnabled();
  55. // Lazy-load heavy modules (CodeGraph, runInstaller) to keep CLI startup fast.
  56. async function loadCodeGraph(): Promise<typeof import('../index')> {
  57. try {
  58. return await import('../index');
  59. } catch (err) {
  60. const msg = err instanceof Error ? err.message : String(err);
  61. const [red, reset] = COLORS_ENABLED ? ['\x1b[31m', '\x1b[0m'] : ['', ''];
  62. console.error(`${red}${getGlyphs().err}${reset} Failed to load CodeGraph modules.`);
  63. console.error(`\n Node: ${process.version} Platform: ${process.platform} ${process.arch}`);
  64. console.error(`\n Error: ${msg}`);
  65. console.error('\n Try reinstalling with: npm install -g @colbymchenry/codegraph\n');
  66. process.exit(1);
  67. }
  68. }
  69. // Dynamic import helper — tsc compiles import() to require() in CJS mode,
  70. // which fails for ESM-only packages. This bypasses the transformation.
  71. // eslint-disable-next-line @typescript-eslint/no-implied-eval
  72. const importESM = new Function('specifier', 'return import(specifier)') as
  73. (specifier: string) => Promise<typeof import('@clack/prompts')>;
  74. // Block CodeGraph on Node.js 25.x — V8's turboshaft WASM JIT has a Zone
  75. // allocator bug that reliably crashes when compiling tree-sitter
  76. // grammars (see #54, #81, #140). The previous behaviour was a soft
  77. // console.warn that scrolls off-screen before the OOM crash 30 seconds
  78. // later, leading to a steady stream of "what is this OOM" reports.
  79. // Hard-exit before any WASM work; allow override via env var for users
  80. // who patched V8 themselves or want to test a future fix.
  81. const nodeVersion = process.versions.node;
  82. const nodeMajor = parseInt(nodeVersion.split('.')[0] ?? '0', 10);
  83. if (nodeMajor >= 25) {
  84. process.stderr.write(buildNode25BlockBanner(nodeVersion) + '\n');
  85. if (!process.env.CODEGRAPH_ALLOW_UNSAFE_NODE) {
  86. process.exit(1);
  87. }
  88. // Override active — banner shown for visibility, continuing.
  89. }
  90. // Enforce the supported Node floor. `engines` in package.json only *warns* on
  91. // install (unless engine-strict), so hard-block here to actually keep users off
  92. // unsupported versions. Mirrors the 25+ block above. See package.json `engines`.
  93. if (nodeMajor < MIN_NODE_MAJOR) {
  94. process.stderr.write(buildNodeTooOldBanner(nodeVersion) + '\n');
  95. if (!process.env.CODEGRAPH_ALLOW_UNSAFE_NODE) {
  96. process.exit(1);
  97. }
  98. // Override active — banner shown for visibility, continuing.
  99. }
  100. // Re-exec with V8's `--liftoff-only` if it isn't already set, so tree-sitter's
  101. // large WASM grammars never hit the turboshaft Zone OOM (`Fatal process out of
  102. // memory: Zone`) on Node >= 22. No-op under the bundled launcher, which already
  103. // passes the flag. Must run before any grammar (in the parse worker, which
  104. // inherits this process's flags) is compiled. See ../extraction/wasm-runtime-flags.
  105. relaunchWithWasmRuntimeFlagsIfNeeded(__filename);
  106. // Last-resort fatal handlers: log a bounded line and exit non-zero. A fault
  107. // that reaches here escaped every boundary, so the process is in an undefined
  108. // state — keeping it alive is what let the detached MCP daemon orphan and pin a
  109. // CPU core with no recovery (#799, #850). Installed before the command branch
  110. // so it also covers a synchronous throw during startup. See ./fatal-handler.
  111. installFatalHandlers();
  112. // Check if running with no arguments - run installer
  113. if (process.argv.length === 2) {
  114. import('../installer').then(({ runInstaller }) =>
  115. runInstaller()
  116. ).catch((err) => {
  117. console.error('Installation failed:', err instanceof Error ? err.message : String(err));
  118. process.exit(1);
  119. });
  120. } else {
  121. // Normal CLI flow
  122. main();
  123. }
  124. function main() {
  125. const program = new Command();
  126. // Version from package.json
  127. const packageJson = JSON.parse(
  128. fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf-8')
  129. );
  130. // Make the version trivial to reach. commander's `.version()` (below) wires up
  131. // `--version` and `-V`; intercept the spellings it can't — lowercase `-v` and
  132. // single-dash `-version` — before any parsing. (commander's version short flag
  133. // is the capital `-V`, and its parser rejects a multi-character single-dash
  134. // flag.) The bare `codegraph version` subcommand is registered further down so
  135. // the affordance also shows up in `codegraph --help`.
  136. const firstArg = process.argv[2];
  137. if (firstArg === '-v' || firstArg === '-version') {
  138. console.log(packageJson.version);
  139. return;
  140. }
  141. // =============================================================================
  142. // ANSI Color Helpers (avoid chalk ESM issues)
  143. // =============================================================================
  144. // `--color` / `--no-color` are global and position-independent — they were
  145. // already read by ansiColorsEnabled() at module load, so strip them before
  146. // commander parses (a subcommand would otherwise reject the unknown flag).
  147. process.argv = process.argv.filter((a) => a !== '--color' && a !== '--no-color');
  148. const colors = COLORS_ENABLED
  149. ? {
  150. reset: '\x1b[0m',
  151. bold: '\x1b[1m',
  152. dim: '\x1b[2m',
  153. red: '\x1b[31m',
  154. green: '\x1b[32m',
  155. yellow: '\x1b[33m',
  156. blue: '\x1b[34m',
  157. cyan: '\x1b[36m',
  158. white: '\x1b[37m',
  159. gray: '\x1b[90m',
  160. }
  161. : {
  162. reset: '',
  163. bold: '',
  164. dim: '',
  165. red: '',
  166. green: '',
  167. yellow: '',
  168. blue: '',
  169. cyan: '',
  170. white: '',
  171. gray: '',
  172. };
  173. const chalk = {
  174. bold: (s: string) => `${colors.bold}${s}${colors.reset}`,
  175. dim: (s: string) => `${colors.dim}${s}${colors.reset}`,
  176. red: (s: string) => `${colors.red}${s}${colors.reset}`,
  177. green: (s: string) => `${colors.green}${s}${colors.reset}`,
  178. yellow: (s: string) => `${colors.yellow}${s}${colors.reset}`,
  179. blue: (s: string) => `${colors.blue}${s}${colors.reset}`,
  180. cyan: (s: string) => `${colors.cyan}${s}${colors.reset}`,
  181. white: (s: string) => `${colors.white}${s}${colors.reset}`,
  182. gray: (s: string) => `${colors.gray}${s}${colors.reset}`,
  183. };
  184. program
  185. .name('codegraph')
  186. .description('Code intelligence and knowledge graph for any codebase')
  187. .version(packageJson.version)
  188. // Parsed manually before commander runs (any argv position works); declared
  189. // here so they show up in --help. NO_COLOR / FORCE_COLOR env vars are also
  190. // honored, and piped output defaults to no color (#1281).
  191. .option('--color', 'force ANSI colors even when stdout is not a TTY')
  192. .option('--no-color', 'disable ANSI colors (NO_COLOR env is also honored)');
  193. // Anonymous usage telemetry (see TELEMETRY.md): record the invoked subcommand
  194. // NAME only — never arguments or paths. Counts buffer locally; network sends
  195. // piggyback on commands that run long anyway (quick commands only append to
  196. // the local buffer at exit, costing nothing).
  197. // install/uninstall are absent on purpose: the installer flushes at its own
  198. // end, AFTER its consent prompt — a flush here would fire the first-run
  199. // notice before the user ever sees the toggle.
  200. const TELEMETRY_FLUSH_COMMANDS = new Set(['init', 'uninit', 'index', 'sync', 'upgrade']);
  201. program.hook('preAction', (_thisCommand, actionCommand) => {
  202. try {
  203. // The detached daemon re-invokes `serve --mcp` internally — not a user action.
  204. if (process.env.CODEGRAPH_DAEMON_INTERNAL) return;
  205. const name = actionCommand.name();
  206. if (name === 'telemetry') return; // managing telemetry is not usage
  207. getTelemetry().recordUsage('cli_command', name, true);
  208. if (TELEMETRY_FLUSH_COMMANDS.has(name)) getTelemetry().maybeFlush();
  209. } catch {
  210. /* telemetry must never break the CLI */
  211. }
  212. });
  213. // =============================================================================
  214. // Helper Functions
  215. // =============================================================================
  216. /**
  217. * Resolve project path from argument or current directory
  218. * Walks up parent directories to find nearest initialized CodeGraph project
  219. * (must have .codegraph/codegraph.db, not just .codegraph/lessons.db)
  220. */
  221. function resolveProjectPath(pathArg?: string): string {
  222. const absolutePath = path.resolve(pathArg || process.cwd());
  223. // If exact path is initialized (has codegraph.db), use it
  224. if (isInitialized(absolutePath)) {
  225. return absolutePath;
  226. }
  227. // Walk up to find nearest parent with CodeGraph initialized
  228. // Note: findNearestCodeGraphRoot finds any .codegraph folder, but we need one with codegraph.db
  229. let current = absolutePath;
  230. const root = path.parse(current).root;
  231. while (current !== root) {
  232. const parent = path.dirname(current);
  233. if (parent === current) break;
  234. current = parent;
  235. if (isInitialized(current)) {
  236. return current;
  237. }
  238. }
  239. // Not found - return original path (will fail later with helpful error)
  240. return absolutePath;
  241. }
  242. /**
  243. * Format a number with commas
  244. */
  245. function formatNumber(n: number): string {
  246. return n.toLocaleString();
  247. }
  248. /**
  249. * Format duration in milliseconds to human readable
  250. */
  251. function formatDuration(ms: number): string {
  252. if (ms < 1000) {
  253. return `${ms}ms`;
  254. }
  255. const seconds = ms / 1000;
  256. if (seconds < 60) {
  257. return `${seconds.toFixed(1)}s`;
  258. }
  259. const minutes = Math.floor(seconds / 60);
  260. const remainingSeconds = seconds % 60;
  261. return `${minutes}m ${remainingSeconds.toFixed(0)}s`;
  262. }
  263. // Shimmer progress renderer (runs in a worker thread for smooth animation)
  264. // Imported at top of file from '../ui/shimmer-progress'
  265. /**
  266. * Create a plain-text progress callback for --verbose mode.
  267. * No animations, no ANSI tricks — just timestamped lines to stdout.
  268. */
  269. function createVerboseProgress(): (progress: { phase: string; current: number; total: number; currentFile?: string }) => void {
  270. let lastPhase = '';
  271. let lastPct = -1;
  272. const startTime = Date.now();
  273. return (progress) => {
  274. const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
  275. if (progress.phase !== lastPhase) {
  276. lastPhase = progress.phase;
  277. lastPct = -1;
  278. console.log(`[${elapsed}s] Phase: ${progress.phase}`);
  279. }
  280. if (progress.total > 0) {
  281. const pct = Math.floor((progress.current / progress.total) * 100);
  282. // Log every 5% to keep output manageable
  283. if (pct >= lastPct + 5 || progress.current === progress.total) {
  284. lastPct = pct;
  285. console.log(`[${elapsed}s] ${progress.current}/${progress.total} (${pct}%)${progress.currentFile ? ` ${getGlyphs().dash} ${progress.currentFile}` : ''}`);
  286. }
  287. } else if (progress.current > 0) {
  288. // Scanning phase (no total yet) — log periodically
  289. if (progress.current % 1000 === 0 || progress.current === 1) {
  290. console.log(`[${elapsed}s] ${formatNumber(progress.current)} files found`);
  291. }
  292. }
  293. };
  294. }
  295. /**
  296. * Print success message
  297. */
  298. function success(message: string): void {
  299. console.log(chalk.green(getGlyphs().ok) + ' ' + message);
  300. }
  301. /**
  302. * Print error message
  303. */
  304. function error(message: string): void {
  305. console.error(chalk.red(getGlyphs().err) + ' ' + message);
  306. }
  307. /**
  308. * Print info message
  309. */
  310. function info(message: string): void {
  311. console.log(chalk.blue(getGlyphs().info) + ' ' + message);
  312. }
  313. /**
  314. * Print warning message
  315. */
  316. function warn(message: string): void {
  317. console.log(chalk.yellow(getGlyphs().warn) + ' ' + message);
  318. }
  319. type IndexResult = {
  320. success: boolean;
  321. filesIndexed: number;
  322. filesSkipped: number;
  323. filesErrored: number;
  324. nodesCreated: number;
  325. edgesCreated: number;
  326. errors: Array<{ message: string; filePath?: string; severity: string; code?: string }>;
  327. durationMs: number;
  328. };
  329. /**
  330. * Print indexing results using clack log methods
  331. */
  332. function printIndexResult(clack: typeof import('@clack/prompts'), result: IndexResult, projectPath?: string): void {
  333. const hasErrors = result.filesErrored > 0;
  334. // Surface non-file-level failures (e.g. lock-acquisition failure
  335. // when another indexer is running) before the file-count branches.
  336. // Without this the CLI falls through to "No files found to index",
  337. // which is actively misleading — the index DID run, it just couldn't
  338. // get the lock.
  339. //
  340. // If success is false but no severity:'error' entry exists in
  341. // `result.errors` (degenerate case — shouldn't happen in practice
  342. // but worth guarding because the result shape is plumbed through
  343. // multiple call sites), fall back to a generic message rather than
  344. // continuing to the misleading "No files found" branch or throwing.
  345. if (!result.success && !hasErrors && result.filesIndexed === 0) {
  346. const generic = result.errors.find((e) => e.severity === 'error');
  347. clack.log.error(generic?.message ?? `Indexing failed ${getGlyphs().dash} no further details available`);
  348. return;
  349. }
  350. if (result.filesIndexed > 0) {
  351. if (hasErrors) {
  352. clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files (${formatNumber(result.filesErrored)} could not be parsed)`);
  353. } else {
  354. clack.log.success(`Indexed ${formatNumber(result.filesIndexed)} files`);
  355. }
  356. clack.log.info(`${formatNumber(result.nodesCreated)} nodes, ${formatNumber(result.edgesCreated)} edges in ${formatDuration(result.durationMs)}`);
  357. // A PARTIAL index (files silently dropped mid-pipeline) must not pass
  358. // as a clean run — it's the difference between "indexed the repo" and
  359. // "indexed most of the repo, quietly". Only the completeness
  360. // reconciliation warning; per-file extractor warnings stay in the
  361. // error-code summary below.
  362. for (const w of result.errors.filter((e) => e.code === 'index_partial')) {
  363. clack.log.warn(w.message);
  364. }
  365. // Files salvaged from comment-stripped source after repeated parser
  366. // failures are indexed but possibly incomplete — say so here, or the run
  367. // reads as fully clean and the index quietly disagrees with a later
  368. // re-parse of the same bytes (#1565).
  369. const salvaged = result.errors.filter((e) => e.code === 'salvaged_stripped');
  370. if (salvaged.length > 0) {
  371. const sample = salvaged.slice(0, 3).map((e) => e.filePath).filter(Boolean).join(', ');
  372. const more = salvaged.length > 3 ? ', ...' : '';
  373. clack.log.warn(`${formatNumber(salvaged.length)} file(s) indexed from comment-stripped source after repeated parse failures ${getGlyphs().dash} symbols may be incomplete (${sample}${more})`);
  374. }
  375. } else if (hasErrors) {
  376. clack.log.error(`Indexing failed ${getGlyphs().dash} all ${formatNumber(result.filesErrored)} files had errors`);
  377. } else {
  378. clack.log.warn('No files found to index');
  379. }
  380. if (hasErrors) {
  381. const errorsByCode = new Map<string, number>();
  382. for (const err of result.errors) {
  383. if (err.severity === 'error') {
  384. const code = err.code || 'unknown';
  385. errorsByCode.set(code, (errorsByCode.get(code) || 0) + 1);
  386. }
  387. }
  388. const codeLabels: Record<string, string> = {
  389. parse_error: 'files failed to parse',
  390. read_error: 'files could not be read',
  391. size_exceeded: 'files exceeded size limit',
  392. path_traversal: 'blocked paths',
  393. unsupported_language: 'unsupported language',
  394. parser_error: 'parser initialization failures',
  395. };
  396. const breakdown = Array.from(errorsByCode)
  397. .map(([code, count]) => `${formatNumber(count)} ${codeLabels[code] || code}`)
  398. .join('\n');
  399. clack.note(breakdown, 'Error breakdown');
  400. if (projectPath) {
  401. writeErrorLog(projectPath, result.errors);
  402. clack.log.info('See .codegraph/errors.log for details');
  403. }
  404. if (result.filesIndexed > 0) {
  405. clack.log.info(`The index is fully usable ${getGlyphs().dash} only the failed files are missing.`);
  406. }
  407. } else if (projectPath) {
  408. // No hard errors. Salvaged-file warnings still belong in the log — it
  409. // carries the per-file detail behind the one-line summary above.
  410. if (result.errors.some((e) => e.code === 'salvaged_stripped')) {
  411. writeErrorLog(projectPath, result.errors);
  412. clack.log.info('See .codegraph/errors.log for details');
  413. } else {
  414. const logPath = path.join(getCodeGraphDir(projectPath), 'errors.log');
  415. if (fs.existsSync(logPath)) {
  416. fs.unlinkSync(logPath);
  417. }
  418. }
  419. }
  420. }
  421. /**
  422. * When an `init`/`index` produced an EMPTY graph and the reason is that the
  423. * project's own `.gitignore` excludes nested git repositories — the "super-repo
  424. * gitignores its child repos" layout (#1156), where `init` at the parent
  425. * correctly indexes ~nothing while `init` inside each child works — name those
  426. * repos and offer to index them. An interactive terminal gets a yes/no prompt
  427. * that writes `includeIgnored` to codegraph.json and re-indexes; a
  428. * non-interactive run just prints the one-line opt-in snippet. The caller gates
  429. * this on `nodesCreated === 0`, so a project that DID index real content is
  430. * never nagged about the gitignored reference clones it deliberately keeps out
  431. * (#970, #1065). Best-effort throughout: detection never breaks the command.
  432. */
  433. async function offerIndexIgnoredRepos(
  434. clack: typeof import('@clack/prompts'),
  435. projectPath: string,
  436. reindex: () => Promise<IndexResult>,
  437. opts: { interactive: boolean },
  438. ): Promise<IndexResult | undefined> {
  439. let repos: string[];
  440. try {
  441. const { findUnindexedIgnoredRepos } = await import('../extraction');
  442. repos = findUnindexedIgnoredRepos(projectPath);
  443. } catch {
  444. return; // detection is advisory — never let it break the command
  445. }
  446. if (repos.length === 0) return;
  447. const { PROJECT_CONFIG_FILENAME } = await import('../project-config');
  448. const isOne = repos.length === 1;
  449. const SHOWN = 6;
  450. const names = repos.slice(0, SHOWN).map((r) => r.replace(/\/$/, ''));
  451. const extra = repos.length > SHOWN ? ` (+${formatNumber(repos.length - SHOWN)} more)` : '';
  452. const snippet = `{ "includeIgnored": [${repos.map((p) => JSON.stringify(p)).join(', ')}] }`;
  453. clack.log.warn(
  454. `Your .gitignore excludes ${isOne ? 'a nested git repository' : `${formatNumber(repos.length)} nested git repositories`} here, ` +
  455. `so ${isOne ? 'it was' : 'they were'} not indexed: ${names.join(', ')}${extra}.`,
  456. );
  457. const manualHint = () => {
  458. clack.log.info(
  459. `If ${isOne ? "it's" : "they're"} your code, add ${isOne ? 'it' : 'them'} to ${PROJECT_CONFIG_FILENAME} and re-index:`,
  460. );
  461. clack.log.info(` ${snippet}`);
  462. };
  463. if (!opts.interactive || !process.stdin.isTTY) {
  464. manualHint();
  465. return;
  466. }
  467. const yes = await clack.confirm({
  468. message: `Index ${isOne ? 'it' : `these ${formatNumber(repos.length)}`} now? Adds ${isOne ? 'it' : 'them'} to ${PROJECT_CONFIG_FILENAME}.`,
  469. initialValue: true,
  470. });
  471. if (clack.isCancel(yes) || !yes) {
  472. manualHint();
  473. return;
  474. }
  475. let added: number;
  476. try {
  477. const { addIncludeIgnoredPatterns } = await import('../project-config');
  478. added = addIncludeIgnoredPatterns(projectPath, repos);
  479. } catch (err) {
  480. clack.log.error(`Could not update ${PROJECT_CONFIG_FILENAME}: ${err instanceof Error ? err.message : String(err)}`);
  481. manualHint();
  482. return;
  483. }
  484. clack.log.success(`Added ${formatNumber(added)} ${added === 1 ? 'entry' : 'entries'} to ${PROJECT_CONFIG_FILENAME} ${getGlyphs().dash} re-indexing…`);
  485. const result = await reindex();
  486. printIndexResult(clack, result, projectPath);
  487. return result;
  488. }
  489. /**
  490. * Write detailed error log to .codegraph/errors.log
  491. */
  492. function writeErrorLog(projectPath: string, errors: Array<{ message: string; filePath?: string; severity: string; code?: string }>): void {
  493. const cgDir = getCodeGraphDir(projectPath);
  494. if (!fs.existsSync(cgDir)) return;
  495. const logPath = path.join(cgDir, 'errors.log');
  496. // Group errors by file path
  497. const errorsByFile = new Map<string, Array<{ message: string; code?: string }>>();
  498. const noFileErrors: Array<{ message: string; code?: string }> = [];
  499. for (const err of errors) {
  500. if (err.severity !== 'error') continue;
  501. if (err.filePath) {
  502. let list = errorsByFile.get(err.filePath);
  503. if (!list) {
  504. list = [];
  505. errorsByFile.set(err.filePath, list);
  506. }
  507. list.push({ message: err.message, code: err.code });
  508. } else {
  509. noFileErrors.push({ message: err.message, code: err.code });
  510. }
  511. }
  512. const lines: string[] = [
  513. `CodeGraph Error Log - ${new Date().toISOString()}`,
  514. `${errorsByFile.size} files with errors`,
  515. '',
  516. ];
  517. for (const [filePath, fileErrors] of errorsByFile) {
  518. for (const err of fileErrors) {
  519. lines.push(`${filePath}: ${err.message}`);
  520. }
  521. }
  522. for (const err of noFileErrors) {
  523. lines.push(err.message);
  524. }
  525. fs.writeFileSync(logPath, lines.join('\n') + '\n');
  526. }
  527. /**
  528. * Telemetry for a completed full index (see TELEMETRY.md). The bounded flush
  529. * keeps init/index responsive (these commands just ran for seconds anyway)
  530. * while delivering the event promptly.
  531. */
  532. async function recordIndexTelemetry(
  533. cg: { getStats(): { filesByLanguage: Record<string, number> }; getBackend(): string },
  534. result: IndexResult,
  535. ): Promise<void> {
  536. recordIndexEvent(cg, result);
  537. await getTelemetry().flushNow();
  538. }
  539. // =============================================================================
  540. // Commands
  541. // =============================================================================
  542. /**
  543. * codegraph init [path]
  544. */
  545. program
  546. .command('init [path]')
  547. .description('Initialize CodeGraph in a project directory and build the initial index')
  548. .option('-i, --index', 'Deprecated: indexing now runs by default; flag accepted for backward compatibility')
  549. .option('-f, --force', 'Initialize even if the path looks like your home directory or a filesystem root')
  550. .option('-v, --verbose', 'Show detailed worker lifecycle and memory info')
  551. .action(async (pathArg: string | undefined, options: { index?: boolean; force?: boolean; verbose?: boolean }) => {
  552. const projectPath = path.resolve(pathArg || process.cwd());
  553. const clack = await importESM('@clack/prompts');
  554. clack.intro('Initializing CodeGraph');
  555. try {
  556. // Refuse to index your home directory / a filesystem root — it pulls in
  557. // caches, other projects, and your whole tree (a multi-GB index + watcher
  558. // churn, and on pre-1.0 macOS a machine-crashing fd blowup, #845).
  559. const unsafe = unsafeIndexRootReason(projectPath);
  560. if (unsafe && !options.force) {
  561. clack.log.error(`Refusing to initialize in ${projectPath} — it looks like ${unsafe}.`);
  562. clack.log.info('Run this inside a specific project directory, or pass --force if you really mean to index everything under it.');
  563. clack.outro('');
  564. process.exitCode = 1;
  565. return;
  566. }
  567. if (isInitialized(projectPath)) {
  568. clack.log.warn(`Already initialized in ${projectPath}`);
  569. clack.log.info('Use "codegraph index" to re-index or "codegraph sync" to update');
  570. try {
  571. const { offerWatchFallback } = await import('../installer');
  572. await offerWatchFallback(clack, projectPath);
  573. } catch { /* non-fatal */ }
  574. clack.outro('');
  575. return;
  576. }
  577. const { default: CodeGraph, getDatabasePath } = await loadCodeGraph();
  578. const cg = await CodeGraph.init(projectPath, { index: false });
  579. clack.log.success(`Initialized in ${projectPath}`);
  580. // Indexing runs by default now. The legacy -i/--index flag is still
  581. // accepted (so existing muscle memory and scripts don't break) but is a
  582. // no-op — initializing always builds the initial index.
  583. // Supervise the index: self-terminate if orphaned or wedged (#999).
  584. // The DB + WAL paths let the liveness watchdog tell a slow store on
  585. // degraded storage from a true wedge (#1231).
  586. // A closure so we can re-run the exact same supervised, progress-rendered
  587. // index if the user opts gitignored child repos in below (#1156).
  588. const dbPath = getDatabasePath(projectPath);
  589. const runIndex = async (): Promise<IndexResult> => {
  590. const supervision = installCommandSupervision('init', { progressPaths: [dbPath, `${dbPath}-wal`] });
  591. try {
  592. if (options.verbose) {
  593. return await cg.indexAll({ onProgress: createVerboseProgress(), verbose: true });
  594. }
  595. process.stdout.write(`${colors.dim}${getGlyphs().rail}${colors.reset}\n`);
  596. const progress = createShimmerProgress();
  597. const r = await cg.indexAll({ onProgress: progress.onProgress });
  598. await progress.stop();
  599. return r;
  600. } finally {
  601. supervision.stop();
  602. }
  603. };
  604. const result = await runIndex();
  605. printIndexResult(clack, result, projectPath);
  606. await recordIndexTelemetry(cg, result);
  607. // An empty graph at a git super-repo usually means `.gitignore` excludes
  608. // the child repos that hold the code — surface them and offer to opt in
  609. // rather than leaving the user with a silent 0-node "Done". (#1156)
  610. if (result.nodesCreated === 0) {
  611. await offerIndexIgnoredRepos(clack, projectPath, runIndex, { interactive: true });
  612. }
  613. try {
  614. const { offerWatchFallback } = await import('../installer');
  615. await offerWatchFallback(clack, projectPath);
  616. } catch { /* non-fatal */ }
  617. clack.outro('Done');
  618. cg.destroy();
  619. } catch (err) {
  620. clack.log.error(`Failed: ${err instanceof Error ? err.message : String(err)}`);
  621. process.exit(1);
  622. }
  623. });
  624. /**
  625. * codegraph uninit [path]
  626. */
  627. program
  628. .command('uninit [path]')
  629. .description('Remove CodeGraph from a project (deletes .codegraph/ directory)')
  630. .option('-f, --force', 'Skip confirmation prompt')
  631. .action(async (pathArg: string | undefined, options: { force?: boolean }) => {
  632. const projectPath = resolveProjectPath(pathArg);
  633. try {
  634. if (!isInitialized(projectPath)) {
  635. warn(`CodeGraph is not initialized in ${projectPath}`);
  636. return;
  637. }
  638. if (!options.force) {
  639. // Confirm with user
  640. const readline = await import('readline');
  641. const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  642. const answer = await new Promise<string>((resolve) => {
  643. rl.question(
  644. chalk.yellow(`${getGlyphs().warn} This will permanently delete all CodeGraph data. Continue? (y/N) `),
  645. resolve
  646. );
  647. });
  648. rl.close();
  649. if (answer.toLowerCase() !== 'y') {
  650. info('Cancelled');
  651. return;
  652. }
  653. }
  654. const { default: CodeGraph } = await loadCodeGraph();
  655. const cg = CodeGraph.openSync(projectPath);
  656. cg.uninitialize();
  657. // Clean up any git sync hooks we installed (no-op if none / not a repo).
  658. try {
  659. const { removeGitSyncHook } = await import('../sync/git-hooks');
  660. const removed = removeGitSyncHook(projectPath);
  661. if (removed.installed.length > 0) {
  662. info(`Removed git ${removed.installed.join(', ')} sync hook${removed.installed.length > 1 ? 's' : ''}`);
  663. }
  664. } catch { /* non-fatal */ }
  665. success(`Removed CodeGraph from ${projectPath}`);
  666. // Churn signal — and flush now, since after an uninit there may be no
  667. // "next run" to deliver it.
  668. try {
  669. getTelemetry().recordLifecycle('uninstall', {});
  670. await getTelemetry().flushNow();
  671. } catch { /* non-fatal */ }
  672. } catch (err) {
  673. error(`Failed to uninitialize: ${err instanceof Error ? err.message : String(err)}`);
  674. process.exit(1);
  675. }
  676. });
  677. /**
  678. * codegraph index [path]
  679. */
  680. program
  681. .command('index [path]')
  682. .description('Rebuild the full index from scratch (same result as a fresh init)')
  683. .option('-f, --force', 'Index even if the path looks like your home directory or a filesystem root')
  684. .option('-q, --quiet', 'Suppress progress output')
  685. .option('-v, --verbose', 'Show detailed worker lifecycle and memory info')
  686. .action(async (pathArg: string | undefined, options: { force?: boolean; quiet?: boolean; verbose?: boolean }) => {
  687. const projectPath = resolveProjectPath(pathArg);
  688. try {
  689. // Don't (re)index your home directory / a filesystem root (#845). --force
  690. // doubles as the override.
  691. const unsafe = unsafeIndexRootReason(projectPath);
  692. if (unsafe && !options.force) {
  693. error(`Refusing to index ${projectPath} — it looks like ${unsafe}. Pass --force to override.`);
  694. process.exit(1);
  695. }
  696. if (!isInitialized(projectPath)) {
  697. error(`CodeGraph not initialized in ${projectPath}`);
  698. info('Run "codegraph init" first');
  699. process.exit(1);
  700. }
  701. const { default: CodeGraph, getDatabasePath } = await loadCodeGraph();
  702. // `index` is a FULL re-index — identical to a fresh `init`. RECREATE the
  703. // database from scratch (discard .codegraph/codegraph.db + its WAL) rather
  704. // than opening the old graph and DELETE-ing every row. The clear-then-index
  705. // approach reported "0 nodes" without the clear (#874); the recreate keeps
  706. // that fixed AND avoids the failure mode where, on a large or pre-fix
  707. // poisoned index, the per-row FTS delete churn wedged the main thread long
  708. // enough to trip the liveness watchdog before scanning even began (#1067).
  709. // recreate() hands back a fresh, empty instance — no clear() needed. For
  710. // fast incremental updates use `sync`.
  711. const cg = await CodeGraph.recreate(projectPath);
  712. // Supervise the indexer: self-terminate if orphaned (parent shim killed)
  713. // or if the main thread wedges — neither was guarded on this path (#999).
  714. // The DB + WAL paths let the liveness watchdog tell a slow store on
  715. // degraded storage from a true wedge (#1231).
  716. const dbPath = getDatabasePath(projectPath);
  717. const supervision = installCommandSupervision('index', { progressPaths: [dbPath, `${dbPath}-wal`] });
  718. try {
  719. if (options.quiet) {
  720. // Quiet mode: no UI, just run against the freshly-recreated graph.
  721. const result = await cg.indexAll();
  722. if (!result.success) process.exit(1);
  723. cg.destroy();
  724. return;
  725. }
  726. const clack = await importESM('@clack/prompts');
  727. clack.intro('Indexing project');
  728. // A closure so a re-index (after opting gitignored child repos in, #1156)
  729. // renders identically. Supervision already wraps the whole command.
  730. const renderIndex = async (): Promise<IndexResult> => {
  731. if (options.verbose) {
  732. return await cg.indexAll({ onProgress: createVerboseProgress(), verbose: true });
  733. }
  734. process.stdout.write(`${colors.dim}${getGlyphs().rail}${colors.reset}\n`);
  735. const progress = createShimmerProgress();
  736. const r = await cg.indexAll({ onProgress: progress.onProgress });
  737. await progress.stop();
  738. return r;
  739. };
  740. const result = await renderIndex();
  741. printIndexResult(clack, result, projectPath);
  742. await recordIndexTelemetry(cg, result);
  743. // Empty graph at a git super-repo → likely `.gitignore`d child repos;
  744. // name them and offer to opt in instead of a silent 0-node result (#1156).
  745. let finalResult = result;
  746. if (result.nodesCreated === 0) {
  747. finalResult = (await offerIndexIgnoredRepos(clack, projectPath, renderIndex, { interactive: true })) ?? result;
  748. }
  749. if (!finalResult.success) {
  750. process.exit(1);
  751. }
  752. clack.outro('Done');
  753. cg.destroy();
  754. } finally {
  755. supervision.stop();
  756. }
  757. } catch (err) {
  758. error(`Failed to index: ${err instanceof Error ? err.message : String(err)}`);
  759. process.exit(1);
  760. }
  761. });
  762. /**
  763. * codegraph sync [path]
  764. */
  765. program
  766. .command('sync [path]')
  767. .description('Sync changes since last index')
  768. .option('-q, --quiet', 'Suppress output (for git hooks)')
  769. .action(async (pathArg: string | undefined, options: { quiet?: boolean }) => {
  770. const projectPath = resolveProjectPath(pathArg);
  771. try {
  772. if (!isInitialized(projectPath)) {
  773. if (!options.quiet) {
  774. error(`CodeGraph not initialized in ${projectPath}`);
  775. }
  776. process.exit(1);
  777. }
  778. const { default: CodeGraph } = await loadCodeGraph();
  779. const cg = await CodeGraph.open(projectPath);
  780. if (options.quiet) {
  781. await cg.sync();
  782. cg.destroy();
  783. return;
  784. }
  785. const clack = await importESM('@clack/prompts');
  786. clack.intro('Syncing CodeGraph');
  787. process.stdout.write(`${colors.dim}${getGlyphs().rail}${colors.reset}\n`);
  788. const progress = createShimmerProgress();
  789. const result = await cg.sync({
  790. onProgress: progress.onProgress,
  791. });
  792. await progress.stop();
  793. const totalChanges = result.filesAdded + result.filesModified + result.filesRemoved;
  794. if (totalChanges === 0) {
  795. clack.log.info('Already up to date');
  796. } else {
  797. clack.log.success(`Synced ${formatNumber(totalChanges)} changed files`);
  798. const details: string[] = [];
  799. if (result.filesAdded > 0) details.push(`Added: ${result.filesAdded}`);
  800. if (result.filesModified > 0) details.push(`Modified: ${result.filesModified}`);
  801. if (result.filesRemoved > 0) details.push(`Removed: ${result.filesRemoved}`);
  802. clack.log.info(`${details.join(', ')} ${getGlyphs().dash} ${formatNumber(result.nodesUpdated)} nodes in ${formatDuration(result.durationMs)}`);
  803. }
  804. clack.outro('Done');
  805. cg.destroy();
  806. } catch (err) {
  807. if (!options.quiet) {
  808. error(`Failed to sync: ${err instanceof Error ? err.message : String(err)}`);
  809. }
  810. process.exit(1);
  811. }
  812. });
  813. /**
  814. * codegraph status [path]
  815. */
  816. program
  817. .command('status [path]')
  818. .description('Show index status and statistics')
  819. .option('-j, --json', 'Output as JSON')
  820. .action(async (pathArg: string | undefined, options: { json?: boolean }) => {
  821. const projectPath = resolveProjectPath(pathArg);
  822. // The directory the user actually ran from, before walking up to the index
  823. // root. Used to detect when the resolved index lives in a different git
  824. // working tree (e.g. a nested worktree borrowing the main checkout's index).
  825. const startPath = path.resolve(pathArg || process.cwd());
  826. const worktreeMismatch = detectWorktreeIndexMismatch(startPath, projectPath);
  827. try {
  828. if (!isInitialized(projectPath)) {
  829. if (options.json) {
  830. console.log(JSON.stringify({
  831. initialized: false,
  832. version: packageJson.version,
  833. projectPath,
  834. indexPath: getCodeGraphDir(projectPath),
  835. lastIndexed: null,
  836. }));
  837. return;
  838. }
  839. console.log(chalk.bold('\nCodeGraph Status\n'));
  840. info(`Project: ${projectPath}`);
  841. warn('Not initialized');
  842. info('Run "codegraph init" to initialize');
  843. return;
  844. }
  845. const { default: CodeGraph } = await loadCodeGraph();
  846. const cg = await CodeGraph.open(projectPath);
  847. const stats = cg.getStats();
  848. const changes = cg.getChangedFiles();
  849. const backend = cg.getBackend();
  850. const journalMode = cg.getJournalMode();
  851. const buildInfo = cg.getIndexBuildInfo();
  852. const reindexRecommended = cg.isIndexStale();
  853. const indexState = cg.getIndexState();
  854. // Zero on a healthy index; non-zero at rest means a resolution pass was
  855. // interrupted, so some files' call edges are missing (#1187).
  856. const pendingRefs = cg.getPendingReferenceCount();
  857. // JSON output mode
  858. if (options.json) {
  859. const lastIndexedMs = cg.getLastIndexedAt();
  860. console.log(JSON.stringify({
  861. initialized: true,
  862. version: packageJson.version,
  863. projectPath,
  864. indexPath: getCodeGraphDir(projectPath),
  865. lastIndexed: lastIndexedMs != null ? new Date(lastIndexedMs).toISOString() : null,
  866. fileCount: stats.fileCount,
  867. nodeCount: stats.nodeCount,
  868. edgeCount: stats.edgeCount,
  869. dbSizeBytes: stats.dbSizeBytes,
  870. walSizeBytes: stats.walSizeBytes,
  871. backend,
  872. journalMode,
  873. nodesByKind: stats.nodesByKind,
  874. languages: Object.entries(stats.filesByLanguage).filter(([, count]) => count > 0).map(([lang]) => lang),
  875. pendingChanges: {
  876. added: changes.added.length,
  877. modified: changes.modified.length,
  878. removed: changes.removed.length,
  879. },
  880. worktreeMismatch: worktreeMismatch
  881. ? { worktreeRoot: worktreeMismatch.worktreeRoot, indexRoot: worktreeMismatch.indexRoot }
  882. : null,
  883. index: {
  884. builtWithVersion: buildInfo.version,
  885. builtWithExtractionVersion: buildInfo.extractionVersion,
  886. currentExtractionVersion: EXTRACTION_VERSION,
  887. reindexRecommended,
  888. // 'complete' | 'partial' (files silently dropped) | 'indexing'
  889. // (a run was killed mid-index — the index is truncated) |
  890. // 'failed' | null (predates the marker).
  891. state: indexState,
  892. // References awaiting resolution. Non-zero at rest means an
  893. // interrupted resolution pass left edges missing; the next
  894. // sync sweeps them (#1187).
  895. pendingRefs,
  896. },
  897. }));
  898. cg.destroy();
  899. return;
  900. }
  901. console.log(chalk.bold('\nCodeGraph Status\n'));
  902. // Project info
  903. console.log(chalk.cyan('Project:'), projectPath);
  904. if (worktreeMismatch) {
  905. warn(worktreeMismatchWarning(worktreeMismatch));
  906. }
  907. if (indexState === 'indexing') {
  908. warn('The last index run never finished (killed mid-index?) — the index is truncated. Re-run "codegraph index".');
  909. } else if (indexState === 'partial') {
  910. warn('The last index run silently dropped files — the index is partial. Re-run "codegraph index".');
  911. } else if (indexState === 'failed') {
  912. warn('The last index run failed — results may be incomplete. Re-run "codegraph index".');
  913. }
  914. if (pendingRefs > 0) {
  915. warn(`${formatNumber(pendingRefs)} references from an interrupted run are awaiting resolution — some callers/impact edges are missing. Run "codegraph sync" to resolve them.`);
  916. }
  917. console.log();
  918. // Index stats
  919. console.log(chalk.bold('Index Statistics:'));
  920. console.log(` Files: ${formatNumber(stats.fileCount)}`);
  921. console.log(` Nodes: ${formatNumber(stats.nodeCount)}`);
  922. console.log(` Edges: ${formatNumber(stats.edgeCount)}`);
  923. console.log(` DB Size: ${(stats.dbSizeBytes / 1024 / 1024).toFixed(2)} MB`);
  924. // Surface the WAL sidecar (#1431): a WAL that dwarfs the DB at rest is
  925. // the killed-session leak — invisible before this line, it only showed
  926. // up as a mysteriously full disk. open() above already kicked off the
  927. // automatic heal for the oversized case.
  928. if (stats.walSizeBytes > 0) {
  929. const { WAL_HEAL_THRESHOLD_BYTES } = await import('../db/index');
  930. const oversized = stats.walSizeBytes > Math.max(WAL_HEAL_THRESHOLD_BYTES, stats.dbSizeBytes);
  931. const walLabel = `${(stats.walSizeBytes / 1024 / 1024).toFixed(2)} MB`;
  932. console.log(` WAL Size: ${oversized ? chalk.yellow(walLabel) : walLabel}`);
  933. if (oversized) {
  934. warn('The write-ahead log is larger than the database — killed sessions left it behind. It is reclaimed automatically on open; if it persists across runs, another live CodeGraph process is holding it.');
  935. }
  936. }
  937. // Surface the active SQLite backend (node:sqlite — Node's built-in real
  938. // SQLite, full WAL + FTS5, no native build).
  939. const backendLabel = chalk.green(`node:sqlite ${getGlyphs().dash} built-in (full WAL)`);
  940. console.log(` Backend: ${backendLabel}`);
  941. // Effective journal mode: 'wal' means concurrent reads never block on a
  942. // writer; anything else means they can ("database is locked"). node:sqlite
  943. // supports WAL everywhere, so a non-wal mode means the filesystem can't
  944. // (network mounts, WSL2 /mnt). See issue #238.
  945. const journalLabel = journalMode === 'wal'
  946. ? chalk.green('wal')
  947. : chalk.yellow(`${journalMode || 'unknown'} ${getGlyphs().dash} WAL inactive; reads can block on writes`);
  948. console.log(` Journal: ${journalLabel}`);
  949. console.log();
  950. // Node breakdown
  951. console.log(chalk.bold('Nodes by Kind:'));
  952. const nodesByKind = Object.entries(stats.nodesByKind)
  953. .filter(([, count]) => count > 0)
  954. .sort((a, b) => b[1] - a[1]);
  955. for (const [kind, count] of nodesByKind) {
  956. console.log(` ${kind.padEnd(15)} ${formatNumber(count)}`);
  957. }
  958. console.log();
  959. // Language breakdown
  960. console.log(chalk.bold('Files by Language:'));
  961. const filesByLang = Object.entries(stats.filesByLanguage)
  962. .filter(([, count]) => count > 0)
  963. .sort((a, b) => b[1] - a[1]);
  964. for (const [lang, count] of filesByLang) {
  965. console.log(` ${lang.padEnd(15)} ${formatNumber(count)}`);
  966. }
  967. console.log();
  968. // Pending changes
  969. const totalChanges = changes.added.length + changes.modified.length + changes.removed.length;
  970. if (totalChanges > 0) {
  971. console.log(chalk.bold('Pending Changes:'));
  972. if (changes.added.length > 0) {
  973. console.log(` Added: ${changes.added.length} files`);
  974. }
  975. if (changes.modified.length > 0) {
  976. console.log(` Modified: ${changes.modified.length} files`);
  977. }
  978. if (changes.removed.length > 0) {
  979. console.log(` Removed: ${changes.removed.length} files`);
  980. }
  981. info('Run "codegraph sync" to update the index');
  982. } else {
  983. success('Index is up to date');
  984. }
  985. console.log();
  986. // Re-index hint: the index was built by an older engine than the one now
  987. // running, so a rebuild would add data a migration can't backfill.
  988. if (reindexRecommended) {
  989. const builtWith = buildInfo.version ? `v${buildInfo.version.replace(/^v/, '')}` : 'an earlier version';
  990. warn(`Index was built by ${builtWith}; re-index to pick up this engine's improvements.`);
  991. info('Run "codegraph index" (full rebuild) or "codegraph sync"');
  992. console.log();
  993. }
  994. cg.destroy();
  995. } catch (err) {
  996. error(`Failed to get status: ${err instanceof Error ? err.message : String(err)}`);
  997. process.exit(1);
  998. }
  999. });
  1000. /**
  1001. * codegraph query <search>
  1002. */
  1003. program
  1004. .command('query <search>')
  1005. .description('Search for symbols in the codebase')
  1006. .option('-p, --path <path>', 'Project path')
  1007. .option('-l, --limit <number>', 'Maximum results', '10')
  1008. .option('-k, --kind <kind>', 'Filter by node kind (function, class, etc.)')
  1009. .option('-j, --json', 'Output as JSON')
  1010. .action(async (search: string, options: { path?: string; limit?: string; kind?: string; json?: boolean }) => {
  1011. const projectPath = resolveProjectPath(options.path);
  1012. try {
  1013. if (!isInitialized(projectPath)) {
  1014. error(`CodeGraph not initialized in ${projectPath}`);
  1015. process.exit(1);
  1016. }
  1017. const { default: CodeGraph } = await loadCodeGraph();
  1018. const cg = await CodeGraph.open(projectPath);
  1019. const limit = parseInt(options.limit || '10', 10);
  1020. const rawResults = cg.searchNodes(search, {
  1021. limit,
  1022. kinds: options.kind ? [options.kind as any] : undefined,
  1023. });
  1024. // Mirror the MCP search down-rank so the CLI also surfaces the
  1025. // hand-written implementation before protobuf/gRPC scaffolding
  1026. // when both share a name. See extraction/generated-detection.ts.
  1027. const isGen = cg.generatedFilePredicate(rawResults.map((r) => r.node.filePath));
  1028. const results = [...rawResults].sort((a, b) => {
  1029. const aGen = isGen(a.node.filePath) ? 1 : 0;
  1030. const bGen = isGen(b.node.filePath) ? 1 : 0;
  1031. return aGen - bGen;
  1032. });
  1033. if (options.json) {
  1034. console.log(JSON.stringify(results, null, 2));
  1035. } else {
  1036. if (results.length === 0) {
  1037. info(`No results found for "${search}"`);
  1038. } else {
  1039. console.log(chalk.bold(`\nSearch Results for "${search}":\n`));
  1040. // Results arrive already ranked by relevance, so the order conveys
  1041. // it. We don't print the raw score: it's an unbounded BM25/FTS value
  1042. // (relative-ranking only), and the old `(score * 100)%` rendered it
  1043. // as nonsensical percentages like "12042%" (#1045). The MCP search
  1044. // tool likewise shows no score. Raw `score` stays in --json output.
  1045. for (const result of results) {
  1046. const node = result.node;
  1047. const location = `${node.filePath}:${node.startLine}`;
  1048. console.log(
  1049. chalk.cyan(node.kind.padEnd(12)) +
  1050. chalk.white(node.name)
  1051. );
  1052. console.log(chalk.dim(` ${location}`));
  1053. if (node.signature) {
  1054. console.log(chalk.dim(` ${node.signature}`));
  1055. }
  1056. console.log();
  1057. }
  1058. }
  1059. }
  1060. cg.destroy();
  1061. } catch (err) {
  1062. error(`Search failed: ${err instanceof Error ? err.message : String(err)}`);
  1063. process.exit(1);
  1064. }
  1065. });
  1066. /**
  1067. * codegraph explore <query...>
  1068. *
  1069. * The CLI face of the MCP codegraph_explore tool — same handler, same
  1070. * output (source of the relevant symbols grouped by file + the call path
  1071. * among them). Exists so agents WITHOUT the MCP tools — Task-tool
  1072. * subagents (which don't inherit MCP tools, #704) and non-MCP harnesses —
  1073. * can reach the graph through a plain shell command.
  1074. */
  1075. program
  1076. .command('explore <query...>')
  1077. .description('Explore an area: relevant symbols\' source + call paths in one shot (same output as the codegraph_explore MCP tool)')
  1078. .option('-p, --path <path>', 'Project path')
  1079. .option('--max-files <number>', 'Maximum number of files to include source from')
  1080. .action(async (queryParts: string[], options: { path?: string; maxFiles?: string }) => {
  1081. const projectPath = resolveProjectPath(options.path);
  1082. try {
  1083. if (!isInitialized(projectPath)) {
  1084. error(`CodeGraph isn't available here — no .codegraph/ index exists in ${projectPath}. If you are an AI agent: continue with your usual tools; indexing is the user's decision, do not run it yourself. (The project owner can enable CodeGraph with 'codegraph init'.)`);
  1085. process.exit(1);
  1086. }
  1087. const { default: CodeGraph } = await loadCodeGraph();
  1088. const cg = await CodeGraph.open(projectPath);
  1089. const { ToolHandler } = await import('../mcp/tools');
  1090. const handler = new ToolHandler(cg);
  1091. const args: Record<string, unknown> = { query: queryParts.join(' ') };
  1092. if (options.maxFiles) args.maxFiles = parseInt(options.maxFiles, 10);
  1093. const result = await handler.execute('codegraph_explore', args);
  1094. console.log(result.content[0]?.text ?? '');
  1095. cg.destroy();
  1096. if (result.isError) process.exit(1);
  1097. } catch (err) {
  1098. error(`Explore failed: ${err instanceof Error ? err.message : String(err)}`);
  1099. process.exit(1);
  1100. }
  1101. });
  1102. /**
  1103. * codegraph prompt-hook (hidden)
  1104. *
  1105. * A Claude Code `UserPromptSubmit` hook entry point. Reads `{prompt, cwd}` JSON
  1106. * on stdin; for a structural/flow/impact prompt it runs `codegraph_explore` on
  1107. * the indexed project and prints the result to stdout, which Claude injects into
  1108. * the agent's context — so the agent's reflex grep/read has nothing left to find
  1109. * and reliably uses CodeGraph (the adoption problem). Installed by the installer
  1110. * into Claude's settings.json (opt-in, default-yes).
  1111. *
  1112. * LOAD-BEARING: this must NEVER break the user's prompt. Every failure path —
  1113. * kill-switch, non-structural prompt, no index, engine error — exits 0 with no
  1114. * output. The only effect is additive context when it can confidently provide it.
  1115. */
  1116. program
  1117. .command('prompt-hook', { hidden: true })
  1118. .description('Claude UserPromptSubmit hook: inject CodeGraph context for structural prompts (reads {prompt,cwd} JSON on stdin)')
  1119. .action(async () => {
  1120. try {
  1121. // Kill-switch: lets a user disable the nudge without uninstalling /
  1122. // editing settings.json (CI, low-power machines, personal preference).
  1123. if (process.env.CODEGRAPH_NO_PROMPT_HOOK === '1' || process.env.CODEGRAPH_PROMPT_HOOK === '0') return;
  1124. if (process.stdin.isTTY) return; // invoked by hand, no piped payload
  1125. const raw = await new Promise<string>((resolve) => {
  1126. let data = '';
  1127. process.stdin.setEncoding('utf8');
  1128. process.stdin.on('data', (c) => { data += c; });
  1129. process.stdin.on('end', () => resolve(data));
  1130. process.stdin.on('error', () => resolve(data));
  1131. });
  1132. let input: { prompt?: string; cwd?: string } = {};
  1133. try { input = JSON.parse(raw); } catch { return; }
  1134. const prompt = String(input.prompt || '');
  1135. // Gate telemetry: how often each tier fires vs. no-ops — counter names
  1136. // only, NEVER prompt content (see TELEMETRY.md). This is the data that
  1137. // turns "is the gate any good" from vibes into a measured recall rate.
  1138. const gate = (outcome: string): void => {
  1139. try { getTelemetry().recordUsage('cli_command', `prompt-hook-gate-${outcome}`, true); } catch { /* never break the hook */ }
  1140. };
  1141. // Gate, tiered by confidence (#994, #1126):
  1142. // HIGH — a structural keyword (any covered language), or a code-shaped
  1143. // token verified in the index → full explore injection.
  1144. // MEDIUM — no keyword/token, but prose words match indexed symbol-name
  1145. // SEGMENTS ("state machine" → OrderStateMachine, in any
  1146. // language): inject a short list of the matching symbols and
  1147. // let the AGENT write the explore query — the graph-derived
  1148. // tier, no vocabulary involved.
  1149. // silent — nothing verified. Every other prompt ("fix this typo")
  1150. // stays a zero-cost no-op.
  1151. // Keywords fire on their own; a token or prose word is only a CANDIDATE
  1152. // verified against the graph below, so a tech brand ("JavaScript") that
  1153. // merely looks like code doesn't inject spurious context.
  1154. const keyworded = hasStructuralKeyword(prompt);
  1155. const codeTokens = keyworded ? [] : extractCodeTokens(prompt);
  1156. const proseWords = keyworded ? [] : extractProseCandidates(prompt);
  1157. if (!keyworded && codeTokens.length === 0 && proseWords.length === 0) { gate('noop-shape'); return; }
  1158. // Decide what to inject, shaped by WHERE the index(es) are: the nearest
  1159. // indexed ancestor of cwd, or — when cwd is an un-indexed workspace root
  1160. // whose indexed project(s) live in sub-dirs (the monorepo case, #964) —
  1161. // the sub-project the prompt points at, plus a `projectPath` nudge for any
  1162. // others. Without the down-scan the hook injected nothing at a monorepo
  1163. // root (it only walked up), so the validated adoption lever never fired
  1164. // exactly where the agent most needs it.
  1165. const plan = planFrontload(String(input.cwd || process.cwd()), prompt);
  1166. if (!plan.exploreRoot && plan.nudgeProjects.length === 0) { gate('noop-no-index'); return; } // nothing reachable — the agent's normal tools apply
  1167. // A "pass projectPath" line for indexed sub-projects we did NOT front-load.
  1168. // Follow-up codegraph_explore calls against a sub-project (cwd isn't its
  1169. // index root) need an explicit projectPath, so spell it out.
  1170. const nudge = (projects: string[], lead: string): string =>
  1171. `${lead}\n${projects.map((p) => ` - projectPath: "${p}"`).join('\n')}\n`;
  1172. if (plan.exploreRoot) {
  1173. const { default: CodeGraph } = await loadCodeGraph();
  1174. const cg = await CodeGraph.open(plan.exploreRoot);
  1175. try {
  1176. const others = plan.nudgeProjects.length
  1177. ? `\n${nudge(plan.nudgeProjects, 'Other indexed projects in this workspace — pass projectPath to query them:')}`
  1178. : '';
  1179. // Tier decision against THIS index (issue #994 follow-up: candidates
  1180. // must be real here — a brand name or prose about another domain
  1181. // must not inject). Keyword-bearing prompts skip verification — the
  1182. // keyword is signal enough.
  1183. const tokenVerified = !keyworded && codeTokens.some((t) => cg.getNodesByName(t).length > 0);
  1184. if (keyworded || tokenVerified) {
  1185. const { ToolHandler } = await import('../mcp/tools');
  1186. const handler = new ToolHandler(cg);
  1187. const result = await handler.execute('codegraph_explore', { query: prompt });
  1188. const text = result.content[0]?.text ?? '';
  1189. if (!result.isError && text.trim()) {
  1190. // Cap the injection so a large-repo explore can't flood the prompt.
  1191. const MAX = 16000;
  1192. const body = text.length > MAX ? `${text.slice(0, MAX)}\n…(truncated; call codegraph_explore for the rest)` : text;
  1193. // For a front-loaded SUB-project, a follow-up explore needs its path.
  1194. const more = plan.viaSubScan
  1195. ? `call codegraph_explore with projectPath: "${plan.exploreRoot}" for more`
  1196. : 'call codegraph_explore for more';
  1197. process.stdout.write(
  1198. `<codegraph_context note="Structural context from CodeGraph for this prompt — treat returned source as already read; ${more}.">\n${body}${others}\n</codegraph_context>\n`,
  1199. );
  1200. gate(keyworded ? 'high-keyword' : 'high-token');
  1201. } else {
  1202. // A high-* outcome must mean context was actually delivered —
  1203. // the funnel's noop-vs-high split is how gate recall is
  1204. // measured (#1143). An explore error or empty result is a
  1205. // delivery failure, not a gate success.
  1206. gate(keyworded ? 'noop-explore-keyword' : 'noop-explore-token');
  1207. }
  1208. return;
  1209. }
  1210. // MEDIUM: prose words → symbol-name segments, co-occurrence/rarity
  1211. // scored, each hit re-verified to exist (see getSegmentMatches). The
  1212. // payload names the symbols but does NOT run explore — the agent owns
  1213. // the query where the hook's confidence is only "these are related".
  1214. //
  1215. // A database indexed before the vocab table existed starts with it
  1216. // EMPTY, and only sync() backfills it — which this hook never runs
  1217. // (#1142). Heal it here: on a populated vocab this is one SELECT;
  1218. // the actual backfill is a one-time batched pass whose cost the MCP
  1219. // server's own catch-up sync usually pays first (it runs at every
  1220. // session start). A distinct noop outcome keeps a dormant vocab
  1221. // from polluting the noop-unverified recall signal.
  1222. const vocabReady = await cg.healSegmentVocabIfEmpty().catch(() => false);
  1223. if (!vocabReady) { gate('noop-vocab-empty'); return; }
  1224. const related = cg.getSegmentMatches(proseWords);
  1225. if (related.length === 0) { gate('noop-unverified'); return; }
  1226. const lines = related
  1227. .map((m) => ` - ${m.name} (${m.kind} — ${m.filePath}:${m.startLine})`)
  1228. .join('\n');
  1229. const exampleQuery = related.slice(0, 3).map((m) => m.name).join(' ');
  1230. const projectHint = plan.viaSubScan ? ` with projectPath: "${plan.exploreRoot}"` : '';
  1231. process.stdout.write(
  1232. `<codegraph_context note="CodeGraph found indexed symbols matching this prompt — query the graph before searching files.">\n` +
  1233. `This project's CodeGraph index contains symbols matching this request:\n${lines}\n` +
  1234. `Call codegraph_explore ONCE${projectHint} with the relevant names in one query (e.g. "${exampleQuery}") ` +
  1235. `to get their source, call paths, and blast radius — cheaper and more complete than Read/Grep.\n${others}` +
  1236. `</codegraph_context>\n`,
  1237. );
  1238. gate('medium-segment');
  1239. } finally {
  1240. cg.destroy();
  1241. }
  1242. } else {
  1243. // Several indexed sub-projects, none a clear match — don't guess; tell
  1244. // the agent they exist and how to query one.
  1245. process.stdout.write(
  1246. `<codegraph_context note="CodeGraph is available for this workspace's indexed sub-projects — query one by passing projectPath to codegraph_explore.">\n` +
  1247. nudge(plan.nudgeProjects, "This workspace's CodeGraph indexes live in sub-projects. To use CodeGraph, call codegraph_explore with the projectPath of the relevant one:") +
  1248. `</codegraph_context>\n`,
  1249. );
  1250. gate('nudge-projects');
  1251. }
  1252. } catch {
  1253. // Degradable by contract: never surface an error to the prompt pipeline.
  1254. }
  1255. });
  1256. /**
  1257. * codegraph node [name]
  1258. *
  1259. * The CLI face of the MCP codegraph_node tool: one symbol's source +
  1260. * caller/callee trail, or a whole file with line numbers + dependents
  1261. * (Read-parity). Same subagent/non-MCP rationale as `explore`.
  1262. *
  1263. * `name` is OPTIONAL because `--file` (file-read mode) carries no symbol —
  1264. * a required `<name>` made `codegraph node -f <file>` unreachable (#1044).
  1265. */
  1266. program
  1267. .command('node [name]')
  1268. .description('One symbol\'s source + caller/callee trail, or read a file with line numbers + dependents (same output as the codegraph_node MCP tool)')
  1269. .option('-p, --path <path>', 'Project path')
  1270. .option('-f, --file <file>', 'Treat as file mode (or disambiguate a symbol to this file)')
  1271. .option('--offset <number>', 'File mode: 1-based start line')
  1272. .option('--limit <number>', 'File mode: maximum lines')
  1273. .option('--symbols-only', 'File mode: just the symbol map + dependents')
  1274. .action(async (name: string | undefined, options: { path?: string; file?: string; offset?: string; limit?: string; symbolsOnly?: boolean }) => {
  1275. // Need a symbol (positional) OR a file (--file / a path-like positional).
  1276. // With [name] optional, a bare `codegraph node` reaches here with neither
  1277. // and must be told what to pass, rather than crashing downstream.
  1278. if (!name && !options.file) {
  1279. error("Pass a symbol name (e.g. 'codegraph node parseToken') or a file (e.g. 'codegraph node -f src/auth.ts', or 'codegraph node src/auth.ts').");
  1280. process.exit(1);
  1281. }
  1282. const projectPath = resolveProjectPath(options.path);
  1283. try {
  1284. if (!isInitialized(projectPath)) {
  1285. error(`CodeGraph isn't available here — no .codegraph/ index exists in ${projectPath}. If you are an AI agent: continue with your usual tools; indexing is the user's decision, do not run it yourself. (The project owner can enable CodeGraph with 'codegraph init'.)`);
  1286. process.exit(1);
  1287. }
  1288. const { default: CodeGraph } = await loadCodeGraph();
  1289. const cg = await CodeGraph.open(projectPath);
  1290. const { ToolHandler } = await import('../mcp/tools');
  1291. const handler = new ToolHandler(cg);
  1292. // A name with a path separator is a file read; otherwise a symbol
  1293. // (use --file for basename-only file reads or to pin an overload).
  1294. // Both separators: Windows users type src\auth\session.ts. Symbols
  1295. // never contain either ('/' isn't an identifier char anywhere we
  1296. // index; C++ scope is '::', JS members '.').
  1297. const args: Record<string, unknown> = {};
  1298. if (options.file) {
  1299. args.file = options.file;
  1300. if (name && name !== options.file) {
  1301. args.symbol = name;
  1302. // Symbol mode pinned to a file is still symbol mode — the CLI
  1303. // always wants the body, exactly like the bare-symbol branch
  1304. // below. Omitting this printed location + trail with no source
  1305. // (#1284).
  1306. args.includeCode = true;
  1307. }
  1308. } else if (name && (name.includes('/') || name.includes('\\'))) {
  1309. args.file = name.replace(/\\/g, '/');
  1310. } else if (name) {
  1311. args.symbol = name;
  1312. args.includeCode = true;
  1313. }
  1314. if (options.offset) args.offset = parseInt(options.offset, 10);
  1315. if (options.limit) args.limit = parseInt(options.limit, 10);
  1316. if (options.symbolsOnly) args.symbolsOnly = true;
  1317. const result = await handler.execute('codegraph_node', args);
  1318. console.log(result.content[0]?.text ?? '');
  1319. cg.destroy();
  1320. if (result.isError) process.exit(1);
  1321. } catch (err) {
  1322. error(`Node lookup failed: ${err instanceof Error ? err.message : String(err)}`);
  1323. process.exit(1);
  1324. }
  1325. });
  1326. /**
  1327. * codegraph files [path]
  1328. */
  1329. program
  1330. .command('files')
  1331. .description('Show project file structure from the index')
  1332. .option('-p, --path <path>', 'Project path')
  1333. .option('--filter <dir>', 'Filter to files under this directory')
  1334. .option('--pattern <glob>', 'Filter files matching this glob pattern')
  1335. .option('--format <format>', 'Output format (tree, flat, grouped)', 'tree')
  1336. .option('--max-depth <number>', 'Maximum directory depth for tree format')
  1337. .option('--no-metadata', 'Hide file metadata (language, symbol count)')
  1338. .option('-j, --json', 'Output as JSON')
  1339. .action(async (options: {
  1340. path?: string;
  1341. filter?: string;
  1342. pattern?: string;
  1343. format?: string;
  1344. maxDepth?: string;
  1345. metadata?: boolean;
  1346. json?: boolean;
  1347. }) => {
  1348. const projectPath = resolveProjectPath(options.path);
  1349. try {
  1350. if (!isInitialized(projectPath)) {
  1351. error(`CodeGraph not initialized in ${projectPath}`);
  1352. process.exit(1);
  1353. }
  1354. const { default: CodeGraph } = await loadCodeGraph();
  1355. const cg = await CodeGraph.open(projectPath);
  1356. let files = cg.getFiles();
  1357. if (files.length === 0) {
  1358. info('No files indexed. Run "codegraph index" first.');
  1359. cg.destroy();
  1360. return;
  1361. }
  1362. // Filter by path prefix
  1363. if (options.filter) {
  1364. const filter = options.filter;
  1365. files = files.filter(f => f.path.startsWith(filter) || f.path.startsWith('./' + filter));
  1366. }
  1367. // Filter by glob pattern
  1368. if (options.pattern) {
  1369. const regex = globToRegex(options.pattern);
  1370. files = files.filter(f => regex.test(f.path));
  1371. }
  1372. if (files.length === 0) {
  1373. info('No files found matching the criteria.');
  1374. cg.destroy();
  1375. return;
  1376. }
  1377. // JSON output
  1378. if (options.json) {
  1379. const output = files.map(f => ({
  1380. path: f.path,
  1381. language: f.language,
  1382. nodeCount: f.nodeCount,
  1383. size: f.size,
  1384. }));
  1385. console.log(JSON.stringify(output, null, 2));
  1386. cg.destroy();
  1387. return;
  1388. }
  1389. const includeMetadata = options.metadata !== false;
  1390. const format = options.format || 'tree';
  1391. const maxDepth = options.maxDepth ? parseInt(options.maxDepth, 10) : undefined;
  1392. // Format output
  1393. switch (format) {
  1394. case 'flat':
  1395. console.log(chalk.bold(`\nFiles (${files.length}):\n`));
  1396. for (const file of files.sort((a, b) => a.path.localeCompare(b.path))) {
  1397. if (includeMetadata) {
  1398. console.log(` ${file.path} ${chalk.dim(`(${file.language}, ${file.nodeCount} symbols)`)}`);
  1399. } else {
  1400. console.log(` ${file.path}`);
  1401. }
  1402. }
  1403. break;
  1404. case 'grouped':
  1405. console.log(chalk.bold(`\nFiles by Language (${files.length} total):\n`));
  1406. const byLang = new Map<string, typeof files>();
  1407. for (const file of files) {
  1408. const existing = byLang.get(file.language) || [];
  1409. existing.push(file);
  1410. byLang.set(file.language, existing);
  1411. }
  1412. const sortedLangs = [...byLang.entries()].sort((a, b) => b[1].length - a[1].length);
  1413. for (const [lang, langFiles] of sortedLangs) {
  1414. console.log(chalk.cyan(`${lang} (${langFiles.length}):`));
  1415. for (const file of langFiles.sort((a, b) => a.path.localeCompare(b.path))) {
  1416. if (includeMetadata) {
  1417. console.log(` ${file.path} ${chalk.dim(`(${file.nodeCount} symbols)`)}`);
  1418. } else {
  1419. console.log(` ${file.path}`);
  1420. }
  1421. }
  1422. console.log();
  1423. }
  1424. break;
  1425. case 'tree':
  1426. default:
  1427. console.log(chalk.bold(`\nProject Structure (${files.length} files):\n`));
  1428. printFileTree(files, includeMetadata, maxDepth, chalk);
  1429. break;
  1430. }
  1431. console.log();
  1432. cg.destroy();
  1433. } catch (err) {
  1434. error(`Failed to list files: ${err instanceof Error ? err.message : String(err)}`);
  1435. process.exit(1);
  1436. }
  1437. });
  1438. /**
  1439. * Normalize a user-supplied file path to the project-relative, forward-slash
  1440. * form CodeGraph stores in the index. Accepts an absolute path, a `./`-prefixed
  1441. * path, or Windows back-slashes; an empty string when the input is blank. Used
  1442. * by `codegraph affected` so `./src/x.ts`, `/abs/repo/src/x.ts`, and
  1443. * `src/x.ts` all match the same indexed file. (#825)
  1444. */
  1445. function normalizeIndexPath(filePath: string, projectPath: string): string {
  1446. let f = filePath.trim();
  1447. if (!f) return '';
  1448. if (path.isAbsolute(f)) f = path.relative(projectPath, f);
  1449. // Collapse `.`/`..` segments, then force forward slashes and drop a leading
  1450. // `./` (path.normalize already strips it on POSIX; explicit for Windows).
  1451. f = path.normalize(f).replace(/\\/g, '/').replace(/^\.\//, '');
  1452. return f;
  1453. }
  1454. /**
  1455. * Convert glob pattern to regex
  1456. */
  1457. function globToRegex(pattern: string): RegExp {
  1458. const escaped = pattern
  1459. .replace(/[.+^${}()|[\]\\]/g, '\\$&')
  1460. .replace(/\*\*/g, '{{GLOBSTAR}}')
  1461. .replace(/\*/g, '[^/]*')
  1462. .replace(/\?/g, '[^/]')
  1463. .replace(/\{\{GLOBSTAR\}\}/g, '.*');
  1464. return new RegExp(escaped);
  1465. }
  1466. /**
  1467. * Print files as a tree
  1468. */
  1469. function printFileTree(
  1470. files: { path: string; language: string; nodeCount: number }[],
  1471. includeMetadata: boolean,
  1472. maxDepth: number | undefined,
  1473. chalk: { dim: (s: string) => string; cyan: (s: string) => string }
  1474. ): void {
  1475. interface TreeNode {
  1476. name: string;
  1477. children: Map<string, TreeNode>;
  1478. file?: { language: string; nodeCount: number };
  1479. }
  1480. const root: TreeNode = { name: '', children: new Map() };
  1481. for (const file of files) {
  1482. const parts = file.path.split('/');
  1483. let current = root;
  1484. for (let i = 0; i < parts.length; i++) {
  1485. const part = parts[i];
  1486. if (!part) continue;
  1487. if (!current.children.has(part)) {
  1488. current.children.set(part, { name: part, children: new Map() });
  1489. }
  1490. current = current.children.get(part)!;
  1491. if (i === parts.length - 1) {
  1492. current.file = { language: file.language, nodeCount: file.nodeCount };
  1493. }
  1494. }
  1495. }
  1496. const renderNode = (node: TreeNode, prefix: string, isLast: boolean, depth: number): void => {
  1497. if (maxDepth !== undefined && depth > maxDepth) return;
  1498. const glyphs = getGlyphs();
  1499. const connector = isLast ? glyphs.treeLast : glyphs.treeBranch;
  1500. const childPrefix = isLast ? ' ' : glyphs.treePipe;
  1501. if (node.name) {
  1502. let line = prefix + connector + node.name;
  1503. if (node.file && includeMetadata) {
  1504. line += chalk.dim(` (${node.file.language}, ${node.file.nodeCount} symbols)`);
  1505. }
  1506. console.log(line);
  1507. }
  1508. const children = [...node.children.values()];
  1509. children.sort((a, b) => {
  1510. const aIsDir = a.children.size > 0 && !a.file;
  1511. const bIsDir = b.children.size > 0 && !b.file;
  1512. if (aIsDir !== bIsDir) return aIsDir ? -1 : 1;
  1513. return a.name.localeCompare(b.name);
  1514. });
  1515. for (let i = 0; i < children.length; i++) {
  1516. const child = children[i]!;
  1517. const nextPrefix = node.name ? prefix + childPrefix : prefix;
  1518. renderNode(child, nextPrefix, i === children.length - 1, depth + 1);
  1519. }
  1520. };
  1521. renderNode(root, '', true, 0);
  1522. }
  1523. /**
  1524. * codegraph daemon — interactive manager for the background daemons. Arrow keys
  1525. * to pick one (the current project's daemon floats to the top, auto-selected),
  1526. * enter to stop it. Falls back to a plain list when output isn't a TTY.
  1527. */
  1528. program
  1529. .command('daemon')
  1530. .aliases(['daemons'])
  1531. .description('Manage running CodeGraph background daemons — pick one and press enter to stop it')
  1532. .action(async () => {
  1533. const { listVerifiedDaemons, stopDaemonAt, stopAllDaemons } = await import('../mcp/daemon-registry');
  1534. const { runDaemonPicker } = await import('../mcp/daemon-manager');
  1535. const daemons = await listVerifiedDaemons();
  1536. if (daemons.length === 0) {
  1537. info('No CodeGraph daemons running.');
  1538. return;
  1539. }
  1540. // No TTY (piped / CI / non-interactive) — can't do arrow-key selection, so
  1541. // just print what's running instead of crashing on a prompt with no input.
  1542. if (!process.stdout.isTTY || !process.stdin.isTTY) {
  1543. for (const d of daemons) {
  1544. console.log(`pid ${d.pid} v${d.version} up ${formatDuration(Date.now() - d.startedAt)} ${d.root}`);
  1545. }
  1546. return;
  1547. }
  1548. // The current project's daemon floats to the top and is pre-selected.
  1549. let cwdRoot: string | null = null;
  1550. const found = findNearestCodeGraphRoot(process.cwd());
  1551. if (found) { try { cwdRoot = fs.realpathSync(found); } catch { cwdRoot = found; } }
  1552. const clack = await importESM('@clack/prompts');
  1553. clack.intro('CodeGraph daemons');
  1554. await runDaemonPicker({
  1555. list: listVerifiedDaemons,
  1556. stop: stopDaemonAt,
  1557. stopAll: stopAllDaemons,
  1558. cwdRoot,
  1559. now: () => Date.now(),
  1560. select: (opts) => clack.select(opts),
  1561. isCancel: (v) => clack.isCancel(v),
  1562. note: (m) => clack.log.success(m),
  1563. done: (m) => clack.outro(m),
  1564. });
  1565. });
  1566. /**
  1567. * codegraph serve
  1568. */
  1569. program
  1570. // Hidden from `--help`: this is the stdio entry point an AI agent launches
  1571. // for itself (the installer wires `args: ['serve','--mcp']` into every
  1572. // agent's MCP config), not a command a human runs. It still works when
  1573. // invoked — hiding only removes it from the listing. See the interactive-TTY
  1574. // guard below, which explains this to anyone who runs it by hand.
  1575. .command('serve', { hidden: true })
  1576. .description('Start CodeGraph as an MCP server for AI assistants')
  1577. .option('-p, --path <path>', 'Project path (optional for MCP mode, uses rootUri from client)')
  1578. .option('--mcp', 'Run as MCP server (stdio transport)')
  1579. .option('--no-watch', 'Disable the file watcher (no auto-sync; useful on slow filesystems like WSL2 /mnt drives)')
  1580. .action(async (options: { path?: string; mcp?: boolean; watch?: boolean }) => {
  1581. const projectPath = options.path ? resolveProjectPath(options.path) : undefined;
  1582. // Commander sets watch=false when --no-watch is passed. Route it through
  1583. // the same env-var chokepoint the watcher and MCP server already honor.
  1584. if (options.watch === false) {
  1585. process.env.CODEGRAPH_NO_WATCH = '1';
  1586. }
  1587. try {
  1588. if (options.mcp) {
  1589. // `serve --mcp` is the stdio MCP server an AI agent launches for itself,
  1590. // not a command to run by hand. A human in a terminal would otherwise
  1591. // see it hang waiting for JSON-RPC on stdin, which reads as broken. If
  1592. // stdin is an interactive TTY, explain instead of hanging. The agent's
  1593. // pipe and the detached daemon both have a non-TTY stdin, so this only
  1594. // ever fires for a person who typed it.
  1595. if (process.stdin.isTTY && !process.env.CODEGRAPH_DAEMON_INTERNAL) {
  1596. console.error(chalk.bold('\nCodeGraph MCP server\n'));
  1597. console.error("This is the MCP server your AI agent (Claude Code, Cursor, Codex, opencode, …)");
  1598. console.error("starts automatically — you don't run it yourself.");
  1599. console.error(`\nIt's already wired up by ${chalk.cyan('codegraph install')}. To check on things:`);
  1600. console.error(` ${chalk.cyan('codegraph status')} ${chalk.dim('— is this project indexed and healthy?')}`);
  1601. console.error(` ${chalk.cyan('codegraph daemon')} ${chalk.dim('— list or stop background MCP servers')}`);
  1602. console.error(chalk.dim('\n(Running it directly only does something when an MCP client drives it over stdin.)'));
  1603. return;
  1604. }
  1605. // Start MCP server - it handles initialization lazily based on rootUri from client
  1606. const { MCPServer } = await import('../mcp/index');
  1607. const server = new MCPServer(projectPath);
  1608. await server.start();
  1609. // Server will run until terminated
  1610. } else {
  1611. // Default: show info about MCP mode.
  1612. // Use stderr so stdout stays clean for any piped/stdio usage.
  1613. console.error(chalk.bold('\nCodeGraph MCP Server\n'));
  1614. console.error(chalk.blue(getGlyphs().info) + ' Use --mcp flag to start the MCP server');
  1615. console.error('\nTo use with Claude Code, add to your MCP configuration:');
  1616. console.error(chalk.dim(`
  1617. {
  1618. "mcpServers": {
  1619. "codegraph": {
  1620. "command": "codegraph",
  1621. "args": ["serve", "--mcp"]
  1622. }
  1623. }
  1624. }
  1625. `));
  1626. console.error('Available tools:');
  1627. console.error(chalk.cyan(' codegraph_explore') + ' - Primary: source of the relevant symbols for any question');
  1628. console.error(chalk.cyan(' codegraph_search') + ' - Search for code symbols');
  1629. console.error(chalk.cyan(' codegraph_callers') + ' - Find callers of a symbol');
  1630. console.error(chalk.cyan(' codegraph_callees') + ' - Find what a symbol calls');
  1631. console.error(chalk.cyan(' codegraph_impact') + ' - Analyze impact of changes');
  1632. console.error(chalk.cyan(' codegraph_node') + ' - Get symbol details');
  1633. console.error(chalk.cyan(' codegraph_files') + ' - Get project file structure');
  1634. console.error(chalk.cyan(' codegraph_status') + ' - Get index status');
  1635. }
  1636. } catch (err) {
  1637. error(`Failed to start server: ${err instanceof Error ? err.message : String(err)}`);
  1638. process.exit(1);
  1639. }
  1640. });
  1641. /**
  1642. * codegraph unlock [path]
  1643. */
  1644. program
  1645. .command('unlock [path]')
  1646. .description('Remove a stale lock file that is blocking indexing')
  1647. .action(async (pathArg: string | undefined) => {
  1648. const projectPath = resolveProjectPath(pathArg);
  1649. try {
  1650. if (!isInitialized(projectPath)) {
  1651. error(`CodeGraph not initialized in ${projectPath}`);
  1652. return;
  1653. }
  1654. const lockPath = path.join(getCodeGraphDir(projectPath), 'codegraph.lock');
  1655. let removed = false;
  1656. if (fs.existsSync(lockPath)) {
  1657. fs.unlinkSync(lockPath);
  1658. removed = true;
  1659. }
  1660. const { clearStaleDaemonArtifacts } = await import('../mcp/daemon-registry');
  1661. removed = await clearStaleDaemonArtifacts(projectPath) || removed;
  1662. if (removed) success('Removed stale lock artifacts. You can now run indexing again.');
  1663. else info(`No stale lock files found ${getGlyphs().dash} nothing to do`);
  1664. } catch (err) {
  1665. error(`Failed to remove lock: ${err instanceof Error ? err.message : String(err)}`);
  1666. process.exit(1);
  1667. }
  1668. });
  1669. /**
  1670. * codegraph callers <symbol>
  1671. *
  1672. * CLI parity with the MCP graph tools (codegraph_callers/callees/impact) so the
  1673. * traversal queries work in scripts, CI, and git hooks without a running MCP
  1674. * server.
  1675. */
  1676. program
  1677. .command('callers <symbol>')
  1678. .description('Find all functions/methods that call a specific symbol')
  1679. .option('-p, --path <path>', 'Project path')
  1680. .option('-l, --limit <number>', 'Maximum results', '20')
  1681. .option('-j, --json', 'Output as JSON')
  1682. .action(async (symbol: string, options: { path?: string; limit?: string; json?: boolean }) => {
  1683. const projectPath = resolveProjectPath(options.path);
  1684. try {
  1685. if (!isInitialized(projectPath)) {
  1686. error(`CodeGraph not initialized in ${projectPath}`);
  1687. process.exit(1);
  1688. }
  1689. const { default: CodeGraph } = await loadCodeGraph();
  1690. const cg = await CodeGraph.open(projectPath);
  1691. const limit = parseInt(options.limit || '20', 10);
  1692. const matches = cg.searchNodes(symbol, { limit: 50 });
  1693. if (matches.length === 0) {
  1694. info(`Symbol "${symbol}" not found`);
  1695. cg.destroy();
  1696. return;
  1697. }
  1698. const seen = new Set<string>();
  1699. const allCallers: Array<{ name: string; kind: string; filePath: string; startLine?: number }> = [];
  1700. for (const match of matches) {
  1701. const exactMatch = match.node.name === symbol || match.node.name.endsWith(`.${symbol}`) || match.node.name.endsWith(`::${symbol}`);
  1702. if (!exactMatch && matches.length > 1) continue;
  1703. for (const c of cg.getCallers(match.node.id)) {
  1704. if (!seen.has(c.node.id)) {
  1705. seen.add(c.node.id);
  1706. allCallers.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
  1707. }
  1708. }
  1709. }
  1710. // Fallback: if exact filter removed everything, use the top match
  1711. if (allCallers.length === 0 && matches[0]) {
  1712. for (const c of cg.getCallers(matches[0].node.id)) {
  1713. if (!seen.has(c.node.id)) {
  1714. seen.add(c.node.id);
  1715. allCallers.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
  1716. }
  1717. }
  1718. }
  1719. const limited = allCallers.slice(0, limit);
  1720. if (options.json) {
  1721. console.log(JSON.stringify({ symbol, callers: limited }, null, 2));
  1722. } else if (limited.length === 0) {
  1723. info(`No callers found for "${symbol}"`);
  1724. } else {
  1725. console.log(chalk.bold(`\nCallers of "${symbol}" (${limited.length}):\n`));
  1726. for (const node of limited) {
  1727. const loc = node.startLine ? `:${node.startLine}` : '';
  1728. console.log(
  1729. chalk.cyan(node.kind.padEnd(12)) +
  1730. chalk.white(node.name)
  1731. );
  1732. console.log(chalk.dim(` ${node.filePath}${loc}`));
  1733. console.log();
  1734. }
  1735. }
  1736. cg.destroy();
  1737. } catch (err) {
  1738. error(`callers failed: ${err instanceof Error ? err.message : String(err)}`);
  1739. process.exit(1);
  1740. }
  1741. });
  1742. /**
  1743. * codegraph callees <symbol>
  1744. */
  1745. program
  1746. .command('callees <symbol>')
  1747. .description('Find all functions/methods that a specific symbol calls')
  1748. .option('-p, --path <path>', 'Project path')
  1749. .option('-l, --limit <number>', 'Maximum results', '20')
  1750. .option('-j, --json', 'Output as JSON')
  1751. .action(async (symbol: string, options: { path?: string; limit?: string; json?: boolean }) => {
  1752. const projectPath = resolveProjectPath(options.path);
  1753. try {
  1754. if (!isInitialized(projectPath)) {
  1755. error(`CodeGraph not initialized in ${projectPath}`);
  1756. process.exit(1);
  1757. }
  1758. const { default: CodeGraph } = await loadCodeGraph();
  1759. const cg = await CodeGraph.open(projectPath);
  1760. const limit = parseInt(options.limit || '20', 10);
  1761. const matches = cg.searchNodes(symbol, { limit: 50 });
  1762. if (matches.length === 0) {
  1763. info(`Symbol "${symbol}" not found`);
  1764. cg.destroy();
  1765. return;
  1766. }
  1767. const seen = new Set<string>();
  1768. const allCallees: Array<{ name: string; kind: string; filePath: string; startLine?: number }> = [];
  1769. for (const match of matches) {
  1770. const exactMatch = match.node.name === symbol || match.node.name.endsWith(`.${symbol}`) || match.node.name.endsWith(`::${symbol}`);
  1771. if (!exactMatch && matches.length > 1) continue;
  1772. for (const c of cg.getCallees(match.node.id)) {
  1773. if (!seen.has(c.node.id)) {
  1774. seen.add(c.node.id);
  1775. allCallees.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
  1776. }
  1777. }
  1778. }
  1779. if (allCallees.length === 0 && matches[0]) {
  1780. for (const c of cg.getCallees(matches[0].node.id)) {
  1781. if (!seen.has(c.node.id)) {
  1782. seen.add(c.node.id);
  1783. allCallees.push({ name: c.node.name, kind: c.node.kind, filePath: c.node.filePath, startLine: c.node.startLine });
  1784. }
  1785. }
  1786. }
  1787. const limited = allCallees.slice(0, limit);
  1788. if (options.json) {
  1789. console.log(JSON.stringify({ symbol, callees: limited }, null, 2));
  1790. } else if (limited.length === 0) {
  1791. info(`No callees found for "${symbol}"`);
  1792. } else {
  1793. console.log(chalk.bold(`\nCallees of "${symbol}" (${limited.length}):\n`));
  1794. for (const node of limited) {
  1795. const loc = node.startLine ? `:${node.startLine}` : '';
  1796. console.log(
  1797. chalk.cyan(node.kind.padEnd(12)) +
  1798. chalk.white(node.name)
  1799. );
  1800. console.log(chalk.dim(` ${node.filePath}${loc}`));
  1801. console.log();
  1802. }
  1803. }
  1804. cg.destroy();
  1805. } catch (err) {
  1806. error(`callees failed: ${err instanceof Error ? err.message : String(err)}`);
  1807. process.exit(1);
  1808. }
  1809. });
  1810. /**
  1811. * codegraph impact <symbol>
  1812. */
  1813. program
  1814. .command('impact <symbol>')
  1815. .description('Analyze what code is affected by changing a symbol')
  1816. .option('-p, --path <path>', 'Project path')
  1817. .option('-d, --depth <number>', 'Traversal depth', '2')
  1818. .option('-j, --json', 'Output as JSON')
  1819. .action(async (symbol: string, options: { path?: string; depth?: string; json?: boolean }) => {
  1820. const projectPath = resolveProjectPath(options.path);
  1821. try {
  1822. if (!isInitialized(projectPath)) {
  1823. error(`CodeGraph not initialized in ${projectPath}`);
  1824. process.exit(1);
  1825. }
  1826. const { default: CodeGraph } = await loadCodeGraph();
  1827. const cg = await CodeGraph.open(projectPath);
  1828. const depth = Math.min(Math.max(parseInt(options.depth || '2', 10), 1), 10);
  1829. const matches = cg.searchNodes(symbol, { limit: 50 });
  1830. if (matches.length === 0) {
  1831. info(`Symbol "${symbol}" not found`);
  1832. cg.destroy();
  1833. return;
  1834. }
  1835. // Merge impact subgraphs across all exact-matching symbols
  1836. const mergedNodes = new Map<string, { name: string; kind: string; filePath: string; startLine?: number }>();
  1837. const seenEdges = new Set<string>();
  1838. let edgeCount = 0;
  1839. for (const match of matches) {
  1840. const exactMatch = match.node.name === symbol || match.node.name.endsWith(`.${symbol}`) || match.node.name.endsWith(`::${symbol}`);
  1841. if (!exactMatch && matches.length > 1) continue;
  1842. const impact = cg.getImpactRadius(match.node.id, depth);
  1843. for (const [id, n] of impact.nodes) {
  1844. mergedNodes.set(id, { name: n.name, kind: n.kind, filePath: n.filePath, startLine: n.startLine });
  1845. }
  1846. for (const e of impact.edges) {
  1847. const key = `${e.source}->${e.target}:${e.kind}`;
  1848. if (!seenEdges.has(key)) {
  1849. seenEdges.add(key);
  1850. edgeCount++;
  1851. }
  1852. }
  1853. }
  1854. // Fallback to top match if exact filter removed everything
  1855. if (mergedNodes.size === 0 && matches[0]) {
  1856. const impact = cg.getImpactRadius(matches[0].node.id, depth);
  1857. for (const [id, n] of impact.nodes) {
  1858. mergedNodes.set(id, { name: n.name, kind: n.kind, filePath: n.filePath, startLine: n.startLine });
  1859. }
  1860. edgeCount = impact.edges.length;
  1861. }
  1862. if (options.json) {
  1863. console.log(JSON.stringify({
  1864. symbol,
  1865. depth,
  1866. nodeCount: mergedNodes.size,
  1867. edgeCount,
  1868. affected: Array.from(mergedNodes.values()),
  1869. }, null, 2));
  1870. } else if (mergedNodes.size === 0) {
  1871. info(`No affected symbols found for "${symbol}"`);
  1872. } else {
  1873. console.log(chalk.bold(`\nImpact of changing "${symbol}" — ${mergedNodes.size} affected symbols:\n`));
  1874. // Group by file
  1875. const byFile = new Map<string, Array<{ name: string; kind: string; startLine?: number }>>();
  1876. for (const node of mergedNodes.values()) {
  1877. const list = byFile.get(node.filePath) || [];
  1878. list.push({ name: node.name, kind: node.kind, startLine: node.startLine });
  1879. byFile.set(node.filePath, list);
  1880. }
  1881. for (const [file, nodes] of byFile) {
  1882. console.log(chalk.cyan(file));
  1883. for (const node of nodes) {
  1884. const loc = node.startLine ? `:${node.startLine}` : '';
  1885. console.log(` ${chalk.dim(node.kind.padEnd(12))}${node.name}${chalk.dim(loc)}`);
  1886. }
  1887. console.log();
  1888. }
  1889. }
  1890. cg.destroy();
  1891. } catch (err) {
  1892. error(`impact failed: ${err instanceof Error ? err.message : String(err)}`);
  1893. process.exit(1);
  1894. }
  1895. });
  1896. /**
  1897. * codegraph affected [files...]
  1898. *
  1899. * Find test files affected by the given source files.
  1900. * Traces dependency edges transitively to find test files that depend on changed code.
  1901. *
  1902. * Usage:
  1903. * git diff --name-only | codegraph affected --stdin
  1904. * codegraph affected src/lib/components/Editor.svelte src/routes/+page.svelte
  1905. */
  1906. program
  1907. .command('affected [files...]')
  1908. .description('Find test files affected by changed source files')
  1909. .option('-p, --path <path>', 'Project path')
  1910. .option('--stdin', 'Read file list from stdin (one per line)')
  1911. .option('-d, --depth <number>', 'Max dependency traversal depth', '5')
  1912. .option('-f, --filter <glob>', 'Custom glob filter for test files (e.g. "e2e/*.spec.ts")')
  1913. .option('-j, --json', 'Output as JSON')
  1914. .option('-q, --quiet', 'Only output file paths, no decoration')
  1915. .action(async (fileArgs: string[], options: { path?: string; stdin?: boolean; depth?: string; filter?: string; json?: boolean; quiet?: boolean }) => {
  1916. const projectPath = resolveProjectPath(options.path);
  1917. try {
  1918. if (!isInitialized(projectPath)) {
  1919. error(`CodeGraph not initialized in ${projectPath}`);
  1920. process.exit(1);
  1921. }
  1922. // Collect changed files from args or stdin
  1923. let changedFiles: string[] = [...(fileArgs || [])];
  1924. if (options.stdin) {
  1925. const stdinData = fs.readFileSync(0, 'utf-8');
  1926. const stdinFiles = stdinData.split('\n').map(f => f.trim()).filter(Boolean);
  1927. changedFiles.push(...stdinFiles);
  1928. }
  1929. // Normalize inputs to the project-relative, forward-slash form the index
  1930. // stores. Without this, `affected ./src/x.ts`, an absolute path (what a
  1931. // wrapping script often passes), or a Windows back-slash path silently
  1932. // matches nothing and reports 0 affected tests. (#825)
  1933. changedFiles = changedFiles
  1934. .map((f) => normalizeIndexPath(f, projectPath))
  1935. .filter(Boolean);
  1936. if (changedFiles.length === 0) {
  1937. if (!options.quiet) info('No files provided. Use file arguments or --stdin.');
  1938. process.exit(0);
  1939. }
  1940. const { default: CodeGraph } = await loadCodeGraph();
  1941. const cg = await CodeGraph.open(projectPath);
  1942. const maxDepth = parseInt(options.depth || '5', 10);
  1943. // Common test file patterns
  1944. const defaultTestPatterns = [
  1945. /\.spec\./,
  1946. /\.test\./,
  1947. /\/__tests__\//,
  1948. /\/tests?\//,
  1949. /\/e2e\//,
  1950. /\/spec\//,
  1951. ];
  1952. // Custom filter pattern
  1953. let customFilter: RegExp | null = null;
  1954. if (options.filter) {
  1955. // Convert glob to regex: ** → .+, * → [^/]*, . → \.
  1956. const regex = options.filter
  1957. .replace(/[+[\]{}()^$|\\]/g, '\\$&')
  1958. .replace(/\./g, '\\.')
  1959. .replace(/\*\*/g, '.+')
  1960. .replace(/\*/g, '[^/]*');
  1961. customFilter = new RegExp(regex);
  1962. }
  1963. function isTestFile(filePath: string): boolean {
  1964. if (customFilter) return customFilter.test(filePath);
  1965. return defaultTestPatterns.some(p => p.test(filePath));
  1966. }
  1967. // BFS to find all transitive dependents of changed files, filtered to test files
  1968. const affectedTests = new Set<string>();
  1969. const allDependents = new Set<string>();
  1970. for (const file of changedFiles) {
  1971. // If the changed file is itself a test file, include it
  1972. if (isTestFile(file)) {
  1973. affectedTests.add(file);
  1974. continue;
  1975. }
  1976. // BFS through dependents
  1977. const queue: Array<{ file: string; depth: number }> = [{ file, depth: 0 }];
  1978. const visited = new Set<string>();
  1979. visited.add(file);
  1980. while (queue.length > 0) {
  1981. const current = queue.shift()!;
  1982. if (current.depth >= maxDepth) continue;
  1983. const dependents = cg.getFileDependents(current.file);
  1984. for (const dep of dependents) {
  1985. if (visited.has(dep)) continue;
  1986. visited.add(dep);
  1987. allDependents.add(dep);
  1988. if (isTestFile(dep)) {
  1989. affectedTests.add(dep);
  1990. } else {
  1991. queue.push({ file: dep, depth: current.depth + 1 });
  1992. }
  1993. }
  1994. }
  1995. }
  1996. const sortedTests = Array.from(affectedTests).sort();
  1997. // Output
  1998. if (options.json) {
  1999. console.log(JSON.stringify({
  2000. changedFiles,
  2001. affectedTests: sortedTests,
  2002. totalDependentsTraversed: allDependents.size,
  2003. }, null, 2));
  2004. } else if (options.quiet) {
  2005. for (const t of sortedTests) console.log(t);
  2006. } else {
  2007. if (sortedTests.length === 0) {
  2008. info('No test files affected by the changed files.');
  2009. } else {
  2010. console.log(chalk.bold(`\nAffected test files (${sortedTests.length}):\n`));
  2011. for (const t of sortedTests) {
  2012. console.log(' ' + chalk.cyan(t));
  2013. }
  2014. console.log();
  2015. }
  2016. }
  2017. cg.destroy();
  2018. } catch (err) {
  2019. error(`Affected analysis failed: ${err instanceof Error ? err.message : String(err)}`);
  2020. process.exit(1);
  2021. }
  2022. });
  2023. /**
  2024. * codegraph install
  2025. */
  2026. program
  2027. .command('install')
  2028. .description('Install codegraph MCP server into one or more agents (Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, Kiro, GitHub Copilot)')
  2029. .option('-t, --target <ids>', 'Target agent(s): comma-separated ids, or "auto"|"all"|"none". Default: prompt')
  2030. .option('-l, --location <where>', 'Install location: "global" or "local". Default: prompt')
  2031. .option('-y, --yes', 'Non-interactive: defaults to --location=global --target=auto, auto-allow on')
  2032. .option('--no-permissions', 'Skip writing the auto-allow permissions list (Claude Code only)')
  2033. .option('--print-config <id>', 'Print MCP config snippet for the named agent and exit (no file writes)')
  2034. .option('--refresh', 'Rewrite what previous installs configured, for already-configured agents only (never adds new ones). Run automatically by `codegraph upgrade`')
  2035. .action(async (opts: {
  2036. target?: string;
  2037. location?: string;
  2038. yes?: boolean;
  2039. permissions?: boolean;
  2040. printConfig?: string;
  2041. refresh?: boolean;
  2042. }) => {
  2043. if (opts.printConfig) {
  2044. const { getTarget, listTargetIds } = await import('../installer/targets/registry');
  2045. const target = getTarget(opts.printConfig);
  2046. if (!target) {
  2047. const known = listTargetIds().join(', ');
  2048. error(`Unknown target "${opts.printConfig}". Known: ${known}.`);
  2049. process.exit(1);
  2050. }
  2051. const loc = (opts.location === 'local' ? 'local' : 'global') as 'global' | 'local';
  2052. process.stdout.write(target.printConfig(loc));
  2053. return;
  2054. }
  2055. // --refresh: non-interactive sweep that re-writes what previous
  2056. // installs configured (instructions section, MCP entry, legacy-hook
  2057. // cleanups) for already-configured agents, so those surfaces match
  2058. // THIS binary's templates. Skips everything else — never a first
  2059. // install, never touches permissions or the prompt hook. Sweeps both
  2060. // locations unless --location narrows it.
  2061. if (opts.refresh) {
  2062. const { refreshTargets } = await import('../installer');
  2063. const { ALL_TARGETS } = await import('../installer/targets/registry');
  2064. if (opts.location && opts.location !== 'global' && opts.location !== 'local') {
  2065. error(`--location must be "global" or "local" (got "${opts.location}").`);
  2066. process.exit(1);
  2067. }
  2068. const locs: Array<'global' | 'local'> = opts.location
  2069. ? [opts.location as 'global' | 'local']
  2070. : ['global', 'local'];
  2071. let changed = 0;
  2072. for (const loc of locs) {
  2073. for (const report of refreshTargets(ALL_TARGETS, loc)) {
  2074. for (const p of report.changedPaths) {
  2075. changed += 1;
  2076. console.log(` ${report.displayName}: refreshed ${p}`);
  2077. }
  2078. }
  2079. }
  2080. if (changed === 0) {
  2081. console.log('All configured agent surfaces are already current.');
  2082. }
  2083. return;
  2084. }
  2085. const { runInstallerWithOptions } = await import('../installer');
  2086. if (opts.location && opts.location !== 'global' && opts.location !== 'local') {
  2087. error(`--location must be "global" or "local" (got "${opts.location}").`);
  2088. process.exit(1);
  2089. }
  2090. try {
  2091. // Commander's `--no-permissions` makes `opts.permissions === false`;
  2092. // omitting the flag leaves it `true` (the positive-form default).
  2093. // We MUST treat the default-true as "user did not override — let
  2094. // the orchestrator prompt" and only forward an explicit `false`
  2095. // (or `true` when --yes implies it). Otherwise the auto-allow
  2096. // prompt is silently skipped on every interactive run.
  2097. const explicitNoPermissions = opts.permissions === false;
  2098. const autoAllow: boolean | undefined = explicitNoPermissions
  2099. ? false
  2100. : opts.yes
  2101. ? true
  2102. : undefined;
  2103. await runInstallerWithOptions({
  2104. target: opts.target,
  2105. location: opts.location as 'global' | 'local' | undefined,
  2106. autoAllow,
  2107. yes: opts.yes,
  2108. });
  2109. } catch (err) {
  2110. error(err instanceof Error ? err.message : String(err));
  2111. process.exit(1);
  2112. }
  2113. });
  2114. /**
  2115. * codegraph uninstall
  2116. *
  2117. * Inverse of `install`. Removes the codegraph MCP server entry,
  2118. * instructions block, and permissions from every agent (or a
  2119. * `--target` subset). Prompts global-vs-local when not given. Does NOT
  2120. * delete the `.codegraph/` index — that's `codegraph uninit`.
  2121. */
  2122. program
  2123. .command('uninstall')
  2124. .description('Remove codegraph from your agents (Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, Kiro, GitHub Copilot)')
  2125. .option('-t, --target <ids>', 'Target agent(s): comma-separated ids, or "all". Default: all')
  2126. .option('-l, --location <where>', 'Uninstall location: "global" or "local". Default: prompt')
  2127. .option('-y, --yes', 'Non-interactive: defaults to --location=global --target=all')
  2128. .option('--keep-cli', 'Remove agent configs only — leave the codegraph CLI installed')
  2129. .action(async (opts: {
  2130. target?: string;
  2131. location?: string;
  2132. yes?: boolean;
  2133. keepCli?: boolean;
  2134. }) => {
  2135. const { runUninstaller } = await import('../installer');
  2136. if (opts.location && opts.location !== 'global' && opts.location !== 'local') {
  2137. error(`--location must be "global" or "local" (got "${opts.location}").`);
  2138. process.exit(1);
  2139. }
  2140. try {
  2141. await runUninstaller({
  2142. target: opts.target,
  2143. location: opts.location as 'global' | 'local' | undefined,
  2144. yes: opts.yes,
  2145. keepCli: opts.keepCli,
  2146. cliFilename: __filename,
  2147. });
  2148. } catch (err) {
  2149. error(err instanceof Error ? err.message : String(err));
  2150. process.exit(1);
  2151. }
  2152. });
  2153. /**
  2154. * codegraph telemetry [on|off|status]
  2155. */
  2156. program
  2157. .command('telemetry [action]')
  2158. .description('Show or change anonymous usage telemetry (status, on, off)')
  2159. .action((action?: string) => {
  2160. const t = getTelemetry();
  2161. if (action === 'on' || action === 'off') {
  2162. t.setEnabled(action === 'on', 'cli');
  2163. if (action === 'on') {
  2164. success('Telemetry enabled — anonymous usage stats only (no code, paths, or names).');
  2165. } else {
  2166. success('Telemetry disabled. Buffered, unsent data was deleted.');
  2167. }
  2168. const effective = t.getStatus();
  2169. if (effective.decidedBy === 'DO_NOT_TRACK' || effective.decidedBy === 'CODEGRAPH_TELEMETRY') {
  2170. warn(
  2171. `The ${effective.decidedBy} environment variable overrides this choice — ` +
  2172. `effective state right now: ${effective.enabled ? 'enabled' : 'disabled'}.`
  2173. );
  2174. }
  2175. return;
  2176. }
  2177. if (action !== undefined && action !== 'status') {
  2178. error(`Unknown action: ${action} (expected status, on, or off)`);
  2179. process.exit(1);
  2180. }
  2181. const s = t.getStatus();
  2182. const decidedBy: Record<typeof s.decidedBy, string> = {
  2183. DO_NOT_TRACK: 'DO_NOT_TRACK environment variable',
  2184. CODEGRAPH_TELEMETRY: 'CODEGRAPH_TELEMETRY environment variable',
  2185. config: 'your saved choice',
  2186. default: 'default',
  2187. };
  2188. console.log(`\nTelemetry: ${s.enabled ? chalk.green('enabled') : chalk.yellow('disabled')} ${chalk.dim(`(${decidedBy[s.decidedBy]})`)}`);
  2189. console.log(`Machine ID: ${s.machineId ?? chalk.dim('(random UUID, created on first use)')}`);
  2190. console.log(`Config: ${s.configPath}`);
  2191. console.log(chalk.dim(`\nExactly what is collected (and never collected): ${TELEMETRY_DOCS}\n`));
  2192. });
  2193. /**
  2194. * codegraph upgrade [version]
  2195. *
  2196. * Self-update, however CodeGraph was installed (bundle via install.sh/.ps1,
  2197. * npm-global, npx, or a source checkout). See ../upgrade for the detection and
  2198. * per-method upgrade logic.
  2199. */
  2200. program
  2201. .command('upgrade [version]')
  2202. .description('Update CodeGraph to the latest release (or a specific version)')
  2203. .option('--check', 'Check whether an update is available without installing')
  2204. .option('-f, --force', 'Reinstall even if already on the target version')
  2205. .action(async (versionArg: string | undefined, options: { check?: boolean; force?: boolean }) => {
  2206. const up = await import('../upgrade');
  2207. const method = up.detectInstallMethod({
  2208. filename: __filename,
  2209. platform: process.platform,
  2210. cwd: process.cwd(),
  2211. });
  2212. const pin = versionArg || process.env.CODEGRAPH_VERSION || undefined;
  2213. const code = await up.runUpgrade(
  2214. { version: pin, check: options.check, force: options.force },
  2215. {
  2216. currentVersion: packageJson.version,
  2217. method,
  2218. resolveLatest: () => up.resolveLatestVersion(),
  2219. run: up.defaultRun,
  2220. capture: up.defaultCapture,
  2221. hasCommand: up.hasCommand,
  2222. log: (m: string) => console.log(m),
  2223. warn: (m: string) => warn(m),
  2224. error: (m: string) => error(m),
  2225. platform: process.platform,
  2226. offerBetaSignup: async () => {
  2227. const { maybeOfferBetaSignup } = await import('../installer/beta-signup');
  2228. await maybeOfferBetaSignup({ source: 'cli-upgrade' });
  2229. },
  2230. }
  2231. );
  2232. process.exit(code);
  2233. });
  2234. /**
  2235. * codegraph version
  2236. *
  2237. * The bare-noun form of `--version`. commander already provides `--version`
  2238. * and `-V`, and the `-v` / `-version` spellings are intercepted before parse
  2239. * (see top of main). This subcommand makes `codegraph version` work and lists
  2240. * the version affordance in `codegraph --help`.
  2241. */
  2242. program
  2243. .command('version')
  2244. .description('Print the installed CodeGraph version (also: -v, --version)')
  2245. .action(() => {
  2246. console.log(packageJson.version);
  2247. });
  2248. // Parse and run
  2249. program.parse();
  2250. } // end main()