index.ts 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  1. /**
  2. * CodeGraph
  3. *
  4. * A local-first code intelligence system that builds a semantic
  5. * knowledge graph from any codebase.
  6. */
  7. import * as path from 'path';
  8. import {
  9. Node,
  10. NodeKind,
  11. Edge,
  12. FileRecord,
  13. ExtractionResult,
  14. Subgraph,
  15. TraversalOptions,
  16. SearchOptions,
  17. SearchResult,
  18. SegmentMatch,
  19. Context,
  20. GraphStats,
  21. TaskInput,
  22. TaskContext,
  23. BuildContextOptions,
  24. FindRelevantContextOptions,
  25. } from './types';
  26. import { DatabaseConnection, getDatabasePath, removeDatabaseFiles } from './db';
  27. import { WalCheckpointValve } from './db/wal-valve';
  28. import { QueryBuilder } from './db/queries';
  29. import {
  30. isInitialized,
  31. createDirectory,
  32. removeDirectory,
  33. validateDirectory,
  34. } from './directory';
  35. import {
  36. ExtractionOrchestrator,
  37. IndexProgress,
  38. IndexResult,
  39. SyncResult,
  40. extractFromSource,
  41. initGrammars,
  42. } from './extraction';
  43. import {
  44. ReferenceResolver,
  45. createResolver,
  46. ResolutionResult,
  47. } from './resolution';
  48. import { GraphTraverser, GraphQueryManager } from './graph';
  49. import { ContextBuilder, createContextBuilder } from './context';
  50. import { Mutex, FileLock } from './utils';
  51. import { FileWatcher, WatchOptions, PendingFile, LockUnavailableError } from './sync';
  52. import { EXTRACTION_VERSION } from './extraction/extraction-version';
  53. import { getCodeGraphDir } from './directory';
  54. import { deriveProjectNameTokens } from './search/query-utils';
  55. import { CodeGraphPackageVersion } from './mcp/version';
  56. import { segmentLookupVariants, splitIdentifierSegments } from './search/identifier-segments';
  57. import { createYielder } from './resolution/cooperative-yield';
  58. import { minRefsForPool } from './resolution/resolver-pool';
  59. // Re-export types for consumers
  60. export * from './types';
  61. // Storage building blocks for embedded/SDK consumers that drive the graph
  62. // directly (open a DB, run prepared queries) rather than through the CodeGraph
  63. // facade. Exposed from the package entry so they no longer require deep imports
  64. // into dist/ (issue #354).
  65. export { getDatabasePath, DatabaseConnection } from './db';
  66. export { QueryBuilder } from './db/queries';
  67. export {
  68. getCodeGraphDir,
  69. isInitialized,
  70. findNearestCodeGraphRoot,
  71. CODEGRAPH_DIR,
  72. } from './directory';
  73. export { IndexProgress, IndexResult, SyncResult } from './extraction';
  74. export { detectLanguage, isLanguageSupported, isGrammarLoaded, getSupportedLanguages, initGrammars, loadGrammarsForLanguages, loadAllGrammars } from './extraction';
  75. export { ResolutionResult } from './resolution';
  76. export {
  77. CodeGraphError,
  78. FileError,
  79. ParseError,
  80. DatabaseError,
  81. SearchError,
  82. VectorError,
  83. ConfigError,
  84. Logger,
  85. setLogger,
  86. getLogger,
  87. silentLogger,
  88. defaultLogger,
  89. } from './errors';
  90. export { Mutex, FileLock, processInBatches, debounce, throttle, MemoryMonitor } from './utils';
  91. export { FileWatcher, WatchOptions, PendingFile, LockUnavailableError } from './sync';
  92. export { MCPServer } from './mcp';
  93. /**
  94. * Options for initializing a new CodeGraph project
  95. */
  96. export interface InitOptions {
  97. /** Whether to run initial indexing after init */
  98. index?: boolean;
  99. /** Progress callback for indexing */
  100. onProgress?: (progress: IndexProgress) => void;
  101. }
  102. /**
  103. * Options for opening an existing CodeGraph project
  104. */
  105. export interface OpenOptions {
  106. /** Whether to run sync if files have changed */
  107. sync?: boolean;
  108. /** Whether to run in read-only mode */
  109. readOnly?: boolean;
  110. }
  111. /**
  112. * Options for indexing
  113. */
  114. export interface IndexOptions {
  115. /** Progress callback */
  116. onProgress?: (progress: IndexProgress) => void;
  117. /** Abort signal for cancellation */
  118. signal?: AbortSignal;
  119. /** Enable verbose logging (worker lifecycle, memory, timeouts) */
  120. verbose?: boolean;
  121. }
  122. /**
  123. * Main CodeGraph class
  124. *
  125. * Provides the primary interface for interacting with the code knowledge graph.
  126. */
  127. export class CodeGraph {
  128. private db: DatabaseConnection;
  129. private queries: QueryBuilder;
  130. private projectRoot: string;
  131. // Assigned via wireLayers() from the constructor (and again on reopen) — the
  132. // `!` tells TS these are definitely set even though the assignment is one
  133. // method call away from the constructor body.
  134. private orchestrator!: ExtractionOrchestrator;
  135. private resolver!: ReferenceResolver;
  136. private graphManager!: GraphQueryManager;
  137. private traverser!: GraphTraverser;
  138. private contextBuilder!: ContextBuilder;
  139. // Mutex for preventing concurrent indexing operations (in-process)
  140. private indexMutex = new Mutex();
  141. // File lock for preventing concurrent writes across processes (CLI, MCP, git hooks)
  142. private fileLock: FileLock;
  143. // File watcher for auto-sync on file changes
  144. private watcher: FileWatcher | null = null;
  145. private constructor(
  146. db: DatabaseConnection,
  147. queries: QueryBuilder,
  148. projectRoot: string
  149. ) {
  150. this.db = db;
  151. this.queries = queries;
  152. this.projectRoot = projectRoot;
  153. this.fileLock = new FileLock(
  154. path.join(getCodeGraphDir(projectRoot), 'codegraph.lock')
  155. );
  156. this.wireLayers();
  157. }
  158. /**
  159. * (Re)build the query/extraction/graph layers over the current `this.queries`
  160. * (which wraps `this.db`). Factored out of the constructor so `reopenIfReplaced`
  161. * can rebuild them against a fresh connection without duplicating the wiring.
  162. * The path-based `fileLock` is independent of the DB handle, so it stays put.
  163. */
  164. private wireLayers(): void {
  165. // Down-weight the project name as a query term in search ranking — it names
  166. // the whole repo, not a symbol, so it has no discriminative value (#720).
  167. try {
  168. this.queries.setProjectNameTokens(deriveProjectNameTokens(this.projectRoot));
  169. } catch {
  170. // Best-effort: ranking still works without it.
  171. }
  172. this.orchestrator = new ExtractionOrchestrator(this.projectRoot, this.queries);
  173. this.resolver = createResolver(this.projectRoot, this.queries);
  174. this.graphManager = new GraphQueryManager(this.queries);
  175. this.traverser = new GraphTraverser(this.queries);
  176. this.contextBuilder = createContextBuilder(
  177. this.projectRoot,
  178. this.queries,
  179. this.traverser
  180. );
  181. }
  182. /**
  183. * Heal a stale database handle in place. If `.codegraph/` was removed and
  184. * recreated at the SAME path while this instance held the DB open — a git
  185. * worktree removed and re-added, or `rm -rf .codegraph` + `codegraph init` —
  186. * our open fd points at the now-unlinked inode and can never see the new
  187. * index, so every query returns the pre-removal snapshot until the process
  188. * restarts (#925). When that's detected, open the live file at the same path,
  189. * rebuild the query layers, and swap them IN PLACE, so every holder of this
  190. * instance (the MCP daemon's default project, cached projectPath connections)
  191. * heals without a restart. Returns true iff it reopened.
  192. *
  193. * POSIX-only in practice: `isReplacedOnDisk` never fires on Windows (an open
  194. * file can't be unlinked there, and st_ino is unreliable).
  195. */
  196. reopenIfReplaced(): boolean {
  197. if (!this.db.isReplacedOnDisk()) return false;
  198. const dbPath = this.db.getPath();
  199. // Open the live file FIRST — if that throws (e.g. mid-recreate), the old
  200. // handle stays in place and the caller retries on the next query, rather
  201. // than leaving this instance with no connection at all.
  202. const fresh = DatabaseConnection.open(dbPath);
  203. const stale = this.db;
  204. this.db = fresh;
  205. this.queries = new QueryBuilder(fresh.getDb());
  206. this.wireLayers();
  207. // Releasing the dead handle also frees the leaked db/-wal/-shm fds that were
  208. // pinning the unlinked inode (#925).
  209. try { stale.close(); } catch { /* the old inode is gone; closing just frees fds */ }
  210. return true;
  211. }
  212. // ===========================================================================
  213. // Lifecycle Methods
  214. // ===========================================================================
  215. /**
  216. * Initialize a new CodeGraph project
  217. *
  218. * Creates the .CodeGraph directory, database, and configuration.
  219. *
  220. * @param projectRoot - Path to the project root directory
  221. * @param options - Initialization options
  222. * @returns A new CodeGraph instance
  223. */
  224. static async init(projectRoot: string, options: InitOptions = {}): Promise<CodeGraph> {
  225. await initGrammars();
  226. const resolvedRoot = path.resolve(projectRoot);
  227. // Check if already initialized
  228. if (isInitialized(resolvedRoot)) {
  229. throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
  230. }
  231. // Create directory structure
  232. createDirectory(resolvedRoot);
  233. // Initialize database
  234. const dbPath = getDatabasePath(resolvedRoot);
  235. const db = DatabaseConnection.initialize(dbPath);
  236. const queries = new QueryBuilder(db.getDb());
  237. const instance = new CodeGraph(db, queries, resolvedRoot);
  238. // Run initial indexing if requested
  239. if (options.index) {
  240. await instance.indexAll({ onProgress: options.onProgress });
  241. }
  242. return instance;
  243. }
  244. /**
  245. * Initialize synchronously (without indexing)
  246. */
  247. static initSync(projectRoot: string): CodeGraph {
  248. const resolvedRoot = path.resolve(projectRoot);
  249. // Check if already initialized
  250. if (isInitialized(resolvedRoot)) {
  251. throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
  252. }
  253. // Create directory structure
  254. createDirectory(resolvedRoot);
  255. // Initialize database
  256. const dbPath = getDatabasePath(resolvedRoot);
  257. const db = DatabaseConnection.initialize(dbPath);
  258. const queries = new QueryBuilder(db.getDb());
  259. return new CodeGraph(db, queries, resolvedRoot);
  260. }
  261. /**
  262. * Open an existing CodeGraph project
  263. *
  264. * @param projectRoot - Path to the project root directory
  265. * @param options - Open options
  266. * @returns A CodeGraph instance
  267. */
  268. static async open(projectRoot: string, options: OpenOptions = {}): Promise<CodeGraph> {
  269. await initGrammars();
  270. const resolvedRoot = path.resolve(projectRoot);
  271. // Check if initialized
  272. if (!isInitialized(resolvedRoot)) {
  273. throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
  274. }
  275. // Validate directory structure
  276. const validation = validateDirectory(resolvedRoot);
  277. if (!validation.valid) {
  278. throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
  279. }
  280. // Open database
  281. const dbPath = getDatabasePath(resolvedRoot);
  282. const db = DatabaseConnection.open(dbPath);
  283. const queries = new QueryBuilder(db.getDb());
  284. const instance = new CodeGraph(db, queries, resolvedRoot);
  285. // Sync if requested
  286. if (options.sync) {
  287. await instance.sync();
  288. }
  289. return instance;
  290. }
  291. /**
  292. * Rebuild the project's database from scratch and return a fresh, empty
  293. * instance — the "same result as a fresh init" semantics that `codegraph
  294. * index` documents.
  295. *
  296. * Unlike `open()` followed by `clear()`, this DISCARDS the existing
  297. * `.codegraph/codegraph.db` (and its `-wal`/`-shm` sidecars) before
  298. * re-initializing, instead of opening the old database and DELETE-ing every
  299. * row. On a large or pre-fix poisoned index — e.g. an old graph that scanned
  300. * an ignored gitlink corpus (#1065) into ~1.6M nodes with a multi-GB WAL —
  301. * the per-row `nodes_fts` delete-trigger churn blocks the main thread long
  302. * enough to trip the #850 liveness watchdog before indexing even starts, so a
  303. * full re-index could never recover the bad state (#1067). Discarding the
  304. * files is O(1) regardless of size, reclaims the disk, and sidesteps opening
  305. * (and running migrations against) the poisoned database entirely.
  306. */
  307. static async recreate(projectRoot: string): Promise<CodeGraph> {
  308. await initGrammars();
  309. const resolvedRoot = path.resolve(projectRoot);
  310. // Check if initialized — recreate REBUILDS an existing project; it is not a
  311. // first-time `init`.
  312. if (!isInitialized(resolvedRoot)) {
  313. throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
  314. }
  315. const dbPath = getDatabasePath(resolvedRoot);
  316. try {
  317. removeDatabaseFiles(dbPath);
  318. } catch (err) {
  319. // POSIX unlinks an open file fine; this fires mainly on Windows when a
  320. // live daemon/MCP server still holds the database. Turn the raw EBUSY into
  321. // an actionable instruction instead of a generic failure.
  322. const reason = err instanceof Error ? err.message : String(err);
  323. throw new Error(
  324. `Could not rebuild the index — the database file is in use (${reason}). ` +
  325. `Stop any running CodeGraph MCP server/daemon for this project and retry, ` +
  326. `or remove the ${getCodeGraphDir(resolvedRoot)} directory and run "codegraph init".`
  327. );
  328. }
  329. // Re-create an empty, freshly-schema'd database at the same path.
  330. const db = DatabaseConnection.initialize(dbPath);
  331. const queries = new QueryBuilder(db.getDb());
  332. return new CodeGraph(db, queries, resolvedRoot);
  333. }
  334. /**
  335. * Open synchronously (without sync)
  336. */
  337. static openSync(projectRoot: string): CodeGraph {
  338. const resolvedRoot = path.resolve(projectRoot);
  339. // Check if initialized
  340. if (!isInitialized(resolvedRoot)) {
  341. throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
  342. }
  343. // Validate directory structure
  344. const validation = validateDirectory(resolvedRoot);
  345. if (!validation.valid) {
  346. throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
  347. }
  348. // Open database
  349. const dbPath = getDatabasePath(resolvedRoot);
  350. const db = DatabaseConnection.open(dbPath);
  351. const queries = new QueryBuilder(db.getDb());
  352. return new CodeGraph(db, queries, resolvedRoot);
  353. }
  354. /**
  355. * Check if a directory has been initialized as a CodeGraph project
  356. */
  357. static isInitialized(projectRoot: string): boolean {
  358. return isInitialized(path.resolve(projectRoot));
  359. }
  360. /**
  361. * Close the CodeGraph instance and release resources
  362. */
  363. close(): void {
  364. this.unwatch();
  365. // Release file lock if held
  366. this.fileLock.release();
  367. this.db.close();
  368. }
  369. /**
  370. * Get the project root directory
  371. */
  372. getProjectRoot(): string {
  373. return this.projectRoot;
  374. }
  375. // ===========================================================================
  376. // Indexing
  377. // ===========================================================================
  378. /**
  379. * Index all files in the project
  380. *
  381. * Uses a mutex to prevent concurrent indexing operations.
  382. */
  383. async indexAll(options: IndexOptions = {}): Promise<IndexResult> {
  384. return this.indexMutex.withLock(async () => {
  385. try {
  386. this.fileLock.acquire();
  387. } catch {
  388. return { success: false, filesIndexed: 0, filesSkipped: 0, filesErrored: 0, nodesCreated: 0, edgesCreated: 0, errors: [{ message: 'Could not acquire file lock - another process may be indexing', severity: 'error' as const }], durationMs: 0 };
  389. }
  390. // Defer WAL auto-checkpointing for the whole bulk run (#1231): the
  391. // default 1000-page interval re-writes hot pages into the main DB file
  392. // over and over — ~95% of all disk I/O during a bulk index, and a
  393. // 19+min → 45s difference on HDD-class storage. The valve bounds WAL
  394. // growth by backfilling PASSIVEly on a worker thread (never blocking
  395. // the writer or the #850 watchdog heartbeat); runMaintenance below does
  396. // the final fold-up before the interval is restored in the finally.
  397. // Kill switch: CODEGRAPH_NO_WAL_DEFER=1. Non-WAL journal modes (some
  398. // network filesystems) have no WAL to defer — skip.
  399. // Fast-init: on a COMPLETELY fresh DB, trade crash-durability for speed
  400. // during the bulk build (journal in memory, no fsync). Safe because the
  401. // DB is disposable until the index completes — index_state stays
  402. // 'indexing' and a crashed init is re-run from scratch; existing DBs
  403. // (re-index/sync) never take this path. Kill switch:
  404. // CODEGRAPH_NO_FAST_INIT=1 (same pattern as CODEGRAPH_NO_WAL_DEFER).
  405. const freshDb = this.queries.getNodeAndEdgeCount().nodes === 0;
  406. const fastInit = process.env.CODEGRAPH_NO_FAST_INIT !== '1' && freshDb;
  407. if (fastInit) {
  408. try {
  409. this.db.getDb().pragma('journal_mode = MEMORY');
  410. this.db.getDb().pragma('synchronous = OFF');
  411. } catch { /* keep WAL */ }
  412. }
  413. const deferWal = !fastInit && process.env.CODEGRAPH_NO_WAL_DEFER !== '1' && this.db.getJournalMode() === 'wal';
  414. let walValve: WalCheckpointValve | null = null;
  415. let priorAutocheckpoint = 1000;
  416. // Set when the fastInit+pool path below defers autocheckpointing, so the
  417. // finally knows to restore the interval on that path too.
  418. let restoreAutocheckpoint = false;
  419. if (deferWal) {
  420. priorAutocheckpoint = this.db.getWalAutocheckpoint();
  421. this.db.setWalAutocheckpoint(0);
  422. walValve = new WalCheckpointValve(
  423. this.db,
  424. undefined,
  425. undefined,
  426. options.verbose ? (m) => console.log(`[wal-valve] ${m}`) : undefined
  427. );
  428. walValve.start();
  429. }
  430. try {
  431. const before = this.queries.getNodeAndEdgeCount();
  432. // Mark the index as in-flight BEFORE any writes: a run killed
  433. // mid-index (OOM, SIGKILL, the #850 liveness watchdog) leaves this
  434. // marker behind, so `codegraph status` can tell a truncated index
  435. // from a completed one instead of silently serving partial results.
  436. try { this.queries.setMetadata('index_state', 'indexing'); } catch { /* metadata is advisory */ }
  437. // Segment vocabulary starts empty and is repopulated by the node write
  438. // path as every file (re-)indexes below — so a full index is also the
  439. // orphan-cleanup pass for names deleted since the last one.
  440. try { this.queries.clearNameSegmentVocab(); } catch { /* vocab is advisory — never fail an index over it */ }
  441. // Bulk FTS mode for the mass-insert phase: drop the per-row FTS sync
  442. // triggers, rebuild nodes_fts once from the nodes table afterwards.
  443. // Crash inside the window is healed on the next DatabaseConnection.open.
  444. this.db.beginBulkNodeLoad();
  445. let result: IndexResult;
  446. try {
  447. result = await this.orchestrator.indexAll(
  448. options.onProgress,
  449. options.signal,
  450. options.verbose,
  451. walValve ? () => walValve!.backpressure() : undefined,
  452. // Store-writer offload is fresh-DB-only: with any pre-existing
  453. // data the store path must read (existing-file checks, cross-file
  454. // edge snapshots) and delete, which belongs on one thread.
  455. freshDb ? { dbPath: this.db.getPath(), fastInit } : null
  456. );
  457. } finally {
  458. const tFts = Date.now();
  459. this.db.endBulkNodeLoad();
  460. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] fts-rebuild: ${Date.now() - tFts}ms`);
  461. }
  462. // Fold the parse phase's WAL BEFORE the first post-parse reads
  463. // (resolver re-init and resolution both read on the main thread):
  464. // paging a bulk-write-sized WAL there is what blew the #850
  465. // watchdog's 60s window in the #1231 repro. Off-thread + awaited,
  466. // so the event loop keeps turning.
  467. if (walValve) await walValve.foldNow();
  468. // Re-detect frameworks now that the index is populated. The resolver
  469. // is constructed with createResolver() before any files exist, so
  470. // framework resolvers whose detect() consults the indexed file list
  471. // (e.g. UIKit/SwiftUI scanning for imports, swift-objc-bridge looking
  472. // for both Swift and ObjC files) all return false on that initial pass
  473. // and silently drop themselves. Re-initializing here gives them a
  474. // chance to see the actual project before resolution runs.
  475. if (result.success && result.filesIndexed > 0) {
  476. const tReinit = Date.now();
  477. this.resolver.initialize();
  478. // Cross-file finalization (e.g. NestJS RouterModule prefixes). Runs
  479. // before resolution so updated names show up in subsequent reads.
  480. this.resolver.runPostExtract();
  481. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] resolver-reinit: ${Date.now() - tReinit}ms`);
  482. }
  483. // Resolve references to create call/import/extends edges
  484. if (result.success && result.filesIndexed > 0) {
  485. // Get count without loading all refs into memory
  486. const unresolvedCount = this.queries.getUnresolvedReferencesCount();
  487. // Fast-init leaves the DB in memory-journal (rollback) mode, where
  488. // the parallel resolver pool's read connections would contend with
  489. // the main writer's exclusive commits. When the pool will actually
  490. // run (enough pending refs), restore WAL BEFORE resolution so
  491. // readers never block the writer; otherwise stay in the fast mode
  492. // until the finally — sequential resolution has no readers.
  493. if (fastInit && unresolvedCount >= minRefsForPool()) {
  494. try {
  495. this.db.getDb().pragma('synchronous = NORMAL');
  496. this.db.getDb().pragma('journal_mode = WAL');
  497. // Defer auto-checkpointing for the resolution phase, same
  498. // rationale as the deferWal path above: at the default 1000-page
  499. // interval, the persist loop's edge inserts + ref deletes make
  500. // SQLite re-write hot B-tree pages into the main DB file inline
  501. // on the writer over and over (#1231's pathology — measured as
  502. // ~58% of the resolution phase on a 255k-ref repo). The valve
  503. // bounds WAL growth off-thread; runMaintenance does the final
  504. // fold and the finally restores the interval.
  505. priorAutocheckpoint = this.db.getWalAutocheckpoint();
  506. this.db.setWalAutocheckpoint(0);
  507. restoreAutocheckpoint = true;
  508. walValve = new WalCheckpointValve(
  509. this.db,
  510. undefined,
  511. undefined,
  512. options.verbose ? (m) => console.log(`[wal-valve] ${m}`) : undefined
  513. );
  514. walValve.start();
  515. } catch { /* keep current mode; resolution still works sequentially */ }
  516. }
  517. options.onProgress?.({
  518. phase: 'resolving',
  519. current: 0,
  520. total: unresolvedCount,
  521. });
  522. const tResolve = Date.now();
  523. await this.resolveReferencesBatched(
  524. (current, total) => {
  525. options.onProgress?.({
  526. phase: 'resolving',
  527. current,
  528. total,
  529. });
  530. },
  531. (done, totalPasses) => {
  532. options.onProgress?.({
  533. phase: 'linking',
  534. current: done,
  535. total: totalPasses,
  536. });
  537. }
  538. );
  539. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] resolution: ${Date.now() - tResolve}ms`);
  540. // Second pass: chained calls whose method lives on a supertype the
  541. // receiver conforms to (protocol-extension / inherited / default-
  542. // interface). Needs the implements/extends edges the main pass just
  543. // built, so it runs after resolution (#750).
  544. const tChained = Date.now();
  545. await this.resolver.resolveChainedCallsViaConformance();
  546. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[synth-timing] chainedConformance: ${Date.now() - tChained}ms`);
  547. // Same lifecycle for `this.<member>` callback registrations whose
  548. // member is inherited from a supertype (#808).
  549. const tDeferred = Date.now();
  550. await this.resolver.resolveDeferredThisMemberRefs();
  551. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[synth-timing] deferredThisMember: ${Date.now() - tDeferred}ms`);
  552. }
  553. // Refresh planner stats + checkpoint the WAL after bulk writes.
  554. // Off-thread (worker connection): on a multi-GB index this is minutes
  555. // of IO, and inline it starved the #850 watchdog AFTER a fully
  556. // successful index. Never load-bearing for correctness.
  557. if (result.success && result.filesIndexed > 0) {
  558. const tMaint = Date.now();
  559. // Quiesce the valve first so its in-flight checkpoint and the
  560. // maintenance checkpoint don't contend for the checkpointer lock
  561. // (the loser would silently no-op and leave the WAL unfolded).
  562. if (walValve) { walValve.stop(); await walValve.drain(); }
  563. await this.db.runMaintenance();
  564. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] maintenance: ${Date.now() - tMaint}ms`);
  565. }
  566. // The orchestrator only sees extraction-phase counts; resolution and
  567. // synthesizer edges (often >50% of the graph on JVM repos) come later.
  568. // Recompute against the DB so the CLI summary reports the true totals.
  569. if (result.success && result.filesIndexed > 0) {
  570. const tCount = Date.now();
  571. const after = this.queries.getNodeAndEdgeCount();
  572. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] count-recompute: ${Date.now() - tCount}ms`);
  573. result.nodesCreated = after.nodes - before.nodes;
  574. result.edgesCreated = after.edges - before.edges;
  575. }
  576. // Stamp the index with the engine that built it, so `codegraph status`
  577. // and `codegraph upgrade` can recommend a re-index when the running
  578. // engine produces richer extraction than the one on disk. Only on a
  579. // real full index — a sync touches a subset, so it must NOT advance the
  580. // extraction stamp (the bulk would still be stale). See extraction-version.ts.
  581. if (result.success && result.filesIndexed > 0) {
  582. try {
  583. this.queries.setMetadata('indexed_with_version', CodeGraphPackageVersion);
  584. this.queries.setMetadata('indexed_with_extraction_version', String(EXTRACTION_VERSION));
  585. } catch { /* metadata is advisory — never fail an index over it */ }
  586. }
  587. // Reconcile the scan's ground truth against what the pipeline
  588. // accounted for. A shortfall means files were silently dropped
  589. // (observed in the wild: a run under heavy load came up 37 files
  590. // short with no error) — record it and tell the user, don't let the
  591. // index pass as complete.
  592. try {
  593. if (!result.success) {
  594. this.queries.setMetadata('index_state', 'failed');
  595. } else {
  596. const accounted = result.filesIndexed + result.filesSkipped + result.filesErrored;
  597. const discovered = result.filesDiscovered;
  598. const shortfall = discovered !== undefined ? discovered - accounted : 0;
  599. if (discovered !== undefined && shortfall > 0) {
  600. this.queries.setMetadata('index_state', 'partial');
  601. this.queries.setMetadata('index_files_discovered', String(discovered));
  602. this.queries.setMetadata('index_files_accounted', String(accounted));
  603. result.errors.push({
  604. message: `Index is missing ${shortfall} of ${discovered} discovered files (indexed ${result.filesIndexed}, skipped ${result.filesSkipped}, errored ${result.filesErrored}). The index is PARTIAL — re-run \`codegraph index\`.`,
  605. severity: 'warning',
  606. code: 'index_partial',
  607. });
  608. } else {
  609. this.queries.setMetadata('index_state', 'complete');
  610. if (discovered !== undefined) {
  611. this.queries.setMetadata('index_files_discovered', String(discovered));
  612. this.queries.setMetadata('index_files_accounted', String(accounted));
  613. }
  614. }
  615. }
  616. } catch { /* metadata is advisory — never fail an index over it */ }
  617. return result;
  618. } finally {
  619. // Restore the auto-checkpoint interval AFTER the fold-up above so the
  620. // next ordinary write doesn't inherit a giant inline checkpoint. On
  621. // the error path the WAL may still be large; correctness is unchanged
  622. // (SQLite replays the WAL on the next open) and the follow-up write
  623. // that folds it is the known cost of a failed run.
  624. if (walValve) { walValve.stop(); await walValve.drain(); }
  625. if (deferWal || restoreAutocheckpoint) {
  626. try { this.db.setWalAutocheckpoint(priorAutocheckpoint); } catch { /* connection may be closing */ }
  627. }
  628. if (fastInit) {
  629. // Back to the durable defaults; journal_mode=WAL folds the MEMORY
  630. // journal state into a normal WAL-mode database file.
  631. try {
  632. this.db.getDb().pragma('synchronous = NORMAL');
  633. this.db.getDb().pragma('journal_mode = WAL');
  634. } catch { /* connection may be closing */ }
  635. }
  636. this.fileLock.release();
  637. }
  638. });
  639. }
  640. /**
  641. * Index specific files
  642. *
  643. * Uses a mutex to prevent concurrent indexing operations.
  644. */
  645. async indexFiles(filePaths: string[]): Promise<IndexResult> {
  646. return this.indexMutex.withLock(async () => {
  647. try {
  648. this.fileLock.acquire();
  649. } catch {
  650. return { success: false, filesIndexed: 0, filesSkipped: 0, filesErrored: 0, nodesCreated: 0, edgesCreated: 0, errors: [{ message: 'Could not acquire file lock - another process may be indexing', severity: 'error' as const }], durationMs: 0 };
  651. }
  652. try {
  653. return this.orchestrator.indexFiles(filePaths);
  654. } finally {
  655. this.fileLock.release();
  656. }
  657. });
  658. }
  659. /**
  660. * Sync with current file state (incremental update)
  661. *
  662. * Uses a mutex to prevent concurrent indexing operations.
  663. */
  664. async sync(options: IndexOptions = {}): Promise<SyncResult> {
  665. return this.indexMutex.withLock(async () => {
  666. try {
  667. this.fileLock.acquire();
  668. } catch {
  669. return { filesChecked: 0, filesAdded: 0, filesModified: 0, filesRemoved: 0, nodesUpdated: 0, durationMs: 0 };
  670. }
  671. // Defer WAL auto-checkpointing for the whole incremental run, exactly
  672. // as indexAll does for the bulk path (#1231): sync's store loop and its
  673. // resolution passes churn the same FTS + secondary-index hot pages, and
  674. // at the default 1000-page cadence the inline checkpoints re-write them
  675. // over and over — on HDD-class storage a 7-file sync took 2 minutes at
  676. // 0-2% CPU (#1248). The cost scales with the EXISTING database size,
  677. // not the change size, so small syncs on big indexes hurt most. The
  678. // valve bounds WAL growth off-thread; runMaintenance at the end does
  679. // the final fold-up before the interval is restored in the finally.
  680. // Same kill switch as indexAll: CODEGRAPH_NO_WAL_DEFER=1. Idle valve
  681. // cost is one timer, so watcher-frequency syncs stay cheap.
  682. const deferWal = process.env.CODEGRAPH_NO_WAL_DEFER !== '1' && this.db.getJournalMode() === 'wal';
  683. let walValve: WalCheckpointValve | null = null;
  684. let priorAutocheckpoint = 1000;
  685. if (deferWal) {
  686. priorAutocheckpoint = this.db.getWalAutocheckpoint();
  687. this.db.setWalAutocheckpoint(0);
  688. walValve = new WalCheckpointValve(
  689. this.db,
  690. undefined,
  691. undefined,
  692. options.verbose ? (m) => console.log(`[wal-valve] ${m}`) : undefined
  693. );
  694. walValve.start();
  695. }
  696. try {
  697. // Captured BEFORE the sync runs: the sync's own incremental writes
  698. // populate vocab rows for the files it touches, so an end-of-sync
  699. // emptiness check would see "non-empty" and skip the backfill forever,
  700. // leaving every unchanged file's names unsegmented.
  701. const vocabWasEmpty = (() => {
  702. try { return this.queries.isNameSegmentVocabEmpty(); } catch { return false; }
  703. })();
  704. const result = await this.orchestrator.sync(options.onProgress);
  705. // Fold the store phase's WAL BEFORE the post-store reads below
  706. // (resolution reads on the main thread) — same rationale as
  707. // indexAll's fold between store and resolution.
  708. if (walValve) await walValve.foldNow();
  709. // Cross-file finalization (e.g. NestJS RouterModule prefixes). Run on
  710. // every sync that touched files so edits to `app.module.ts` propagate
  711. // to controllers in unchanged files. The pass is idempotent and cheap
  712. // (regex over *.module.ts only).
  713. if (result.filesAdded > 0 || result.filesModified > 0) {
  714. this.resolver.runPostExtract();
  715. } else if (result.filesRemoved > 0) {
  716. // A pure-removal sync still resolves refs below — the deletion path
  717. // resurrects the removed file's incoming edges as pending refs
  718. // (#1240 removal case) and the orphan sweep consumes them. In a
  719. // long-lived process (daemon) the resolver's name caches were
  720. // warmed against the pre-removal graph; drop them so resolution
  721. // sees the post-removal state. (runPostExtract above clears caches
  722. // itself, so the changed-files branch is already covered.)
  723. this.resolver.clearCaches();
  724. }
  725. // Resolve references if files were updated
  726. const filesChanged = result.filesAdded > 0 || result.filesModified > 0;
  727. if (filesChanged) {
  728. if (result.changedFilePaths) {
  729. // Scope resolution to changed files (git fast path — bounded set)
  730. const tRefLoad = Date.now();
  731. const unresolvedRefs = this.queries.getUnresolvedReferencesByFiles(result.changedFilePaths);
  732. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] sync-ref-load: ${Date.now() - tRefLoad}ms (${unresolvedRefs.length} refs)`);
  733. options.onProgress?.({
  734. phase: 'resolving',
  735. current: 0,
  736. total: unresolvedRefs.length,
  737. });
  738. this.resolver.resolveAndPersist(unresolvedRefs, (current, total) => {
  739. options.onProgress?.({
  740. phase: 'resolving',
  741. current,
  742. total,
  743. });
  744. });
  745. // Retry previously-failed refs the changed files may now satisfy
  746. // (#1240). Scoped resolution above only re-resolves refs FROM the
  747. // changed files — but when a changed file gains an export/symbol,
  748. // refs in UNCHANGED files that failed against the old graph can
  749. // now resolve, and nothing else ever revisits them (their rows
  750. // were parked as status='failed' by an earlier completed pass).
  751. // Look them up by the symbol names the changed files now carry
  752. // and re-resolve just that set. On a sync where no failed ref
  753. // matches, this is one indexed lookup.
  754. const tRetry = Date.now();
  755. const retryable = this.queries.getRetryableFailedReferences(
  756. this.queries.getNodeNamesByFiles(result.changedFilePaths)
  757. );
  758. if (retryable.length > 0) {
  759. options.onProgress?.({
  760. phase: 'resolving',
  761. current: 0,
  762. total: retryable.length,
  763. });
  764. await this.resolver.resolveAndPersistListYielding(retryable);
  765. options.onProgress?.({
  766. phase: 'resolving',
  767. current: retryable.length,
  768. total: retryable.length,
  769. });
  770. }
  771. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] sync-failed-ref-retry: ${Date.now() - tRetry}ms (${retryable.length} refs)`);
  772. } else {
  773. // No git info — use batched resolution to avoid OOM
  774. const unresolvedCount = this.queries.getUnresolvedReferencesCount();
  775. options.onProgress?.({
  776. phase: 'resolving',
  777. current: 0,
  778. total: unresolvedCount,
  779. });
  780. await this.resolveReferencesBatched(
  781. (current, total) => {
  782. options.onProgress?.({
  783. phase: 'resolving',
  784. current,
  785. total,
  786. });
  787. },
  788. (done, totalPasses) => {
  789. options.onProgress?.({
  790. phase: 'linking',
  791. current: done,
  792. total: totalPasses,
  793. });
  794. }
  795. );
  796. }
  797. }
  798. // Orphan sweep (#1187). A resolution pass that dies mid-run — the #850
  799. // daemon liveness watchdog's SIGKILL (#1122), Ctrl-C, a crash — leaves
  800. // the refs it never reached in unresolved_refs, and the git-scoped fast
  801. // path above never revisits them (it reads only the changed files'
  802. // rows). Those files' call edges were then missing PERMANENTLY, with
  803. // nothing to see except a too-small blast radius, until a full
  804. // re-index. A completed pass takes every row it processed out of the
  805. // PENDING set (resolved rows are deleted, unresolvable ones parked as
  806. // status='failed' for the #1240 retry above), so any pending row now
  807. // is such an orphan — or a row from an older engine's scoped pass.
  808. // Grind them down with the batched resolver; this also makes a bare
  809. // `codegraph sync` the recovery command for a wedged index. On a
  810. // healthy index this is one COUNT query.
  811. const orphanCount = this.queries.getUnresolvedReferencesCount();
  812. if (orphanCount > 0) {
  813. options.onProgress?.({
  814. phase: 'resolving',
  815. current: 0,
  816. total: orphanCount,
  817. });
  818. await this.resolveReferencesBatched(
  819. (current, total) => {
  820. options.onProgress?.({
  821. phase: 'resolving',
  822. current,
  823. total,
  824. });
  825. },
  826. (done, totalPasses) => {
  827. options.onProgress?.({
  828. phase: 'linking',
  829. current: done,
  830. total: totalPasses,
  831. });
  832. }
  833. );
  834. }
  835. if (filesChanged || orphanCount > 0) {
  836. // Second pass: chained calls whose method lives on a supertype the
  837. // receiver conforms to (protocol-extension / inherited). Needs the
  838. // implements/extends edges built above (#750).
  839. await this.resolver.resolveChainedCallsViaConformance();
  840. // Same lifecycle for `this.<member>` callback registrations whose
  841. // member is inherited from a supertype (#808).
  842. await this.resolver.resolveDeferredThisMemberRefs();
  843. }
  844. // Refresh planner stats + checkpoint the WAL after bulk writes.
  845. // Off-thread — see indexAll's call site.
  846. if (filesChanged || result.filesRemoved > 0 || orphanCount > 0) {
  847. await this.db.runMaintenance();
  848. }
  849. // Heal the segment vocabulary on indexes built before the table
  850. // existed (upgrade path): incremental writes above only cover changed
  851. // files, so a vocab that was empty when this sync STARTED means the
  852. // bulk was never segmented — backfill it (INSERT OR IGNORE, so the
  853. // rows the sync just wrote are fine). Batched + yielding — sync can
  854. // run on the daemon's liveness-watchdog thread (#850/#1091).
  855. try {
  856. if (vocabWasEmpty && this.queries.getNodeAndEdgeCount().nodes > 0) {
  857. await this.rebuildNameSegmentVocab();
  858. }
  859. } catch { /* vocab is advisory — never fail a sync over it */ }
  860. return result;
  861. } finally {
  862. // Mirror indexAll's teardown: stop the valve, then restore the
  863. // auto-checkpoint interval (runMaintenance above already folded the
  864. // WAL on the success path; on the error path SQLite replays it on
  865. // the next open).
  866. if (walValve) { walValve.stop(); await walValve.drain(); }
  867. if (deferWal) {
  868. try { this.db.setWalAutocheckpoint(priorAutocheckpoint); } catch { /* connection may be closing */ }
  869. }
  870. this.fileLock.release();
  871. }
  872. });
  873. }
  874. /**
  875. * Check if an indexing operation is currently in progress
  876. */
  877. isIndexing(): boolean {
  878. return this.indexMutex.isLocked();
  879. }
  880. // ===========================================================================
  881. // File Watching
  882. // ===========================================================================
  883. /**
  884. * Start watching for file changes and auto-syncing.
  885. *
  886. * Uses native OS file events (FSEvents on macOS, inotify on Linux 19+,
  887. * ReadDirectoryChangesW on Windows) with debouncing to avoid thrashing.
  888. *
  889. * @param options - Watch options (debounce delay, callbacks)
  890. * @returns true if watching started successfully
  891. */
  892. watch(options: WatchOptions = {}): boolean {
  893. if (this.watcher?.isActive()) return true;
  894. this.watcher = new FileWatcher(
  895. this.projectRoot,
  896. async () => {
  897. const result = await this.sync();
  898. // sync() returns this exact zero-shape iff it failed to acquire the
  899. // file lock (a real empty sync always has filesChecked > 0 because
  900. // scanDirectory ran). Surface that to the watcher as a typed error
  901. // so it keeps pendingFiles + reschedules instead of clearing them
  902. // (#449).
  903. if (result.filesChecked === 0 && result.durationMs === 0) {
  904. throw new LockUnavailableError();
  905. }
  906. const filesChanged = result.filesAdded + result.filesModified + result.filesRemoved;
  907. return { filesChanged, durationMs: result.durationMs };
  908. },
  909. options
  910. );
  911. return this.watcher.start();
  912. }
  913. /**
  914. * Stop watching for file changes.
  915. */
  916. unwatch(): void {
  917. if (this.watcher) {
  918. this.watcher.stop();
  919. this.watcher = null;
  920. }
  921. }
  922. /**
  923. * Check if the file watcher is active.
  924. */
  925. isWatching(): boolean {
  926. return this.watcher?.isActive() ?? false;
  927. }
  928. /**
  929. * True once live watching has permanently degraded (OS watch-resource
  930. * exhaustion, or a write lock held past the retry budget) and auto-sync is
  931. * disabled until the next {@link watch} call. Distinct from `!isWatching()`:
  932. * a stopped/never-started watcher is inactive but NOT degraded. MCP tools use
  933. * this to surface a whole-index "results may be stale" notice, since
  934. * `getPendingFiles()` goes empty once watching stops (#876).
  935. */
  936. isWatcherDegraded(): boolean {
  937. return this.watcher?.isDegraded() ?? false;
  938. }
  939. /** The reason live watching degraded, or null if it is healthy (#876). */
  940. getWatcherDegradedReason(): string | null {
  941. return this.watcher?.getDegradedReason() ?? null;
  942. }
  943. /**
  944. * Files seen by the file watcher since the last successful sync —
  945. * the per-file "stale" signal MCP tools attach to responses so an agent
  946. * can fall back to {@link Read} for just the affected file without
  947. * waiting for a debounced sync to complete (issue #403).
  948. *
  949. * Returns an empty list when the watcher isn't active, or no events have
  950. * arrived. Each entry includes `firstSeenMs` and `lastSeenMs` (wall-clock
  951. * `Date.now()` values) so callers can render "edited Nms ago", plus an
  952. * `indexing` flag indicating whether the in-flight sync (if any) will
  953. * absorb that file.
  954. */
  955. getPendingFiles(): PendingFile[] {
  956. return this.watcher?.getPendingFiles() ?? [];
  957. }
  958. /**
  959. * Resolves once the file watcher has installed its watch set. Useful for
  960. * tests that need a deterministic boundary before asserting on
  961. * `getPendingFiles()`. Resolves immediately when no watcher is active.
  962. */
  963. waitUntilWatcherReady(timeoutMs?: number): Promise<void> {
  964. return this.watcher ? this.watcher.waitUntilReady(timeoutMs) : Promise.resolve();
  965. }
  966. /**
  967. * Get files that have changed since last index
  968. */
  969. getChangedFiles(): { added: string[]; modified: string[]; removed: string[] } {
  970. return this.orchestrator.getChangedFiles();
  971. }
  972. /**
  973. * Most recent index timestamp (ms since epoch) across all tracked files, or
  974. * null when nothing is indexed yet. Lets library consumers check index
  975. * freshness without shelling out to `codegraph status --json`. (#329)
  976. */
  977. getLastIndexedAt(): number | null {
  978. return this.queries.getLastIndexedAt();
  979. }
  980. /**
  981. * Completeness of the last full index run. `'complete'` is the only good
  982. * state. `'indexing'` after the fact means a run was killed mid-index (OOM,
  983. * SIGKILL, liveness watchdog) and the on-disk index is truncated;
  984. * `'partial'` means the run finished but silently dropped files
  985. * (discovered > indexed+skipped+errored); `'failed'` means it reported
  986. * failure. `null` = index predates this marker. Surfaced by
  987. * `codegraph status`.
  988. */
  989. getIndexState(): 'indexing' | 'complete' | 'partial' | 'failed' | null {
  990. const raw = this.queries.getMetadata('index_state');
  991. return raw === 'indexing' || raw === 'complete' || raw === 'partial' || raw === 'failed'
  992. ? raw
  993. : null;
  994. }
  995. /**
  996. * Which engine built the current index: the package version + extraction
  997. * version stamped at the last full `indexAll`. Either field is null for an
  998. * index built before stamping existed (treated as stale). See
  999. * `extraction-version.ts` and `isIndexStale()`.
  1000. */
  1001. getIndexBuildInfo(): { version: string | null; extractionVersion: number | null } {
  1002. const version = this.queries.getMetadata('indexed_with_version');
  1003. const ev = this.queries.getMetadata('indexed_with_extraction_version');
  1004. const parsed = ev != null ? parseInt(ev, 10) : NaN;
  1005. return { version, extractionVersion: Number.isFinite(parsed) ? parsed : null };
  1006. }
  1007. /**
  1008. * True when the on-disk index was built by an engine whose extraction is
  1009. * older than the one now running — i.e. a re-index would add data a migration
  1010. * can't backfill. False when there's no index yet (nothing to refresh) or the
  1011. * stamp is current. This is the signal behind `codegraph status`'s re-index
  1012. * hint and `codegraph upgrade`'s reminder.
  1013. */
  1014. isIndexStale(): boolean {
  1015. if (this.queries.getLastIndexedAt() == null) return false;
  1016. const { extractionVersion } = this.getIndexBuildInfo();
  1017. return extractionVersion == null || extractionVersion < EXTRACTION_VERSION;
  1018. }
  1019. /**
  1020. * Extract nodes and edges from source code (without storing)
  1021. */
  1022. extractFromSource(filePath: string, source: string): ExtractionResult {
  1023. return extractFromSource(filePath, source);
  1024. }
  1025. // ===========================================================================
  1026. // Reference Resolution
  1027. // ===========================================================================
  1028. /**
  1029. * Resolve unresolved references and create edges
  1030. *
  1031. * This method takes unresolved references from extraction and attempts
  1032. * to resolve them using multiple strategies:
  1033. * - Framework-specific patterns (React, Express, Laravel)
  1034. * - Import-based resolution
  1035. * - Name-based symbol matching
  1036. */
  1037. resolveReferences(onProgress?: (current: number, total: number) => void): ResolutionResult {
  1038. // Get all unresolved references from the database
  1039. const unresolvedRefs = this.queries.getUnresolvedReferences();
  1040. return this.resolver.resolveAndPersist(unresolvedRefs, onProgress);
  1041. }
  1042. /**
  1043. * Resolve references in batches to keep memory bounded on large codebases.
  1044. * Processes chunks of unresolved refs, persisting results after each batch.
  1045. */
  1046. async resolveReferencesBatched(
  1047. onProgress?: (current: number, total: number) => void,
  1048. onSynthesisProgress?: (done: number, total: number) => void
  1049. ): Promise<ResolutionResult> {
  1050. return this.resolver.resolveAndPersistBatched(onProgress, undefined, onSynthesisProgress, {
  1051. dbPath: this.db.getPath(),
  1052. });
  1053. }
  1054. /**
  1055. * References extracted but never attempted by a resolution pass. Zero on a
  1056. * healthy index — a completed pass consumes every pending row (resolving it
  1057. * or parking it as failed, #1240). Non-zero at rest means a pass was
  1058. * interrupted mid-run (killed indexer, crash — #1187), so some files' call
  1059. * edges are missing; the next `sync` sweeps them.
  1060. */
  1061. getPendingReferenceCount(): number {
  1062. return this.queries.getUnresolvedReferencesCount();
  1063. }
  1064. /**
  1065. * Get detected frameworks in the project
  1066. */
  1067. getDetectedFrameworks(): string[] {
  1068. return this.resolver.getDetectedFrameworks();
  1069. }
  1070. /**
  1071. * Re-initialize the resolver (useful after adding new files)
  1072. */
  1073. reinitializeResolver(): void {
  1074. this.resolver.initialize();
  1075. }
  1076. // ===========================================================================
  1077. // Graph Statistics
  1078. // ===========================================================================
  1079. /**
  1080. * Get statistics about the knowledge graph
  1081. */
  1082. getStats(): GraphStats {
  1083. const stats = this.queries.getStats();
  1084. stats.dbSizeBytes = this.db.getSize();
  1085. return stats;
  1086. }
  1087. /**
  1088. * Active SQLite backend for this project's connection (`node-sqlite` — Node's
  1089. * built-in real-SQLite module). Surfaced via `codegraph status` and the
  1090. * `codegraph_status` MCP tool alongside the effective journal mode.
  1091. */
  1092. getBackend(): import('./db').SqliteBackend {
  1093. return this.db.getBackend();
  1094. }
  1095. /**
  1096. * The journal mode actually in effect ('wal', 'delete', …). 'wal' means
  1097. * readers never block on a concurrent writer; anything else means they can,
  1098. * which is the precondition for the "database is locked" failures in issue
  1099. * #238. Surfaced via `codegraph status` and the `codegraph_status` MCP tool.
  1100. */
  1101. getJournalMode(): string {
  1102. return this.db.getJournalMode();
  1103. }
  1104. // ===========================================================================
  1105. // Node Operations
  1106. // ===========================================================================
  1107. /**
  1108. * Get a node by ID
  1109. */
  1110. getNode(id: string): Node | null {
  1111. return this.queries.getNodeById(id);
  1112. }
  1113. /**
  1114. * Get all nodes in a file
  1115. */
  1116. getNodesInFile(filePath: string): Node[] {
  1117. return this.queries.getNodesByFile(filePath);
  1118. }
  1119. /**
  1120. * Get all nodes of a specific kind
  1121. */
  1122. getNodesByKind(kind: Node['kind']): Node[] {
  1123. return this.queries.getNodesByKind(kind);
  1124. }
  1125. /**
  1126. * Get ALL nodes with an exact name (direct index lookup, not FTS-ranked/capped).
  1127. * Used to enumerate every overload of a heavily-overloaded name so the specific
  1128. * definition the caller wants is never dropped below a search cut.
  1129. */
  1130. getNodesByName(name: string): Node[] {
  1131. return this.queries.getNodesByName(name);
  1132. }
  1133. /** Nodes whose name starts with `prefix` (index range scan, capped). */
  1134. getNodesByNamePrefix(prefix: string, limit = 20): Node[] {
  1135. return this.queries.getNodesByNamePrefix(prefix, limit);
  1136. }
  1137. /**
  1138. * Nodes whose name CONTAINS `substring` (LIKE scan, ASCII-case-insensitive,
  1139. * shortest-first). The camel-infix lookup FTS can't do — `profileInfo`
  1140. * inside `getProfileInfoV2` is one FTS token (#1196).
  1141. */
  1142. getNodesByNameSubstring(
  1143. substring: string,
  1144. options: { kinds?: NodeKind[]; limit?: number; excludePrefix?: boolean } = {}
  1145. ): Node[] {
  1146. return this.queries
  1147. .findNodesByNameSubstring(substring, options)
  1148. .map((r) => r.node);
  1149. }
  1150. /**
  1151. * Search nodes by text
  1152. */
  1153. searchNodes(query: string, options?: SearchOptions): SearchResult[] {
  1154. return this.queries.searchNodes(query, options);
  1155. }
  1156. /**
  1157. * Graph-derived prompt matching for the front-load hook's MEDIUM tier:
  1158. * which indexed symbols do these prose words name? "state machine des
  1159. * commandes" → `OrderStateMachine`, in any human language whose technical
  1160. * nouns are Latin script — no keyword list involved.
  1161. *
  1162. * Precision comes from the repo's own naming statistics, not vocabulary:
  1163. * - CO-OCCURRENCE: ≥2 words that are segments of the SAME name ("state" +
  1164. * "machine" → OrderStateMachine) is strong evidence and always qualifies.
  1165. * - RARITY: a single matched word qualifies only when its segment is
  1166. * discriminative here (≤ {@link SEGMENT_RARITY_CEILING} distinct names) —
  1167. * "checkout" in a shop backend yes, "state" in a react app no.
  1168. * Every candidate is re-verified against `nodes` before being returned
  1169. * (vocab rows are proposals; deletions leave orphans by design), so a
  1170. * returned symbol is guaranteed to exist right now.
  1171. */
  1172. getSegmentMatches(words: string[], limit: number = 6): SegmentMatch[] {
  1173. if (words.length === 0) return [];
  1174. // Variant → original word (plural folding), for coverage accounting.
  1175. const variantToWord = new Map<string, string>();
  1176. for (const word of words) {
  1177. for (const variant of segmentLookupVariants(word)) {
  1178. if (!variantToWord.has(variant)) variantToWord.set(variant, word);
  1179. }
  1180. }
  1181. const variants = [...variantToWord.keys()];
  1182. // Tier A: co-occurrence. The SQL folds variants back to their original
  1183. // word (#1146), so minWords=2 means two distinct PROMPT WORDS — a name
  1184. // matching both `service` and `services` can't tie with (or crowd past
  1185. // the LIMIT) a genuine two-word match. The JS re-check below recomputes
  1186. // the fold from live segments as the honesty layer.
  1187. const variantPairs = [...variantToWord.entries()].map(([segment, word]) => ({ segment, word }));
  1188. const candidates: Array<{ name: string; matchedWords: Set<string> }> = [];
  1189. for (const hit of this.queries.getSegmentCoOccurrence(variantPairs, 2, 24)) {
  1190. const matched = this.wordsMatchingName(hit.name, variantToWord);
  1191. if (matched.size >= 2) candidates.push({ name: hit.name, matchedWords: matched });
  1192. }
  1193. // Tier B: single rare word. Only when co-occurrence found nothing — a
  1194. // co-occurring name is categorically stronger evidence — and under
  1195. // stricter rules, because one word is thin: the word must be ≥5 chars
  1196. // (measured FPs: "this", "typo"); the segment must appear in AT LEAST TWO
  1197. // names (a concept the codebase is about clusters across names —
  1198. // CheckoutService/CheckoutController — while a prose coincidence is a
  1199. // singleton: measured FP "deploy to PRODUCTION" → the one name
  1200. // matchesNonProductionDir); and the candidate name must have ≥2 segments
  1201. // (a bare common verb matching a bare function name — "write" → `write` —
  1202. // is prose coincidence, not the user naming a symbol).
  1203. if (candidates.length === 0) {
  1204. const singleWordVariants = variants.filter((v) => variantToWord.get(v)!.length >= 5);
  1205. const counts = this.queries.getSegmentNameCounts(singleWordVariants);
  1206. const rare = [...counts.entries()]
  1207. .filter(([, n]) => n >= 2 && n <= CodeGraph.SEGMENT_RARITY_CEILING)
  1208. .sort((a, b) => a[1] - b[1])
  1209. .slice(0, 2);
  1210. for (const [variant] of rare) {
  1211. const word = variantToWord.get(variant)!;
  1212. for (const name of this.queries.getNamesForSegment(variant, 12)) {
  1213. if (splitIdentifierSegments(name).length < 2) continue;
  1214. candidates.push({ name, matchedWords: new Set([word]) });
  1215. }
  1216. }
  1217. }
  1218. // Verify against nodes (the honesty gate) and pick a representative
  1219. // definition per name. A name whose only nodes are file/import kind has
  1220. // no real definition to point at — surfacing the import statement instead
  1221. // reads as a matched symbol but isn't one (#1144) — so it's skipped, the
  1222. // same way an orphaned vocab row is. (Import names no longer enter the
  1223. // vocab at write time, but rows written before that exclusion persist
  1224. // until the next full index.)
  1225. const out: SegmentMatch[] = [];
  1226. const seen = new Set<string>();
  1227. candidates.sort((a, b) => b.matchedWords.size - a.matchedWords.size || a.name.length - b.name.length);
  1228. for (const candidate of candidates) {
  1229. if (out.length >= limit) break;
  1230. if (seen.has(candidate.name)) continue;
  1231. seen.add(candidate.name);
  1232. const nodes = this.queries.getNodesByName(candidate.name);
  1233. if (nodes.length === 0) continue; // orphaned vocab row — name no longer exists
  1234. const rep = nodes.find((n) => n.kind !== 'file' && n.kind !== 'import');
  1235. if (!rep) continue; // no real definition — don't surface an import/file as one
  1236. out.push({
  1237. name: candidate.name,
  1238. kind: rep.kind,
  1239. filePath: rep.filePath,
  1240. startLine: rep.startLine ?? 0,
  1241. matchedWords: [...candidate.matchedWords].sort(),
  1242. });
  1243. }
  1244. return out;
  1245. }
  1246. /** A single word ("state") can match hundreds of names in a big repo — that
  1247. * is noise, not signal. Ceiling for the single-word tier; co-occurrence is
  1248. * exempt because two words on one name is already discriminative. */
  1249. private static readonly SEGMENT_RARITY_CEILING = 25;
  1250. /** Which of the prompt's original words match `name`'s segments (via
  1251. * variants). Segments are recomputed in JS — a name-keyed vocab lookup
  1252. * would scan the (segment, name) primary key. */
  1253. private wordsMatchingName(name: string, variantToWord: Map<string, string>): Set<string> {
  1254. const segments = new Set(splitIdentifierSegments(name));
  1255. const matched = new Set<string>();
  1256. for (const [variant, word] of variantToWord) {
  1257. if (segments.has(variant)) matched.add(word);
  1258. }
  1259. return matched;
  1260. }
  1261. /**
  1262. * One-shot upgrade heal for callers that open the graph WITHOUT syncing —
  1263. * concretely the prompt hook, whose MEDIUM tier reads the segment
  1264. * vocabulary: a database migrated from before the vocab table existed
  1265. * starts with it empty, and the only other backfill lives inside `sync()`,
  1266. * which such callers never run (#1142). Returns true when the vocab is
  1267. * usable (already populated — the overwhelmingly common one-SELECT case —
  1268. * or healed here); false when it isn't (empty graph, or another process
  1269. * holds the index lock — that process's own sync heals it).
  1270. */
  1271. async healSegmentVocabIfEmpty(): Promise<boolean> {
  1272. const empty = (() => {
  1273. try { return this.queries.isNameSegmentVocabEmpty(); } catch { return false; }
  1274. })();
  1275. if (!empty) return true;
  1276. if (this.queries.getNodeAndEdgeCount().nodes === 0) return false;
  1277. return this.indexMutex.withLock(async () => {
  1278. try {
  1279. this.fileLock.acquire();
  1280. } catch {
  1281. return false; // an index/sync is running — it backfills the vocab itself
  1282. }
  1283. try {
  1284. if (!this.queries.isNameSegmentVocabEmpty()) return true; // raced: healed meanwhile
  1285. await this.rebuildNameSegmentVocab();
  1286. return true;
  1287. } finally {
  1288. this.fileLock.release();
  1289. }
  1290. });
  1291. }
  1292. /**
  1293. * Rebuild the segment vocabulary from the current graph, batched and
  1294. * yielding — the upgrade-heal path for indexes built before the vocab table
  1295. * existed. Runs inside the index mutex/lock (sync and
  1296. * healSegmentVocabIfEmpty hold them).
  1297. */
  1298. private async rebuildNameSegmentVocab(): Promise<void> {
  1299. const maybeYield = createYielder();
  1300. const BATCH = 2000;
  1301. for (let offset = 0; ; offset += BATCH) {
  1302. const names = this.queries.getDistinctNodeNames(BATCH, offset);
  1303. if (names.length === 0) break;
  1304. this.queries.insertNameSegmentsBatch(names);
  1305. await maybeYield();
  1306. }
  1307. }
  1308. /**
  1309. * Normalized project-name tokens (go.mod / package.json / repo dir) used to
  1310. * down-weight the non-discriminative project name in search ranking (#720).
  1311. * Exposed so explore can exclude it from the PascalCase type-disambiguation
  1312. * bias, which would otherwise pull overloaded tokens toward whichever stack
  1313. * embeds the project name.
  1314. */
  1315. getProjectNameTokens(): Set<string> {
  1316. return this.queries.getProjectNameTokens();
  1317. }
  1318. /**
  1319. * Find the project's "primary route file" — the file with the densest
  1320. * concentration of framework-emitted `route` nodes (≥3 routes, ≥30%
  1321. * of all non-test routes). Used to inline the routing config in
  1322. * `codegraph_explore` responses on small realworld template repos
  1323. * (rails-realworld, laravel-realworld, drupal-admintoolbar, …) where
  1324. * Glob+Read of `routes.rb`/`urls.py`/etc. otherwise beats codegraph.
  1325. */
  1326. getTopRouteFile(): { filePath: string; routeCount: number; totalRoutes: number } | null {
  1327. return this.queries.getTopRouteFile();
  1328. }
  1329. /**
  1330. * Build a URL → handler routing manifest from the index. Each entry
  1331. * pairs a route node (URL + method) with its handler function/method
  1332. * via the `references` edge that framework resolvers emit. Returns
  1333. * null when fewer than 3 valid (non-test) routes exist.
  1334. */
  1335. getRoutingManifest(limit?: number): {
  1336. entries: Array<{ url: string; handler: string; handlerFile: string; handlerLine: number; handlerKind: string }>;
  1337. topHandlerFile: string | null;
  1338. topHandlerFileCount: number;
  1339. totalRoutes: number;
  1340. } | null {
  1341. return this.queries.getRoutingManifest(limit);
  1342. }
  1343. // ===========================================================================
  1344. // Edge Operations
  1345. // ===========================================================================
  1346. /**
  1347. * Get outgoing edges from a node
  1348. */
  1349. getOutgoingEdges(nodeId: string): Edge[] {
  1350. return this.queries.getOutgoingEdges(nodeId);
  1351. }
  1352. /**
  1353. * Get incoming edges to a node
  1354. */
  1355. getIncomingEdges(nodeId: string): Edge[] {
  1356. return this.queries.getIncomingEdges(nodeId);
  1357. }
  1358. // ===========================================================================
  1359. // File Operations
  1360. // ===========================================================================
  1361. /**
  1362. * Get a file record by path
  1363. */
  1364. getFile(filePath: string): FileRecord | null {
  1365. return this.queries.getFileByPath(filePath);
  1366. }
  1367. /**
  1368. * Get all tracked files
  1369. */
  1370. getFiles(): FileRecord[] {
  1371. return this.queries.getAllFiles();
  1372. }
  1373. // ===========================================================================
  1374. // Graph Query Methods
  1375. // ===========================================================================
  1376. /**
  1377. * Get the context for a node (ancestors, children, references)
  1378. *
  1379. * Returns comprehensive context about a node including its containment
  1380. * hierarchy, children, incoming/outgoing references, type information,
  1381. * and relevant imports.
  1382. *
  1383. * @param nodeId - ID of the focal node
  1384. * @returns Context object with all related information
  1385. */
  1386. getContext(nodeId: string): Context {
  1387. return this.graphManager.getContext(nodeId);
  1388. }
  1389. /**
  1390. * Traverse the graph from a starting node
  1391. *
  1392. * Uses breadth-first search by default. Supports filtering by edge types,
  1393. * node types, and traversal direction.
  1394. *
  1395. * @param startId - Starting node ID
  1396. * @param options - Traversal options
  1397. * @returns Subgraph containing traversed nodes and edges
  1398. */
  1399. traverse(startId: string, options?: TraversalOptions): Subgraph {
  1400. return this.traverser.traverseBFS(startId, options);
  1401. }
  1402. /**
  1403. * Get the call graph for a function
  1404. *
  1405. * Returns both callers (functions that call this function) and
  1406. * callees (functions called by this function) up to the specified depth.
  1407. *
  1408. * @param nodeId - ID of the function/method node
  1409. * @param depth - Maximum depth in each direction (default: 2)
  1410. * @returns Subgraph containing the call graph
  1411. */
  1412. getCallGraph(nodeId: string, depth: number = 2): Subgraph {
  1413. return this.traverser.getCallGraph(nodeId, depth);
  1414. }
  1415. /**
  1416. * Get the type hierarchy for a class/interface
  1417. *
  1418. * Returns both ancestors (types this extends/implements) and
  1419. * descendants (types that extend/implement this).
  1420. *
  1421. * @param nodeId - ID of the class/interface node
  1422. * @returns Subgraph containing the type hierarchy
  1423. */
  1424. getTypeHierarchy(nodeId: string): Subgraph {
  1425. return this.traverser.getTypeHierarchy(nodeId);
  1426. }
  1427. /**
  1428. * Find all usages of a symbol
  1429. *
  1430. * Returns all nodes that reference the specified symbol through
  1431. * any edge type (calls, references, type_of, etc.).
  1432. *
  1433. * @param nodeId - ID of the symbol node
  1434. * @returns Array of nodes and edges that reference this symbol
  1435. */
  1436. findUsages(nodeId: string): Array<{ node: Node; edge: Edge }> {
  1437. return this.traverser.findUsages(nodeId);
  1438. }
  1439. /**
  1440. * Get callers of a function/method
  1441. *
  1442. * @param nodeId - ID of the function/method node
  1443. * @param maxDepth - Maximum depth to traverse (default: 1)
  1444. * @returns Array of nodes that call this function
  1445. */
  1446. getCallers(nodeId: string, maxDepth: number = 1): Array<{ node: Node; edge: Edge }> {
  1447. return this.traverser.getCallers(nodeId, maxDepth);
  1448. }
  1449. /**
  1450. * Get callees of a function/method
  1451. *
  1452. * @param nodeId - ID of the function/method node
  1453. * @param maxDepth - Maximum depth to traverse (default: 1)
  1454. * @returns Array of nodes called by this function
  1455. */
  1456. getCallees(nodeId: string, maxDepth: number = 1): Array<{ node: Node; edge: Edge }> {
  1457. return this.traverser.getCallees(nodeId, maxDepth);
  1458. }
  1459. /**
  1460. * Calculate the impact radius of a node
  1461. *
  1462. * Returns all nodes that could be affected by changes to this node.
  1463. *
  1464. * @param nodeId - ID of the node
  1465. * @param maxDepth - Maximum depth to traverse (default: 3)
  1466. * @returns Subgraph containing potentially impacted nodes
  1467. */
  1468. getImpactRadius(nodeId: string, maxDepth: number = 3): Subgraph {
  1469. return this.traverser.getImpactRadius(nodeId, maxDepth);
  1470. }
  1471. /**
  1472. * Find the shortest path between two nodes
  1473. *
  1474. * @param fromId - Starting node ID
  1475. * @param toId - Target node ID
  1476. * @param edgeKinds - Edge types to consider (all if empty)
  1477. * @returns Array of nodes and edges forming the path, or null if no path exists
  1478. */
  1479. findPath(
  1480. fromId: string,
  1481. toId: string,
  1482. edgeKinds?: Edge['kind'][]
  1483. ): Array<{ node: Node; edge: Edge | null }> | null {
  1484. return this.traverser.findPath(fromId, toId, edgeKinds);
  1485. }
  1486. /**
  1487. * Get ancestors of a node in the containment hierarchy
  1488. *
  1489. * @param nodeId - ID of the node
  1490. * @returns Array of ancestor nodes from immediate parent to root
  1491. */
  1492. getAncestors(nodeId: string): Node[] {
  1493. return this.traverser.getAncestors(nodeId);
  1494. }
  1495. /**
  1496. * Get immediate children of a node
  1497. *
  1498. * @param nodeId - ID of the node
  1499. * @returns Array of child nodes
  1500. */
  1501. getChildren(nodeId: string): Node[] {
  1502. return this.traverser.getChildren(nodeId);
  1503. }
  1504. /**
  1505. * Get dependencies of a file
  1506. *
  1507. * @param filePath - Path to the file
  1508. * @returns Array of file paths this file depends on
  1509. */
  1510. getFileDependencies(filePath: string): string[] {
  1511. return this.graphManager.getFileDependencies(filePath);
  1512. }
  1513. /**
  1514. * Get dependents of a file
  1515. *
  1516. * @param filePath - Path to the file
  1517. * @returns Array of file paths that depend on this file
  1518. */
  1519. getFileDependents(filePath: string): string[] {
  1520. return this.graphManager.getFileDependents(filePath);
  1521. }
  1522. /**
  1523. * Find circular dependencies in the codebase
  1524. *
  1525. * @returns Array of cycles, each cycle is an array of file paths
  1526. */
  1527. findCircularDependencies(): string[][] {
  1528. return this.graphManager.findCircularDependencies();
  1529. }
  1530. /**
  1531. * Find dead code (unreferenced symbols)
  1532. *
  1533. * @param kinds - Node kinds to check (default: functions, methods, classes)
  1534. * @returns Array of unreferenced nodes
  1535. */
  1536. findDeadCode(kinds?: Node['kind'][]): Node[] {
  1537. return this.graphManager.findDeadCode(kinds);
  1538. }
  1539. /**
  1540. * Get complexity metrics for a node
  1541. *
  1542. * @param nodeId - ID of the node
  1543. * @returns Object containing various complexity metrics
  1544. */
  1545. getNodeMetrics(nodeId: string): {
  1546. incomingEdgeCount: number;
  1547. outgoingEdgeCount: number;
  1548. callCount: number;
  1549. callerCount: number;
  1550. childCount: number;
  1551. depth: number;
  1552. } {
  1553. return this.graphManager.getNodeMetrics(nodeId);
  1554. }
  1555. // ===========================================================================
  1556. // Context Building
  1557. // ===========================================================================
  1558. /**
  1559. * Get the source code for a node
  1560. *
  1561. * Reads the file and extracts the code between startLine and endLine.
  1562. *
  1563. * @param nodeId - ID of the node
  1564. * @returns Code string or null if not found
  1565. */
  1566. async getCode(nodeId: string): Promise<string | null> {
  1567. return this.contextBuilder.getCode(nodeId);
  1568. }
  1569. /**
  1570. * Find relevant subgraph for a query
  1571. *
  1572. * Combines semantic search with graph traversal to find the most
  1573. * relevant nodes and their relationships for a given query.
  1574. *
  1575. * @param query - Natural language query describing the task
  1576. * @param options - Search and traversal options
  1577. * @returns Subgraph of relevant nodes and edges
  1578. */
  1579. async findRelevantContext(
  1580. query: string,
  1581. options?: FindRelevantContextOptions
  1582. ): Promise<Subgraph> {
  1583. return this.contextBuilder.findRelevantContext(query, options);
  1584. }
  1585. /**
  1586. * Build context for a task
  1587. *
  1588. * Creates comprehensive context by:
  1589. * 1. Running FTS search to find entry points
  1590. * 2. Expanding the graph around entry points
  1591. * 3. Extracting code blocks for key nodes
  1592. * 4. Formatting output for Claude
  1593. *
  1594. * @param input - Task description (string or {title, description})
  1595. * @param options - Build options (maxNodes, includeCode, format, etc.)
  1596. * @returns TaskContext object or formatted string (markdown/JSON)
  1597. */
  1598. async buildContext(
  1599. input: TaskInput,
  1600. options?: BuildContextOptions
  1601. ): Promise<TaskContext | string> {
  1602. return this.contextBuilder.buildContext(input, options);
  1603. }
  1604. // ===========================================================================
  1605. // Database Management
  1606. // ===========================================================================
  1607. /**
  1608. * Optimize the database (vacuum and analyze)
  1609. */
  1610. optimize(): void {
  1611. this.db.optimize();
  1612. }
  1613. /**
  1614. * Clear all data from the graph
  1615. */
  1616. clear(): void {
  1617. this.queries.clear();
  1618. }
  1619. /**
  1620. * Alias for close() for backwards compatibility.
  1621. * @deprecated Use close() instead
  1622. */
  1623. destroy(): void {
  1624. this.close();
  1625. }
  1626. /**
  1627. * Completely remove CodeGraph from the project.
  1628. * This closes the database and deletes the .CodeGraph directory.
  1629. *
  1630. * WARNING: This permanently deletes all CodeGraph data for the project.
  1631. */
  1632. uninitialize(): void {
  1633. this.close();
  1634. removeDirectory(this.projectRoot);
  1635. }
  1636. }
  1637. // Default export
  1638. export default CodeGraph;