codegraph.ts 115 KB

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