1
0

index.ts 74 KB

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