codegraph.ts 111 KB

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