index.ts 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  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. if (deferWal) {
  417. priorAutocheckpoint = this.db.getWalAutocheckpoint();
  418. this.db.setWalAutocheckpoint(0);
  419. walValve = new WalCheckpointValve(
  420. this.db,
  421. undefined,
  422. undefined,
  423. options.verbose ? (m) => console.log(`[wal-valve] ${m}`) : undefined
  424. );
  425. walValve.start();
  426. }
  427. try {
  428. const before = this.queries.getNodeAndEdgeCount();
  429. // Mark the index as in-flight BEFORE any writes: a run killed
  430. // mid-index (OOM, SIGKILL, the #850 liveness watchdog) leaves this
  431. // marker behind, so `codegraph status` can tell a truncated index
  432. // from a completed one instead of silently serving partial results.
  433. try { this.queries.setMetadata('index_state', 'indexing'); } catch { /* metadata is advisory */ }
  434. // Segment vocabulary starts empty and is repopulated by the node write
  435. // path as every file (re-)indexes below — so a full index is also the
  436. // orphan-cleanup pass for names deleted since the last one.
  437. try { this.queries.clearNameSegmentVocab(); } catch { /* vocab is advisory — never fail an index over it */ }
  438. // Bulk FTS mode for the mass-insert phase: drop the per-row FTS sync
  439. // triggers, rebuild nodes_fts once from the nodes table afterwards.
  440. // Crash inside the window is healed on the next DatabaseConnection.open.
  441. this.db.beginBulkNodeLoad();
  442. let result: IndexResult;
  443. try {
  444. result = await this.orchestrator.indexAll(
  445. options.onProgress,
  446. options.signal,
  447. options.verbose,
  448. walValve ? () => walValve!.backpressure() : undefined,
  449. // Store-writer offload is fresh-DB-only: with any pre-existing
  450. // data the store path must read (existing-file checks, cross-file
  451. // edge snapshots) and delete, which belongs on one thread.
  452. freshDb ? { dbPath: this.db.getPath(), fastInit } : null
  453. );
  454. } finally {
  455. this.db.endBulkNodeLoad();
  456. }
  457. // Fold the parse phase's WAL BEFORE the first post-parse reads
  458. // (resolver re-init and resolution both read on the main thread):
  459. // paging a bulk-write-sized WAL there is what blew the #850
  460. // watchdog's 60s window in the #1231 repro. Off-thread + awaited,
  461. // so the event loop keeps turning.
  462. if (walValve) await walValve.foldNow();
  463. // Re-detect frameworks now that the index is populated. The resolver
  464. // is constructed with createResolver() before any files exist, so
  465. // framework resolvers whose detect() consults the indexed file list
  466. // (e.g. UIKit/SwiftUI scanning for imports, swift-objc-bridge looking
  467. // for both Swift and ObjC files) all return false on that initial pass
  468. // and silently drop themselves. Re-initializing here gives them a
  469. // chance to see the actual project before resolution runs.
  470. if (result.success && result.filesIndexed > 0) {
  471. this.resolver.initialize();
  472. // Cross-file finalization (e.g. NestJS RouterModule prefixes). Runs
  473. // before resolution so updated names show up in subsequent reads.
  474. this.resolver.runPostExtract();
  475. }
  476. // Resolve references to create call/import/extends edges
  477. if (result.success && result.filesIndexed > 0) {
  478. // Get count without loading all refs into memory
  479. const unresolvedCount = this.queries.getUnresolvedReferencesCount();
  480. // Fast-init leaves the DB in memory-journal (rollback) mode, where
  481. // the parallel resolver pool's read connections would contend with
  482. // the main writer's exclusive commits. When the pool will actually
  483. // run (enough pending refs), restore WAL BEFORE resolution so
  484. // readers never block the writer; otherwise stay in the fast mode
  485. // until the finally — sequential resolution has no readers.
  486. if (fastInit && unresolvedCount >= minRefsForPool()) {
  487. try {
  488. this.db.getDb().pragma('synchronous = NORMAL');
  489. this.db.getDb().pragma('journal_mode = WAL');
  490. } catch { /* keep current mode; resolution still works sequentially */ }
  491. }
  492. options.onProgress?.({
  493. phase: 'resolving',
  494. current: 0,
  495. total: unresolvedCount,
  496. });
  497. await this.resolveReferencesBatched(
  498. (current, total) => {
  499. options.onProgress?.({
  500. phase: 'resolving',
  501. current,
  502. total,
  503. });
  504. },
  505. (done, totalPasses) => {
  506. options.onProgress?.({
  507. phase: 'linking',
  508. current: done,
  509. total: totalPasses,
  510. });
  511. }
  512. );
  513. // Second pass: chained calls whose method lives on a supertype the
  514. // receiver conforms to (protocol-extension / inherited / default-
  515. // interface). Needs the implements/extends edges the main pass just
  516. // built, so it runs after resolution (#750).
  517. const tChained = Date.now();
  518. await this.resolver.resolveChainedCallsViaConformance();
  519. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[synth-timing] chainedConformance: ${Date.now() - tChained}ms`);
  520. // Same lifecycle for `this.<member>` callback registrations whose
  521. // member is inherited from a supertype (#808).
  522. const tDeferred = Date.now();
  523. await this.resolver.resolveDeferredThisMemberRefs();
  524. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[synth-timing] deferredThisMember: ${Date.now() - tDeferred}ms`);
  525. }
  526. // Refresh planner stats + checkpoint the WAL after bulk writes.
  527. // Off-thread (worker connection): on a multi-GB index this is minutes
  528. // of IO, and inline it starved the #850 watchdog AFTER a fully
  529. // successful index. Never load-bearing for correctness.
  530. if (result.success && result.filesIndexed > 0) {
  531. const tMaint = Date.now();
  532. // Quiesce the valve first so its in-flight checkpoint and the
  533. // maintenance checkpoint don't contend for the checkpointer lock
  534. // (the loser would silently no-op and leave the WAL unfolded).
  535. if (walValve) { walValve.stop(); await walValve.drain(); }
  536. await this.db.runMaintenance();
  537. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] maintenance: ${Date.now() - tMaint}ms`);
  538. }
  539. // The orchestrator only sees extraction-phase counts; resolution and
  540. // synthesizer edges (often >50% of the graph on JVM repos) come later.
  541. // Recompute against the DB so the CLI summary reports the true totals.
  542. if (result.success && result.filesIndexed > 0) {
  543. const tCount = Date.now();
  544. const after = this.queries.getNodeAndEdgeCount();
  545. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] count-recompute: ${Date.now() - tCount}ms`);
  546. result.nodesCreated = after.nodes - before.nodes;
  547. result.edgesCreated = after.edges - before.edges;
  548. }
  549. // Stamp the index with the engine that built it, so `codegraph status`
  550. // and `codegraph upgrade` can recommend a re-index when the running
  551. // engine produces richer extraction than the one on disk. Only on a
  552. // real full index — a sync touches a subset, so it must NOT advance the
  553. // extraction stamp (the bulk would still be stale). See extraction-version.ts.
  554. if (result.success && result.filesIndexed > 0) {
  555. try {
  556. this.queries.setMetadata('indexed_with_version', CodeGraphPackageVersion);
  557. this.queries.setMetadata('indexed_with_extraction_version', String(EXTRACTION_VERSION));
  558. } catch { /* metadata is advisory — never fail an index over it */ }
  559. }
  560. // Reconcile the scan's ground truth against what the pipeline
  561. // accounted for. A shortfall means files were silently dropped
  562. // (observed in the wild: a run under heavy load came up 37 files
  563. // short with no error) — record it and tell the user, don't let the
  564. // index pass as complete.
  565. try {
  566. if (!result.success) {
  567. this.queries.setMetadata('index_state', 'failed');
  568. } else {
  569. const accounted = result.filesIndexed + result.filesSkipped + result.filesErrored;
  570. const discovered = result.filesDiscovered;
  571. const shortfall = discovered !== undefined ? discovered - accounted : 0;
  572. if (discovered !== undefined && shortfall > 0) {
  573. this.queries.setMetadata('index_state', 'partial');
  574. this.queries.setMetadata('index_files_discovered', String(discovered));
  575. this.queries.setMetadata('index_files_accounted', String(accounted));
  576. result.errors.push({
  577. 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\`.`,
  578. severity: 'warning',
  579. code: 'index_partial',
  580. });
  581. } else {
  582. this.queries.setMetadata('index_state', 'complete');
  583. if (discovered !== undefined) {
  584. this.queries.setMetadata('index_files_discovered', String(discovered));
  585. this.queries.setMetadata('index_files_accounted', String(accounted));
  586. }
  587. }
  588. }
  589. } catch { /* metadata is advisory — never fail an index over it */ }
  590. return result;
  591. } finally {
  592. // Restore the auto-checkpoint interval AFTER the fold-up above so the
  593. // next ordinary write doesn't inherit a giant inline checkpoint. On
  594. // the error path the WAL may still be large; correctness is unchanged
  595. // (SQLite replays the WAL on the next open) and the follow-up write
  596. // that folds it is the known cost of a failed run.
  597. if (walValve) { walValve.stop(); await walValve.drain(); }
  598. if (deferWal) {
  599. try { this.db.setWalAutocheckpoint(priorAutocheckpoint); } catch { /* connection may be closing */ }
  600. }
  601. if (fastInit) {
  602. // Back to the durable defaults; journal_mode=WAL folds the MEMORY
  603. // journal state into a normal WAL-mode database file.
  604. try {
  605. this.db.getDb().pragma('synchronous = NORMAL');
  606. this.db.getDb().pragma('journal_mode = WAL');
  607. } catch { /* connection may be closing */ }
  608. }
  609. this.fileLock.release();
  610. }
  611. });
  612. }
  613. /**
  614. * Index specific files
  615. *
  616. * Uses a mutex to prevent concurrent indexing operations.
  617. */
  618. async indexFiles(filePaths: string[]): Promise<IndexResult> {
  619. return this.indexMutex.withLock(async () => {
  620. try {
  621. this.fileLock.acquire();
  622. } catch {
  623. 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 };
  624. }
  625. try {
  626. return this.orchestrator.indexFiles(filePaths);
  627. } finally {
  628. this.fileLock.release();
  629. }
  630. });
  631. }
  632. /**
  633. * Sync with current file state (incremental update)
  634. *
  635. * Uses a mutex to prevent concurrent indexing operations.
  636. */
  637. async sync(options: IndexOptions = {}): Promise<SyncResult> {
  638. return this.indexMutex.withLock(async () => {
  639. try {
  640. this.fileLock.acquire();
  641. } catch {
  642. return { filesChecked: 0, filesAdded: 0, filesModified: 0, filesRemoved: 0, nodesUpdated: 0, durationMs: 0 };
  643. }
  644. // Defer WAL auto-checkpointing for the whole incremental run, exactly
  645. // as indexAll does for the bulk path (#1231): sync's store loop and its
  646. // resolution passes churn the same FTS + secondary-index hot pages, and
  647. // at the default 1000-page cadence the inline checkpoints re-write them
  648. // over and over — on HDD-class storage a 7-file sync took 2 minutes at
  649. // 0-2% CPU (#1248). The cost scales with the EXISTING database size,
  650. // not the change size, so small syncs on big indexes hurt most. The
  651. // valve bounds WAL growth off-thread; runMaintenance at the end does
  652. // the final fold-up before the interval is restored in the finally.
  653. // Same kill switch as indexAll: CODEGRAPH_NO_WAL_DEFER=1. Idle valve
  654. // cost is one timer, so watcher-frequency syncs stay cheap.
  655. const deferWal = process.env.CODEGRAPH_NO_WAL_DEFER !== '1' && this.db.getJournalMode() === 'wal';
  656. let walValve: WalCheckpointValve | null = null;
  657. let priorAutocheckpoint = 1000;
  658. if (deferWal) {
  659. priorAutocheckpoint = this.db.getWalAutocheckpoint();
  660. this.db.setWalAutocheckpoint(0);
  661. walValve = new WalCheckpointValve(
  662. this.db,
  663. undefined,
  664. undefined,
  665. options.verbose ? (m) => console.log(`[wal-valve] ${m}`) : undefined
  666. );
  667. walValve.start();
  668. }
  669. try {
  670. // Captured BEFORE the sync runs: the sync's own incremental writes
  671. // populate vocab rows for the files it touches, so an end-of-sync
  672. // emptiness check would see "non-empty" and skip the backfill forever,
  673. // leaving every unchanged file's names unsegmented.
  674. const vocabWasEmpty = (() => {
  675. try { return this.queries.isNameSegmentVocabEmpty(); } catch { return false; }
  676. })();
  677. const result = await this.orchestrator.sync(options.onProgress);
  678. // Fold the store phase's WAL BEFORE the post-store reads below
  679. // (resolution reads on the main thread) — same rationale as
  680. // indexAll's fold between store and resolution.
  681. if (walValve) await walValve.foldNow();
  682. // Cross-file finalization (e.g. NestJS RouterModule prefixes). Run on
  683. // every sync that touched files so edits to `app.module.ts` propagate
  684. // to controllers in unchanged files. The pass is idempotent and cheap
  685. // (regex over *.module.ts only).
  686. if (result.filesAdded > 0 || result.filesModified > 0) {
  687. this.resolver.runPostExtract();
  688. } else if (result.filesRemoved > 0) {
  689. // A pure-removal sync still resolves refs below — the deletion path
  690. // resurrects the removed file's incoming edges as pending refs
  691. // (#1240 removal case) and the orphan sweep consumes them. In a
  692. // long-lived process (daemon) the resolver's name caches were
  693. // warmed against the pre-removal graph; drop them so resolution
  694. // sees the post-removal state. (runPostExtract above clears caches
  695. // itself, so the changed-files branch is already covered.)
  696. this.resolver.clearCaches();
  697. }
  698. // Resolve references if files were updated
  699. const filesChanged = result.filesAdded > 0 || result.filesModified > 0;
  700. if (filesChanged) {
  701. if (result.changedFilePaths) {
  702. // Scope resolution to changed files (git fast path — bounded set)
  703. const tRefLoad = Date.now();
  704. const unresolvedRefs = this.queries.getUnresolvedReferencesByFiles(result.changedFilePaths);
  705. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] sync-ref-load: ${Date.now() - tRefLoad}ms (${unresolvedRefs.length} refs)`);
  706. options.onProgress?.({
  707. phase: 'resolving',
  708. current: 0,
  709. total: unresolvedRefs.length,
  710. });
  711. this.resolver.resolveAndPersist(unresolvedRefs, (current, total) => {
  712. options.onProgress?.({
  713. phase: 'resolving',
  714. current,
  715. total,
  716. });
  717. });
  718. // Retry previously-failed refs the changed files may now satisfy
  719. // (#1240). Scoped resolution above only re-resolves refs FROM the
  720. // changed files — but when a changed file gains an export/symbol,
  721. // refs in UNCHANGED files that failed against the old graph can
  722. // now resolve, and nothing else ever revisits them (their rows
  723. // were parked as status='failed' by an earlier completed pass).
  724. // Look them up by the symbol names the changed files now carry
  725. // and re-resolve just that set. On a sync where no failed ref
  726. // matches, this is one indexed lookup.
  727. const tRetry = Date.now();
  728. const retryable = this.queries.getRetryableFailedReferences(
  729. this.queries.getNodeNamesByFiles(result.changedFilePaths)
  730. );
  731. if (retryable.length > 0) {
  732. options.onProgress?.({
  733. phase: 'resolving',
  734. current: 0,
  735. total: retryable.length,
  736. });
  737. await this.resolver.resolveAndPersistListYielding(retryable);
  738. options.onProgress?.({
  739. phase: 'resolving',
  740. current: retryable.length,
  741. total: retryable.length,
  742. });
  743. }
  744. if (process.env.CODEGRAPH_SYNTH_TIMINGS) console.error(`[phase-timing] sync-failed-ref-retry: ${Date.now() - tRetry}ms (${retryable.length} refs)`);
  745. } else {
  746. // No git info — use batched resolution to avoid OOM
  747. const unresolvedCount = this.queries.getUnresolvedReferencesCount();
  748. options.onProgress?.({
  749. phase: 'resolving',
  750. current: 0,
  751. total: unresolvedCount,
  752. });
  753. await this.resolveReferencesBatched(
  754. (current, total) => {
  755. options.onProgress?.({
  756. phase: 'resolving',
  757. current,
  758. total,
  759. });
  760. },
  761. (done, totalPasses) => {
  762. options.onProgress?.({
  763. phase: 'linking',
  764. current: done,
  765. total: totalPasses,
  766. });
  767. }
  768. );
  769. }
  770. }
  771. // Orphan sweep (#1187). A resolution pass that dies mid-run — the #850
  772. // daemon liveness watchdog's SIGKILL (#1122), Ctrl-C, a crash — leaves
  773. // the refs it never reached in unresolved_refs, and the git-scoped fast
  774. // path above never revisits them (it reads only the changed files'
  775. // rows). Those files' call edges were then missing PERMANENTLY, with
  776. // nothing to see except a too-small blast radius, until a full
  777. // re-index. A completed pass takes every row it processed out of the
  778. // PENDING set (resolved rows are deleted, unresolvable ones parked as
  779. // status='failed' for the #1240 retry above), so any pending row now
  780. // is such an orphan — or a row from an older engine's scoped pass.
  781. // Grind them down with the batched resolver; this also makes a bare
  782. // `codegraph sync` the recovery command for a wedged index. On a
  783. // healthy index this is one COUNT query.
  784. const orphanCount = this.queries.getUnresolvedReferencesCount();
  785. if (orphanCount > 0) {
  786. options.onProgress?.({
  787. phase: 'resolving',
  788. current: 0,
  789. total: orphanCount,
  790. });
  791. await this.resolveReferencesBatched(
  792. (current, total) => {
  793. options.onProgress?.({
  794. phase: 'resolving',
  795. current,
  796. total,
  797. });
  798. },
  799. (done, totalPasses) => {
  800. options.onProgress?.({
  801. phase: 'linking',
  802. current: done,
  803. total: totalPasses,
  804. });
  805. }
  806. );
  807. }
  808. if (filesChanged || orphanCount > 0) {
  809. // Second pass: chained calls whose method lives on a supertype the
  810. // receiver conforms to (protocol-extension / inherited). Needs the
  811. // implements/extends edges built above (#750).
  812. await this.resolver.resolveChainedCallsViaConformance();
  813. // Same lifecycle for `this.<member>` callback registrations whose
  814. // member is inherited from a supertype (#808).
  815. await this.resolver.resolveDeferredThisMemberRefs();
  816. }
  817. // Refresh planner stats + checkpoint the WAL after bulk writes.
  818. // Off-thread — see indexAll's call site.
  819. if (filesChanged || result.filesRemoved > 0 || orphanCount > 0) {
  820. await this.db.runMaintenance();
  821. }
  822. // Heal the segment vocabulary on indexes built before the table
  823. // existed (upgrade path): incremental writes above only cover changed
  824. // files, so a vocab that was empty when this sync STARTED means the
  825. // bulk was never segmented — backfill it (INSERT OR IGNORE, so the
  826. // rows the sync just wrote are fine). Batched + yielding — sync can
  827. // run on the daemon's liveness-watchdog thread (#850/#1091).
  828. try {
  829. if (vocabWasEmpty && this.queries.getNodeAndEdgeCount().nodes > 0) {
  830. await this.rebuildNameSegmentVocab();
  831. }
  832. } catch { /* vocab is advisory — never fail a sync over it */ }
  833. return result;
  834. } finally {
  835. // Mirror indexAll's teardown: stop the valve, then restore the
  836. // auto-checkpoint interval (runMaintenance above already folded the
  837. // WAL on the success path; on the error path SQLite replays it on
  838. // the next open).
  839. if (walValve) { walValve.stop(); await walValve.drain(); }
  840. if (deferWal) {
  841. try { this.db.setWalAutocheckpoint(priorAutocheckpoint); } catch { /* connection may be closing */ }
  842. }
  843. this.fileLock.release();
  844. }
  845. });
  846. }
  847. /**
  848. * Check if an indexing operation is currently in progress
  849. */
  850. isIndexing(): boolean {
  851. return this.indexMutex.isLocked();
  852. }
  853. // ===========================================================================
  854. // File Watching
  855. // ===========================================================================
  856. /**
  857. * Start watching for file changes and auto-syncing.
  858. *
  859. * Uses native OS file events (FSEvents on macOS, inotify on Linux 19+,
  860. * ReadDirectoryChangesW on Windows) with debouncing to avoid thrashing.
  861. *
  862. * @param options - Watch options (debounce delay, callbacks)
  863. * @returns true if watching started successfully
  864. */
  865. watch(options: WatchOptions = {}): boolean {
  866. if (this.watcher?.isActive()) return true;
  867. this.watcher = new FileWatcher(
  868. this.projectRoot,
  869. async () => {
  870. const result = await this.sync();
  871. // sync() returns this exact zero-shape iff it failed to acquire the
  872. // file lock (a real empty sync always has filesChecked > 0 because
  873. // scanDirectory ran). Surface that to the watcher as a typed error
  874. // so it keeps pendingFiles + reschedules instead of clearing them
  875. // (#449).
  876. if (result.filesChecked === 0 && result.durationMs === 0) {
  877. throw new LockUnavailableError();
  878. }
  879. const filesChanged = result.filesAdded + result.filesModified + result.filesRemoved;
  880. return { filesChanged, durationMs: result.durationMs };
  881. },
  882. options
  883. );
  884. return this.watcher.start();
  885. }
  886. /**
  887. * Stop watching for file changes.
  888. */
  889. unwatch(): void {
  890. if (this.watcher) {
  891. this.watcher.stop();
  892. this.watcher = null;
  893. }
  894. }
  895. /**
  896. * Check if the file watcher is active.
  897. */
  898. isWatching(): boolean {
  899. return this.watcher?.isActive() ?? false;
  900. }
  901. /**
  902. * True once live watching has permanently degraded (OS watch-resource
  903. * exhaustion, or a write lock held past the retry budget) and auto-sync is
  904. * disabled until the next {@link watch} call. Distinct from `!isWatching()`:
  905. * a stopped/never-started watcher is inactive but NOT degraded. MCP tools use
  906. * this to surface a whole-index "results may be stale" notice, since
  907. * `getPendingFiles()` goes empty once watching stops (#876).
  908. */
  909. isWatcherDegraded(): boolean {
  910. return this.watcher?.isDegraded() ?? false;
  911. }
  912. /** The reason live watching degraded, or null if it is healthy (#876). */
  913. getWatcherDegradedReason(): string | null {
  914. return this.watcher?.getDegradedReason() ?? null;
  915. }
  916. /**
  917. * Files seen by the file watcher since the last successful sync —
  918. * the per-file "stale" signal MCP tools attach to responses so an agent
  919. * can fall back to {@link Read} for just the affected file without
  920. * waiting for a debounced sync to complete (issue #403).
  921. *
  922. * Returns an empty list when the watcher isn't active, or no events have
  923. * arrived. Each entry includes `firstSeenMs` and `lastSeenMs` (wall-clock
  924. * `Date.now()` values) so callers can render "edited Nms ago", plus an
  925. * `indexing` flag indicating whether the in-flight sync (if any) will
  926. * absorb that file.
  927. */
  928. getPendingFiles(): PendingFile[] {
  929. return this.watcher?.getPendingFiles() ?? [];
  930. }
  931. /**
  932. * Resolves once the file watcher has installed its watch set. Useful for
  933. * tests that need a deterministic boundary before asserting on
  934. * `getPendingFiles()`. Resolves immediately when no watcher is active.
  935. */
  936. waitUntilWatcherReady(timeoutMs?: number): Promise<void> {
  937. return this.watcher ? this.watcher.waitUntilReady(timeoutMs) : Promise.resolve();
  938. }
  939. /**
  940. * Get files that have changed since last index
  941. */
  942. getChangedFiles(): { added: string[]; modified: string[]; removed: string[] } {
  943. return this.orchestrator.getChangedFiles();
  944. }
  945. /**
  946. * Most recent index timestamp (ms since epoch) across all tracked files, or
  947. * null when nothing is indexed yet. Lets library consumers check index
  948. * freshness without shelling out to `codegraph status --json`. (#329)
  949. */
  950. getLastIndexedAt(): number | null {
  951. return this.queries.getLastIndexedAt();
  952. }
  953. /**
  954. * Completeness of the last full index run. `'complete'` is the only good
  955. * state. `'indexing'` after the fact means a run was killed mid-index (OOM,
  956. * SIGKILL, liveness watchdog) and the on-disk index is truncated;
  957. * `'partial'` means the run finished but silently dropped files
  958. * (discovered > indexed+skipped+errored); `'failed'` means it reported
  959. * failure. `null` = index predates this marker. Surfaced by
  960. * `codegraph status`.
  961. */
  962. getIndexState(): 'indexing' | 'complete' | 'partial' | 'failed' | null {
  963. const raw = this.queries.getMetadata('index_state');
  964. return raw === 'indexing' || raw === 'complete' || raw === 'partial' || raw === 'failed'
  965. ? raw
  966. : null;
  967. }
  968. /**
  969. * Which engine built the current index: the package version + extraction
  970. * version stamped at the last full `indexAll`. Either field is null for an
  971. * index built before stamping existed (treated as stale). See
  972. * `extraction-version.ts` and `isIndexStale()`.
  973. */
  974. getIndexBuildInfo(): { version: string | null; extractionVersion: number | null } {
  975. const version = this.queries.getMetadata('indexed_with_version');
  976. const ev = this.queries.getMetadata('indexed_with_extraction_version');
  977. const parsed = ev != null ? parseInt(ev, 10) : NaN;
  978. return { version, extractionVersion: Number.isFinite(parsed) ? parsed : null };
  979. }
  980. /**
  981. * True when the on-disk index was built by an engine whose extraction is
  982. * older than the one now running — i.e. a re-index would add data a migration
  983. * can't backfill. False when there's no index yet (nothing to refresh) or the
  984. * stamp is current. This is the signal behind `codegraph status`'s re-index
  985. * hint and `codegraph upgrade`'s reminder.
  986. */
  987. isIndexStale(): boolean {
  988. if (this.queries.getLastIndexedAt() == null) return false;
  989. const { extractionVersion } = this.getIndexBuildInfo();
  990. return extractionVersion == null || extractionVersion < EXTRACTION_VERSION;
  991. }
  992. /**
  993. * Extract nodes and edges from source code (without storing)
  994. */
  995. extractFromSource(filePath: string, source: string): ExtractionResult {
  996. return extractFromSource(filePath, source);
  997. }
  998. // ===========================================================================
  999. // Reference Resolution
  1000. // ===========================================================================
  1001. /**
  1002. * Resolve unresolved references and create edges
  1003. *
  1004. * This method takes unresolved references from extraction and attempts
  1005. * to resolve them using multiple strategies:
  1006. * - Framework-specific patterns (React, Express, Laravel)
  1007. * - Import-based resolution
  1008. * - Name-based symbol matching
  1009. */
  1010. resolveReferences(onProgress?: (current: number, total: number) => void): ResolutionResult {
  1011. // Get all unresolved references from the database
  1012. const unresolvedRefs = this.queries.getUnresolvedReferences();
  1013. return this.resolver.resolveAndPersist(unresolvedRefs, onProgress);
  1014. }
  1015. /**
  1016. * Resolve references in batches to keep memory bounded on large codebases.
  1017. * Processes chunks of unresolved refs, persisting results after each batch.
  1018. */
  1019. async resolveReferencesBatched(
  1020. onProgress?: (current: number, total: number) => void,
  1021. onSynthesisProgress?: (done: number, total: number) => void
  1022. ): Promise<ResolutionResult> {
  1023. return this.resolver.resolveAndPersistBatched(onProgress, undefined, onSynthesisProgress, {
  1024. dbPath: this.db.getPath(),
  1025. });
  1026. }
  1027. /**
  1028. * References extracted but never attempted by a resolution pass. Zero on a
  1029. * healthy index — a completed pass consumes every pending row (resolving it
  1030. * or parking it as failed, #1240). Non-zero at rest means a pass was
  1031. * interrupted mid-run (killed indexer, crash — #1187), so some files' call
  1032. * edges are missing; the next `sync` sweeps them.
  1033. */
  1034. getPendingReferenceCount(): number {
  1035. return this.queries.getUnresolvedReferencesCount();
  1036. }
  1037. /**
  1038. * Get detected frameworks in the project
  1039. */
  1040. getDetectedFrameworks(): string[] {
  1041. return this.resolver.getDetectedFrameworks();
  1042. }
  1043. /**
  1044. * Re-initialize the resolver (useful after adding new files)
  1045. */
  1046. reinitializeResolver(): void {
  1047. this.resolver.initialize();
  1048. }
  1049. // ===========================================================================
  1050. // Graph Statistics
  1051. // ===========================================================================
  1052. /**
  1053. * Get statistics about the knowledge graph
  1054. */
  1055. getStats(): GraphStats {
  1056. const stats = this.queries.getStats();
  1057. stats.dbSizeBytes = this.db.getSize();
  1058. return stats;
  1059. }
  1060. /**
  1061. * Active SQLite backend for this project's connection (`node-sqlite` — Node's
  1062. * built-in real-SQLite module). Surfaced via `codegraph status` and the
  1063. * `codegraph_status` MCP tool alongside the effective journal mode.
  1064. */
  1065. getBackend(): import('./db').SqliteBackend {
  1066. return this.db.getBackend();
  1067. }
  1068. /**
  1069. * The journal mode actually in effect ('wal', 'delete', …). 'wal' means
  1070. * readers never block on a concurrent writer; anything else means they can,
  1071. * which is the precondition for the "database is locked" failures in issue
  1072. * #238. Surfaced via `codegraph status` and the `codegraph_status` MCP tool.
  1073. */
  1074. getJournalMode(): string {
  1075. return this.db.getJournalMode();
  1076. }
  1077. // ===========================================================================
  1078. // Node Operations
  1079. // ===========================================================================
  1080. /**
  1081. * Get a node by ID
  1082. */
  1083. getNode(id: string): Node | null {
  1084. return this.queries.getNodeById(id);
  1085. }
  1086. /**
  1087. * Get all nodes in a file
  1088. */
  1089. getNodesInFile(filePath: string): Node[] {
  1090. return this.queries.getNodesByFile(filePath);
  1091. }
  1092. /**
  1093. * Get all nodes of a specific kind
  1094. */
  1095. getNodesByKind(kind: Node['kind']): Node[] {
  1096. return this.queries.getNodesByKind(kind);
  1097. }
  1098. /**
  1099. * Get ALL nodes with an exact name (direct index lookup, not FTS-ranked/capped).
  1100. * Used to enumerate every overload of a heavily-overloaded name so the specific
  1101. * definition the caller wants is never dropped below a search cut.
  1102. */
  1103. getNodesByName(name: string): Node[] {
  1104. return this.queries.getNodesByName(name);
  1105. }
  1106. /** Nodes whose name starts with `prefix` (index range scan, capped). */
  1107. getNodesByNamePrefix(prefix: string, limit = 20): Node[] {
  1108. return this.queries.getNodesByNamePrefix(prefix, limit);
  1109. }
  1110. /**
  1111. * Nodes whose name CONTAINS `substring` (LIKE scan, ASCII-case-insensitive,
  1112. * shortest-first). The camel-infix lookup FTS can't do — `profileInfo`
  1113. * inside `getProfileInfoV2` is one FTS token (#1196).
  1114. */
  1115. getNodesByNameSubstring(
  1116. substring: string,
  1117. options: { kinds?: NodeKind[]; limit?: number; excludePrefix?: boolean } = {}
  1118. ): Node[] {
  1119. return this.queries
  1120. .findNodesByNameSubstring(substring, options)
  1121. .map((r) => r.node);
  1122. }
  1123. /**
  1124. * Search nodes by text
  1125. */
  1126. searchNodes(query: string, options?: SearchOptions): SearchResult[] {
  1127. return this.queries.searchNodes(query, options);
  1128. }
  1129. /**
  1130. * Graph-derived prompt matching for the front-load hook's MEDIUM tier:
  1131. * which indexed symbols do these prose words name? "state machine des
  1132. * commandes" → `OrderStateMachine`, in any human language whose technical
  1133. * nouns are Latin script — no keyword list involved.
  1134. *
  1135. * Precision comes from the repo's own naming statistics, not vocabulary:
  1136. * - CO-OCCURRENCE: ≥2 words that are segments of the SAME name ("state" +
  1137. * "machine" → OrderStateMachine) is strong evidence and always qualifies.
  1138. * - RARITY: a single matched word qualifies only when its segment is
  1139. * discriminative here (≤ {@link SEGMENT_RARITY_CEILING} distinct names) —
  1140. * "checkout" in a shop backend yes, "state" in a react app no.
  1141. * Every candidate is re-verified against `nodes` before being returned
  1142. * (vocab rows are proposals; deletions leave orphans by design), so a
  1143. * returned symbol is guaranteed to exist right now.
  1144. */
  1145. getSegmentMatches(words: string[], limit: number = 6): SegmentMatch[] {
  1146. if (words.length === 0) return [];
  1147. // Variant → original word (plural folding), for coverage accounting.
  1148. const variantToWord = new Map<string, string>();
  1149. for (const word of words) {
  1150. for (const variant of segmentLookupVariants(word)) {
  1151. if (!variantToWord.has(variant)) variantToWord.set(variant, word);
  1152. }
  1153. }
  1154. const variants = [...variantToWord.keys()];
  1155. // Tier A: co-occurrence. The SQL folds variants back to their original
  1156. // word (#1146), so minWords=2 means two distinct PROMPT WORDS — a name
  1157. // matching both `service` and `services` can't tie with (or crowd past
  1158. // the LIMIT) a genuine two-word match. The JS re-check below recomputes
  1159. // the fold from live segments as the honesty layer.
  1160. const variantPairs = [...variantToWord.entries()].map(([segment, word]) => ({ segment, word }));
  1161. const candidates: Array<{ name: string; matchedWords: Set<string> }> = [];
  1162. for (const hit of this.queries.getSegmentCoOccurrence(variantPairs, 2, 24)) {
  1163. const matched = this.wordsMatchingName(hit.name, variantToWord);
  1164. if (matched.size >= 2) candidates.push({ name: hit.name, matchedWords: matched });
  1165. }
  1166. // Tier B: single rare word. Only when co-occurrence found nothing — a
  1167. // co-occurring name is categorically stronger evidence — and under
  1168. // stricter rules, because one word is thin: the word must be ≥5 chars
  1169. // (measured FPs: "this", "typo"); the segment must appear in AT LEAST TWO
  1170. // names (a concept the codebase is about clusters across names —
  1171. // CheckoutService/CheckoutController — while a prose coincidence is a
  1172. // singleton: measured FP "deploy to PRODUCTION" → the one name
  1173. // matchesNonProductionDir); and the candidate name must have ≥2 segments
  1174. // (a bare common verb matching a bare function name — "write" → `write` —
  1175. // is prose coincidence, not the user naming a symbol).
  1176. if (candidates.length === 0) {
  1177. const singleWordVariants = variants.filter((v) => variantToWord.get(v)!.length >= 5);
  1178. const counts = this.queries.getSegmentNameCounts(singleWordVariants);
  1179. const rare = [...counts.entries()]
  1180. .filter(([, n]) => n >= 2 && n <= CodeGraph.SEGMENT_RARITY_CEILING)
  1181. .sort((a, b) => a[1] - b[1])
  1182. .slice(0, 2);
  1183. for (const [variant] of rare) {
  1184. const word = variantToWord.get(variant)!;
  1185. for (const name of this.queries.getNamesForSegment(variant, 12)) {
  1186. if (splitIdentifierSegments(name).length < 2) continue;
  1187. candidates.push({ name, matchedWords: new Set([word]) });
  1188. }
  1189. }
  1190. }
  1191. // Verify against nodes (the honesty gate) and pick a representative
  1192. // definition per name. A name whose only nodes are file/import kind has
  1193. // no real definition to point at — surfacing the import statement instead
  1194. // reads as a matched symbol but isn't one (#1144) — so it's skipped, the
  1195. // same way an orphaned vocab row is. (Import names no longer enter the
  1196. // vocab at write time, but rows written before that exclusion persist
  1197. // until the next full index.)
  1198. const out: SegmentMatch[] = [];
  1199. const seen = new Set<string>();
  1200. candidates.sort((a, b) => b.matchedWords.size - a.matchedWords.size || a.name.length - b.name.length);
  1201. for (const candidate of candidates) {
  1202. if (out.length >= limit) break;
  1203. if (seen.has(candidate.name)) continue;
  1204. seen.add(candidate.name);
  1205. const nodes = this.queries.getNodesByName(candidate.name);
  1206. if (nodes.length === 0) continue; // orphaned vocab row — name no longer exists
  1207. const rep = nodes.find((n) => n.kind !== 'file' && n.kind !== 'import');
  1208. if (!rep) continue; // no real definition — don't surface an import/file as one
  1209. out.push({
  1210. name: candidate.name,
  1211. kind: rep.kind,
  1212. filePath: rep.filePath,
  1213. startLine: rep.startLine ?? 0,
  1214. matchedWords: [...candidate.matchedWords].sort(),
  1215. });
  1216. }
  1217. return out;
  1218. }
  1219. /** A single word ("state") can match hundreds of names in a big repo — that
  1220. * is noise, not signal. Ceiling for the single-word tier; co-occurrence is
  1221. * exempt because two words on one name is already discriminative. */
  1222. private static readonly SEGMENT_RARITY_CEILING = 25;
  1223. /** Which of the prompt's original words match `name`'s segments (via
  1224. * variants). Segments are recomputed in JS — a name-keyed vocab lookup
  1225. * would scan the (segment, name) primary key. */
  1226. private wordsMatchingName(name: string, variantToWord: Map<string, string>): Set<string> {
  1227. const segments = new Set(splitIdentifierSegments(name));
  1228. const matched = new Set<string>();
  1229. for (const [variant, word] of variantToWord) {
  1230. if (segments.has(variant)) matched.add(word);
  1231. }
  1232. return matched;
  1233. }
  1234. /**
  1235. * One-shot upgrade heal for callers that open the graph WITHOUT syncing —
  1236. * concretely the prompt hook, whose MEDIUM tier reads the segment
  1237. * vocabulary: a database migrated from before the vocab table existed
  1238. * starts with it empty, and the only other backfill lives inside `sync()`,
  1239. * which such callers never run (#1142). Returns true when the vocab is
  1240. * usable (already populated — the overwhelmingly common one-SELECT case —
  1241. * or healed here); false when it isn't (empty graph, or another process
  1242. * holds the index lock — that process's own sync heals it).
  1243. */
  1244. async healSegmentVocabIfEmpty(): Promise<boolean> {
  1245. const empty = (() => {
  1246. try { return this.queries.isNameSegmentVocabEmpty(); } catch { return false; }
  1247. })();
  1248. if (!empty) return true;
  1249. if (this.queries.getNodeAndEdgeCount().nodes === 0) return false;
  1250. return this.indexMutex.withLock(async () => {
  1251. try {
  1252. this.fileLock.acquire();
  1253. } catch {
  1254. return false; // an index/sync is running — it backfills the vocab itself
  1255. }
  1256. try {
  1257. if (!this.queries.isNameSegmentVocabEmpty()) return true; // raced: healed meanwhile
  1258. await this.rebuildNameSegmentVocab();
  1259. return true;
  1260. } finally {
  1261. this.fileLock.release();
  1262. }
  1263. });
  1264. }
  1265. /**
  1266. * Rebuild the segment vocabulary from the current graph, batched and
  1267. * yielding — the upgrade-heal path for indexes built before the vocab table
  1268. * existed. Runs inside the index mutex/lock (sync and
  1269. * healSegmentVocabIfEmpty hold them).
  1270. */
  1271. private async rebuildNameSegmentVocab(): Promise<void> {
  1272. const maybeYield = createYielder();
  1273. const BATCH = 2000;
  1274. for (let offset = 0; ; offset += BATCH) {
  1275. const names = this.queries.getDistinctNodeNames(BATCH, offset);
  1276. if (names.length === 0) break;
  1277. this.queries.insertNameSegmentsBatch(names);
  1278. await maybeYield();
  1279. }
  1280. }
  1281. /**
  1282. * Normalized project-name tokens (go.mod / package.json / repo dir) used to
  1283. * down-weight the non-discriminative project name in search ranking (#720).
  1284. * Exposed so explore can exclude it from the PascalCase type-disambiguation
  1285. * bias, which would otherwise pull overloaded tokens toward whichever stack
  1286. * embeds the project name.
  1287. */
  1288. getProjectNameTokens(): Set<string> {
  1289. return this.queries.getProjectNameTokens();
  1290. }
  1291. /**
  1292. * Find the project's "primary route file" — the file with the densest
  1293. * concentration of framework-emitted `route` nodes (≥3 routes, ≥30%
  1294. * of all non-test routes). Used to inline the routing config in
  1295. * `codegraph_explore` responses on small realworld template repos
  1296. * (rails-realworld, laravel-realworld, drupal-admintoolbar, …) where
  1297. * Glob+Read of `routes.rb`/`urls.py`/etc. otherwise beats codegraph.
  1298. */
  1299. getTopRouteFile(): { filePath: string; routeCount: number; totalRoutes: number } | null {
  1300. return this.queries.getTopRouteFile();
  1301. }
  1302. /**
  1303. * Build a URL → handler routing manifest from the index. Each entry
  1304. * pairs a route node (URL + method) with its handler function/method
  1305. * via the `references` edge that framework resolvers emit. Returns
  1306. * null when fewer than 3 valid (non-test) routes exist.
  1307. */
  1308. getRoutingManifest(limit?: number): {
  1309. entries: Array<{ url: string; handler: string; handlerFile: string; handlerLine: number; handlerKind: string }>;
  1310. topHandlerFile: string | null;
  1311. topHandlerFileCount: number;
  1312. totalRoutes: number;
  1313. } | null {
  1314. return this.queries.getRoutingManifest(limit);
  1315. }
  1316. // ===========================================================================
  1317. // Edge Operations
  1318. // ===========================================================================
  1319. /**
  1320. * Get outgoing edges from a node
  1321. */
  1322. getOutgoingEdges(nodeId: string): Edge[] {
  1323. return this.queries.getOutgoingEdges(nodeId);
  1324. }
  1325. /**
  1326. * Get incoming edges to a node
  1327. */
  1328. getIncomingEdges(nodeId: string): Edge[] {
  1329. return this.queries.getIncomingEdges(nodeId);
  1330. }
  1331. // ===========================================================================
  1332. // File Operations
  1333. // ===========================================================================
  1334. /**
  1335. * Get a file record by path
  1336. */
  1337. getFile(filePath: string): FileRecord | null {
  1338. return this.queries.getFileByPath(filePath);
  1339. }
  1340. /**
  1341. * Get all tracked files
  1342. */
  1343. getFiles(): FileRecord[] {
  1344. return this.queries.getAllFiles();
  1345. }
  1346. // ===========================================================================
  1347. // Graph Query Methods
  1348. // ===========================================================================
  1349. /**
  1350. * Get the context for a node (ancestors, children, references)
  1351. *
  1352. * Returns comprehensive context about a node including its containment
  1353. * hierarchy, children, incoming/outgoing references, type information,
  1354. * and relevant imports.
  1355. *
  1356. * @param nodeId - ID of the focal node
  1357. * @returns Context object with all related information
  1358. */
  1359. getContext(nodeId: string): Context {
  1360. return this.graphManager.getContext(nodeId);
  1361. }
  1362. /**
  1363. * Traverse the graph from a starting node
  1364. *
  1365. * Uses breadth-first search by default. Supports filtering by edge types,
  1366. * node types, and traversal direction.
  1367. *
  1368. * @param startId - Starting node ID
  1369. * @param options - Traversal options
  1370. * @returns Subgraph containing traversed nodes and edges
  1371. */
  1372. traverse(startId: string, options?: TraversalOptions): Subgraph {
  1373. return this.traverser.traverseBFS(startId, options);
  1374. }
  1375. /**
  1376. * Get the call graph for a function
  1377. *
  1378. * Returns both callers (functions that call this function) and
  1379. * callees (functions called by this function) up to the specified depth.
  1380. *
  1381. * @param nodeId - ID of the function/method node
  1382. * @param depth - Maximum depth in each direction (default: 2)
  1383. * @returns Subgraph containing the call graph
  1384. */
  1385. getCallGraph(nodeId: string, depth: number = 2): Subgraph {
  1386. return this.traverser.getCallGraph(nodeId, depth);
  1387. }
  1388. /**
  1389. * Get the type hierarchy for a class/interface
  1390. *
  1391. * Returns both ancestors (types this extends/implements) and
  1392. * descendants (types that extend/implement this).
  1393. *
  1394. * @param nodeId - ID of the class/interface node
  1395. * @returns Subgraph containing the type hierarchy
  1396. */
  1397. getTypeHierarchy(nodeId: string): Subgraph {
  1398. return this.traverser.getTypeHierarchy(nodeId);
  1399. }
  1400. /**
  1401. * Find all usages of a symbol
  1402. *
  1403. * Returns all nodes that reference the specified symbol through
  1404. * any edge type (calls, references, type_of, etc.).
  1405. *
  1406. * @param nodeId - ID of the symbol node
  1407. * @returns Array of nodes and edges that reference this symbol
  1408. */
  1409. findUsages(nodeId: string): Array<{ node: Node; edge: Edge }> {
  1410. return this.traverser.findUsages(nodeId);
  1411. }
  1412. /**
  1413. * Get callers of a function/method
  1414. *
  1415. * @param nodeId - ID of the function/method node
  1416. * @param maxDepth - Maximum depth to traverse (default: 1)
  1417. * @returns Array of nodes that call this function
  1418. */
  1419. getCallers(nodeId: string, maxDepth: number = 1): Array<{ node: Node; edge: Edge }> {
  1420. return this.traverser.getCallers(nodeId, maxDepth);
  1421. }
  1422. /**
  1423. * Get callees of a function/method
  1424. *
  1425. * @param nodeId - ID of the function/method node
  1426. * @param maxDepth - Maximum depth to traverse (default: 1)
  1427. * @returns Array of nodes called by this function
  1428. */
  1429. getCallees(nodeId: string, maxDepth: number = 1): Array<{ node: Node; edge: Edge }> {
  1430. return this.traverser.getCallees(nodeId, maxDepth);
  1431. }
  1432. /**
  1433. * Calculate the impact radius of a node
  1434. *
  1435. * Returns all nodes that could be affected by changes to this node.
  1436. *
  1437. * @param nodeId - ID of the node
  1438. * @param maxDepth - Maximum depth to traverse (default: 3)
  1439. * @returns Subgraph containing potentially impacted nodes
  1440. */
  1441. getImpactRadius(nodeId: string, maxDepth: number = 3): Subgraph {
  1442. return this.traverser.getImpactRadius(nodeId, maxDepth);
  1443. }
  1444. /**
  1445. * Find the shortest path between two nodes
  1446. *
  1447. * @param fromId - Starting node ID
  1448. * @param toId - Target node ID
  1449. * @param edgeKinds - Edge types to consider (all if empty)
  1450. * @returns Array of nodes and edges forming the path, or null if no path exists
  1451. */
  1452. findPath(
  1453. fromId: string,
  1454. toId: string,
  1455. edgeKinds?: Edge['kind'][]
  1456. ): Array<{ node: Node; edge: Edge | null }> | null {
  1457. return this.traverser.findPath(fromId, toId, edgeKinds);
  1458. }
  1459. /**
  1460. * Get ancestors of a node in the containment hierarchy
  1461. *
  1462. * @param nodeId - ID of the node
  1463. * @returns Array of ancestor nodes from immediate parent to root
  1464. */
  1465. getAncestors(nodeId: string): Node[] {
  1466. return this.traverser.getAncestors(nodeId);
  1467. }
  1468. /**
  1469. * Get immediate children of a node
  1470. *
  1471. * @param nodeId - ID of the node
  1472. * @returns Array of child nodes
  1473. */
  1474. getChildren(nodeId: string): Node[] {
  1475. return this.traverser.getChildren(nodeId);
  1476. }
  1477. /**
  1478. * Get dependencies of a file
  1479. *
  1480. * @param filePath - Path to the file
  1481. * @returns Array of file paths this file depends on
  1482. */
  1483. getFileDependencies(filePath: string): string[] {
  1484. return this.graphManager.getFileDependencies(filePath);
  1485. }
  1486. /**
  1487. * Get dependents of a file
  1488. *
  1489. * @param filePath - Path to the file
  1490. * @returns Array of file paths that depend on this file
  1491. */
  1492. getFileDependents(filePath: string): string[] {
  1493. return this.graphManager.getFileDependents(filePath);
  1494. }
  1495. /**
  1496. * Find circular dependencies in the codebase
  1497. *
  1498. * @returns Array of cycles, each cycle is an array of file paths
  1499. */
  1500. findCircularDependencies(): string[][] {
  1501. return this.graphManager.findCircularDependencies();
  1502. }
  1503. /**
  1504. * Find dead code (unreferenced symbols)
  1505. *
  1506. * @param kinds - Node kinds to check (default: functions, methods, classes)
  1507. * @returns Array of unreferenced nodes
  1508. */
  1509. findDeadCode(kinds?: Node['kind'][]): Node[] {
  1510. return this.graphManager.findDeadCode(kinds);
  1511. }
  1512. /**
  1513. * Get complexity metrics for a node
  1514. *
  1515. * @param nodeId - ID of the node
  1516. * @returns Object containing various complexity metrics
  1517. */
  1518. getNodeMetrics(nodeId: string): {
  1519. incomingEdgeCount: number;
  1520. outgoingEdgeCount: number;
  1521. callCount: number;
  1522. callerCount: number;
  1523. childCount: number;
  1524. depth: number;
  1525. } {
  1526. return this.graphManager.getNodeMetrics(nodeId);
  1527. }
  1528. // ===========================================================================
  1529. // Context Building
  1530. // ===========================================================================
  1531. /**
  1532. * Get the source code for a node
  1533. *
  1534. * Reads the file and extracts the code between startLine and endLine.
  1535. *
  1536. * @param nodeId - ID of the node
  1537. * @returns Code string or null if not found
  1538. */
  1539. async getCode(nodeId: string): Promise<string | null> {
  1540. return this.contextBuilder.getCode(nodeId);
  1541. }
  1542. /**
  1543. * Find relevant subgraph for a query
  1544. *
  1545. * Combines semantic search with graph traversal to find the most
  1546. * relevant nodes and their relationships for a given query.
  1547. *
  1548. * @param query - Natural language query describing the task
  1549. * @param options - Search and traversal options
  1550. * @returns Subgraph of relevant nodes and edges
  1551. */
  1552. async findRelevantContext(
  1553. query: string,
  1554. options?: FindRelevantContextOptions
  1555. ): Promise<Subgraph> {
  1556. return this.contextBuilder.findRelevantContext(query, options);
  1557. }
  1558. /**
  1559. * Build context for a task
  1560. *
  1561. * Creates comprehensive context by:
  1562. * 1. Running FTS search to find entry points
  1563. * 2. Expanding the graph around entry points
  1564. * 3. Extracting code blocks for key nodes
  1565. * 4. Formatting output for Claude
  1566. *
  1567. * @param input - Task description (string or {title, description})
  1568. * @param options - Build options (maxNodes, includeCode, format, etc.)
  1569. * @returns TaskContext object or formatted string (markdown/JSON)
  1570. */
  1571. async buildContext(
  1572. input: TaskInput,
  1573. options?: BuildContextOptions
  1574. ): Promise<TaskContext | string> {
  1575. return this.contextBuilder.buildContext(input, options);
  1576. }
  1577. // ===========================================================================
  1578. // Database Management
  1579. // ===========================================================================
  1580. /**
  1581. * Optimize the database (vacuum and analyze)
  1582. */
  1583. optimize(): void {
  1584. this.db.optimize();
  1585. }
  1586. /**
  1587. * Clear all data from the graph
  1588. */
  1589. clear(): void {
  1590. this.queries.clear();
  1591. }
  1592. /**
  1593. * Alias for close() for backwards compatibility.
  1594. * @deprecated Use close() instead
  1595. */
  1596. destroy(): void {
  1597. this.close();
  1598. }
  1599. /**
  1600. * Completely remove CodeGraph from the project.
  1601. * This closes the database and deletes the .CodeGraph directory.
  1602. *
  1603. * WARNING: This permanently deletes all CodeGraph data for the project.
  1604. */
  1605. uninitialize(): void {
  1606. this.close();
  1607. removeDirectory(this.projectRoot);
  1608. }
  1609. }
  1610. // Default export
  1611. export default CodeGraph;