forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
984 lines (865 loc) · 27.9 KB
/
index.ts
File metadata and controls
984 lines (865 loc) · 27.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/**
* CodeGraph
*
* A local-first code intelligence system that builds a semantic
* knowledge graph from any codebase.
*/
import * as path from 'path';
import {
CodeGraphConfig,
Node,
Edge,
FileRecord,
ExtractionResult,
Subgraph,
TraversalOptions,
SearchOptions,
SearchResult,
Context,
GraphStats,
TaskInput,
TaskContext,
BuildContextOptions,
FindRelevantContextOptions,
} from './types';
import { DatabaseConnection, getDatabasePath } from './db';
import { QueryBuilder } from './db/queries';
import { loadConfig, saveConfig, createDefaultConfig } from './config';
import {
isInitialized,
createDirectory,
removeDirectory,
validateDirectory,
} from './directory';
import {
ExtractionOrchestrator,
IndexProgress,
IndexResult,
SyncResult,
extractFromSource,
initGrammars,
} from './extraction';
import {
ReferenceResolver,
createResolver,
ResolutionResult,
} from './resolution';
import { GraphTraverser, GraphQueryManager } from './graph';
import { ContextBuilder, createContextBuilder } from './context';
import { Mutex, FileLock } from './utils';
import { FileWatcher, WatchOptions } from './sync';
// Re-export types for consumers
export * from './types';
export { getDatabasePath } from './db';
export { getConfigPath } from './config';
export {
getCodeGraphDir,
isInitialized,
findNearestCodeGraphRoot,
CODEGRAPH_DIR,
} from './directory';
export { IndexProgress, IndexResult, SyncResult } from './extraction';
export { detectLanguage, isLanguageSupported, isGrammarLoaded, getSupportedLanguages, initGrammars, loadGrammarsForLanguages, loadAllGrammars } from './extraction';
export { ResolutionResult } from './resolution';
export {
CodeGraphError,
FileError,
ParseError,
DatabaseError,
SearchError,
VectorError,
ConfigError,
Logger,
setLogger,
getLogger,
silentLogger,
defaultLogger,
} from './errors';
export { Mutex, FileLock, processInBatches, debounce, throttle, MemoryMonitor } from './utils';
export { FileWatcher, WatchOptions } from './sync';
export { MCPServer } from './mcp';
/**
* Options for initializing a new CodeGraph project
*/
export interface InitOptions {
/** Custom configuration overrides */
config?: Partial<CodeGraphConfig>;
/** Whether to run initial indexing after init */
index?: boolean;
/** Progress callback for indexing */
onProgress?: (progress: IndexProgress) => void;
}
/**
* Options for opening an existing CodeGraph project
*/
export interface OpenOptions {
/** Whether to run sync if files have changed */
sync?: boolean;
/** Whether to run in read-only mode */
readOnly?: boolean;
}
/**
* Options for indexing
*/
export interface IndexOptions {
/** Progress callback */
onProgress?: (progress: IndexProgress) => void;
/** Abort signal for cancellation */
signal?: AbortSignal;
/** Enable verbose logging (worker lifecycle, memory, timeouts) */
verbose?: boolean;
}
/**
* Main CodeGraph class
*
* Provides the primary interface for interacting with the code knowledge graph.
*/
export class CodeGraph {
private db: DatabaseConnection;
private queries: QueryBuilder;
private config: CodeGraphConfig;
private projectRoot: string;
private orchestrator: ExtractionOrchestrator;
private resolver: ReferenceResolver;
private graphManager: GraphQueryManager;
private traverser: GraphTraverser;
private contextBuilder: ContextBuilder;
// Mutex for preventing concurrent indexing operations (in-process)
private indexMutex = new Mutex();
// File lock for preventing concurrent writes across processes (CLI, MCP, git hooks)
private fileLock: FileLock;
// File watcher for auto-sync on file changes
private watcher: FileWatcher | null = null;
private constructor(
db: DatabaseConnection,
queries: QueryBuilder,
config: CodeGraphConfig,
projectRoot: string
) {
this.db = db;
this.queries = queries;
this.config = config;
this.projectRoot = projectRoot;
this.fileLock = new FileLock(
path.join(projectRoot, '.codegraph', 'codegraph.lock')
);
this.orchestrator = new ExtractionOrchestrator(projectRoot, config, queries);
this.resolver = createResolver(projectRoot, queries);
this.graphManager = new GraphQueryManager(queries);
this.traverser = new GraphTraverser(queries);
this.contextBuilder = createContextBuilder(
projectRoot,
queries,
this.traverser
);
}
// ===========================================================================
// Lifecycle Methods
// ===========================================================================
/**
* Initialize a new CodeGraph project
*
* Creates the .CodeGraph directory, database, and configuration.
*
* @param projectRoot - Path to the project root directory
* @param options - Initialization options
* @returns A new CodeGraph instance
*/
static async init(projectRoot: string, options: InitOptions = {}): Promise<CodeGraph> {
await initGrammars();
const resolvedRoot = path.resolve(projectRoot);
// Check if already initialized
if (isInitialized(resolvedRoot)) {
throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
}
// Create directory structure
createDirectory(resolvedRoot);
// Create and save configuration
const config = createDefaultConfig(resolvedRoot);
if (options.config) {
Object.assign(config, options.config);
}
saveConfig(resolvedRoot, config);
// Initialize database
const dbPath = getDatabasePath(resolvedRoot);
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
const instance = new CodeGraph(db, queries, config, resolvedRoot);
// Run initial indexing if requested
if (options.index) {
await instance.indexAll({ onProgress: options.onProgress });
}
return instance;
}
/**
* Initialize synchronously (without indexing)
*/
static initSync(projectRoot: string, options: Omit<InitOptions, 'index' | 'onProgress'> = {}): CodeGraph {
const resolvedRoot = path.resolve(projectRoot);
// Check if already initialized
if (isInitialized(resolvedRoot)) {
throw new Error(`CodeGraph already initialized in ${resolvedRoot}`);
}
// Create directory structure
createDirectory(resolvedRoot);
// Create and save configuration
const config = createDefaultConfig(resolvedRoot);
if (options.config) {
Object.assign(config, options.config);
}
saveConfig(resolvedRoot, config);
// Initialize database
const dbPath = getDatabasePath(resolvedRoot);
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
return new CodeGraph(db, queries, config, resolvedRoot);
}
/**
* Open an existing CodeGraph project
*
* @param projectRoot - Path to the project root directory
* @param options - Open options
* @returns A CodeGraph instance
*/
static async open(projectRoot: string, options: OpenOptions = {}): Promise<CodeGraph> {
await initGrammars();
const resolvedRoot = path.resolve(projectRoot);
// Check if initialized
if (!isInitialized(resolvedRoot)) {
throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
}
// Validate directory structure
const validation = validateDirectory(resolvedRoot);
if (!validation.valid) {
throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
}
// Load configuration
const config = loadConfig(resolvedRoot);
// Open database
const dbPath = getDatabasePath(resolvedRoot);
const db = DatabaseConnection.open(dbPath);
const queries = new QueryBuilder(db.getDb());
const instance = new CodeGraph(db, queries, config, resolvedRoot);
// Sync if requested
if (options.sync) {
await instance.sync();
}
return instance;
}
/**
* Open synchronously (without sync)
*/
static openSync(projectRoot: string): CodeGraph {
const resolvedRoot = path.resolve(projectRoot);
// Check if initialized
if (!isInitialized(resolvedRoot)) {
throw new Error(`CodeGraph not initialized in ${resolvedRoot}. Run init() first.`);
}
// Validate directory structure
const validation = validateDirectory(resolvedRoot);
if (!validation.valid) {
throw new Error(`Invalid CodeGraph directory: ${validation.errors.join(', ')}`);
}
// Load configuration
const config = loadConfig(resolvedRoot);
// Open database
const dbPath = getDatabasePath(resolvedRoot);
const db = DatabaseConnection.open(dbPath);
const queries = new QueryBuilder(db.getDb());
return new CodeGraph(db, queries, config, resolvedRoot);
}
/**
* Check if a directory has been initialized as a CodeGraph project
*/
static isInitialized(projectRoot: string): boolean {
return isInitialized(path.resolve(projectRoot));
}
/**
* Close the CodeGraph instance and release resources
*/
close(): void {
this.unwatch();
// Release file lock if held
this.fileLock.release();
this.db.close();
}
// ===========================================================================
// Configuration
// ===========================================================================
/**
* Get the current configuration
*/
getConfig(): CodeGraphConfig {
return { ...this.config };
}
/**
* Update configuration
*/
updateConfig(updates: Partial<CodeGraphConfig>): void {
Object.assign(this.config, updates);
saveConfig(this.projectRoot, this.config);
// Recreate orchestrator and resolver with new config
this.orchestrator = new ExtractionOrchestrator(
this.projectRoot,
this.config,
this.queries
);
this.resolver = createResolver(this.projectRoot, this.queries);
}
/**
* Get the project root directory
*/
getProjectRoot(): string {
return this.projectRoot;
}
// ===========================================================================
// Indexing
// ===========================================================================
/**
* Index all files in the project
*
* Uses a mutex to prevent concurrent indexing operations.
*/
async indexAll(options: IndexOptions = {}): Promise<IndexResult> {
return this.indexMutex.withLock(async () => {
try {
this.fileLock.acquire();
} catch {
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 };
}
try {
const result = await this.orchestrator.indexAll(options.onProgress, options.signal, options.verbose);
// Resolve references to create call/import/extends edges
if (result.success && result.filesIndexed > 0) {
// Get count without loading all refs into memory
const unresolvedCount = this.queries.getUnresolvedReferencesCount();
options.onProgress?.({
phase: 'resolving',
current: 0,
total: unresolvedCount,
});
await this.resolveReferencesBatched((current, total) => {
options.onProgress?.({
phase: 'resolving',
current,
total,
});
});
}
return result;
} finally {
this.fileLock.release();
}
});
}
/**
* Index specific files
*
* Uses a mutex to prevent concurrent indexing operations.
*/
async indexFiles(filePaths: string[]): Promise<IndexResult> {
return this.indexMutex.withLock(async () => {
try {
this.fileLock.acquire();
} catch {
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 };
}
try {
return this.orchestrator.indexFiles(filePaths);
} finally {
this.fileLock.release();
}
});
}
/**
* Sync with current file state (incremental update)
*
* Uses a mutex to prevent concurrent indexing operations.
*/
async sync(options: IndexOptions = {}): Promise<SyncResult> {
return this.indexMutex.withLock(async () => {
try {
this.fileLock.acquire();
} catch {
return { filesChecked: 0, filesAdded: 0, filesModified: 0, filesRemoved: 0, nodesUpdated: 0, durationMs: 0 };
}
try {
const result = await this.orchestrator.sync(options.onProgress);
// Resolve references if files were updated
if (result.filesAdded > 0 || result.filesModified > 0) {
if (result.changedFilePaths) {
// Scope resolution to changed files (git fast path — bounded set)
const unresolvedRefs = this.queries.getUnresolvedReferencesByFiles(result.changedFilePaths);
options.onProgress?.({
phase: 'resolving',
current: 0,
total: unresolvedRefs.length,
});
this.resolver.resolveAndPersist(unresolvedRefs, (current, total) => {
options.onProgress?.({
phase: 'resolving',
current,
total,
});
});
} else {
// No git info — use batched resolution to avoid OOM
const unresolvedCount = this.queries.getUnresolvedReferencesCount();
options.onProgress?.({
phase: 'resolving',
current: 0,
total: unresolvedCount,
});
await this.resolveReferencesBatched((current, total) => {
options.onProgress?.({
phase: 'resolving',
current,
total,
});
});
}
}
return result;
} finally {
this.fileLock.release();
}
});
}
/**
* Check if an indexing operation is currently in progress
*/
isIndexing(): boolean {
return this.indexMutex.isLocked();
}
// ===========================================================================
// File Watching
// ===========================================================================
/**
* Start watching for file changes and auto-syncing.
*
* Uses native OS file events (FSEvents on macOS, inotify on Linux 19+,
* ReadDirectoryChangesW on Windows) with debouncing to avoid thrashing.
*
* @param options - Watch options (debounce delay, callbacks)
* @returns true if watching started successfully
*/
watch(options: WatchOptions = {}): boolean {
if (this.watcher?.isActive()) return true;
this.watcher = new FileWatcher(
this.projectRoot,
this.config,
async () => {
const result = await this.sync();
const filesChanged = result.filesAdded + result.filesModified + result.filesRemoved;
return { filesChanged, durationMs: result.durationMs };
},
options
);
return this.watcher.start();
}
/**
* Stop watching for file changes.
*/
unwatch(): void {
if (this.watcher) {
this.watcher.stop();
this.watcher = null;
}
}
/**
* Check if the file watcher is active.
*/
isWatching(): boolean {
return this.watcher?.isActive() ?? false;
}
/**
* Get files that have changed since last index
*/
getChangedFiles(): { added: string[]; modified: string[]; removed: string[] } {
return this.orchestrator.getChangedFiles();
}
/**
* Extract nodes and edges from source code (without storing)
*/
extractFromSource(filePath: string, source: string): ExtractionResult {
return extractFromSource(filePath, source);
}
// ===========================================================================
// Reference Resolution
// ===========================================================================
/**
* Resolve unresolved references and create edges
*
* This method takes unresolved references from extraction and attempts
* to resolve them using multiple strategies:
* - Framework-specific patterns (React, Express, Laravel)
* - Import-based resolution
* - Name-based symbol matching
*/
resolveReferences(onProgress?: (current: number, total: number) => void): ResolutionResult {
// Get all unresolved references from the database
const unresolvedRefs = this.queries.getUnresolvedReferences();
return this.resolver.resolveAndPersist(unresolvedRefs, onProgress);
}
/**
* Resolve references in batches to keep memory bounded on large codebases.
* Processes chunks of unresolved refs, persisting results after each batch.
*/
async resolveReferencesBatched(onProgress?: (current: number, total: number) => void): Promise<ResolutionResult> {
return this.resolver.resolveAndPersistBatched(onProgress);
}
/**
* Get detected frameworks in the project
*/
getDetectedFrameworks(): string[] {
return this.resolver.getDetectedFrameworks();
}
/**
* Re-initialize the resolver (useful after adding new files)
*/
reinitializeResolver(): void {
this.resolver.initialize();
}
// ===========================================================================
// Graph Statistics
// ===========================================================================
/**
* Get statistics about the knowledge graph
*/
getStats(): GraphStats {
const stats = this.queries.getStats();
stats.dbSizeBytes = this.db.getSize();
return stats;
}
/**
* Active SQLite backend for this project's connection. `wasm` means
* the native better-sqlite3 install failed and the WASM fallback is
* serving requests at 5-10x the latency. Surfaced via `codegraph
* status` and the `codegraph_status` MCP tool.
*/
getBackend(): import('./db').SqliteBackend {
return this.db.getBackend();
}
// ===========================================================================
// Node Operations
// ===========================================================================
/**
* Get a node by ID
*/
getNode(id: string): Node | null {
return this.queries.getNodeById(id);
}
/**
* Get all nodes in a file
*/
getNodesInFile(filePath: string): Node[] {
return this.queries.getNodesByFile(filePath);
}
/**
* Get all nodes of a specific kind
*/
getNodesByKind(kind: Node['kind']): Node[] {
return this.queries.getNodesByKind(kind);
}
/**
* Search nodes by text
*/
searchNodes(query: string, options?: SearchOptions): SearchResult[] {
return this.queries.searchNodes(query, options);
}
// ===========================================================================
// Edge Operations
// ===========================================================================
/**
* Get outgoing edges from a node
*/
getOutgoingEdges(nodeId: string): Edge[] {
return this.queries.getOutgoingEdges(nodeId);
}
/**
* Get incoming edges to a node
*/
getIncomingEdges(nodeId: string): Edge[] {
return this.queries.getIncomingEdges(nodeId);
}
// ===========================================================================
// File Operations
// ===========================================================================
/**
* Get a file record by path
*/
getFile(filePath: string): FileRecord | null {
return this.queries.getFileByPath(filePath);
}
/**
* Get all tracked files
*/
getFiles(): FileRecord[] {
return this.queries.getAllFiles();
}
// ===========================================================================
// Graph Query Methods
// ===========================================================================
/**
* Get the context for a node (ancestors, children, references)
*
* Returns comprehensive context about a node including its containment
* hierarchy, children, incoming/outgoing references, type information,
* and relevant imports.
*
* @param nodeId - ID of the focal node
* @returns Context object with all related information
*/
getContext(nodeId: string): Context {
return this.graphManager.getContext(nodeId);
}
/**
* Traverse the graph from a starting node
*
* Uses breadth-first search by default. Supports filtering by edge types,
* node types, and traversal direction.
*
* @param startId - Starting node ID
* @param options - Traversal options
* @returns Subgraph containing traversed nodes and edges
*/
traverse(startId: string, options?: TraversalOptions): Subgraph {
return this.traverser.traverseBFS(startId, options);
}
/**
* Get the call graph for a function
*
* Returns both callers (functions that call this function) and
* callees (functions called by this function) up to the specified depth.
*
* @param nodeId - ID of the function/method node
* @param depth - Maximum depth in each direction (default: 2)
* @returns Subgraph containing the call graph
*/
getCallGraph(nodeId: string, depth: number = 2): Subgraph {
return this.traverser.getCallGraph(nodeId, depth);
}
/**
* Get the type hierarchy for a class/interface
*
* Returns both ancestors (types this extends/implements) and
* descendants (types that extend/implement this).
*
* @param nodeId - ID of the class/interface node
* @returns Subgraph containing the type hierarchy
*/
getTypeHierarchy(nodeId: string): Subgraph {
return this.traverser.getTypeHierarchy(nodeId);
}
/**
* Find all usages of a symbol
*
* Returns all nodes that reference the specified symbol through
* any edge type (calls, references, type_of, etc.).
*
* @param nodeId - ID of the symbol node
* @returns Array of nodes and edges that reference this symbol
*/
findUsages(nodeId: string): Array<{ node: Node; edge: Edge }> {
return this.traverser.findUsages(nodeId);
}
/**
* Get callers of a function/method
*
* @param nodeId - ID of the function/method node
* @param maxDepth - Maximum depth to traverse (default: 1)
* @returns Array of nodes that call this function
*/
getCallers(nodeId: string, maxDepth: number = 1): Array<{ node: Node; edge: Edge }> {
return this.traverser.getCallers(nodeId, maxDepth);
}
/**
* Get callees of a function/method
*
* @param nodeId - ID of the function/method node
* @param maxDepth - Maximum depth to traverse (default: 1)
* @returns Array of nodes called by this function
*/
getCallees(nodeId: string, maxDepth: number = 1): Array<{ node: Node; edge: Edge }> {
return this.traverser.getCallees(nodeId, maxDepth);
}
/**
* Calculate the impact radius of a node
*
* Returns all nodes that could be affected by changes to this node.
*
* @param nodeId - ID of the node
* @param maxDepth - Maximum depth to traverse (default: 3)
* @returns Subgraph containing potentially impacted nodes
*/
getImpactRadius(nodeId: string, maxDepth: number = 3): Subgraph {
return this.traverser.getImpactRadius(nodeId, maxDepth);
}
/**
* Find the shortest path between two nodes
*
* @param fromId - Starting node ID
* @param toId - Target node ID
* @param edgeKinds - Edge types to consider (all if empty)
* @returns Array of nodes and edges forming the path, or null if no path exists
*/
findPath(
fromId: string,
toId: string,
edgeKinds?: Edge['kind'][]
): Array<{ node: Node; edge: Edge | null }> | null {
return this.traverser.findPath(fromId, toId, edgeKinds);
}
/**
* Get ancestors of a node in the containment hierarchy
*
* @param nodeId - ID of the node
* @returns Array of ancestor nodes from immediate parent to root
*/
getAncestors(nodeId: string): Node[] {
return this.traverser.getAncestors(nodeId);
}
/**
* Get immediate children of a node
*
* @param nodeId - ID of the node
* @returns Array of child nodes
*/
getChildren(nodeId: string): Node[] {
return this.traverser.getChildren(nodeId);
}
/**
* Get dependencies of a file
*
* @param filePath - Path to the file
* @returns Array of file paths this file depends on
*/
getFileDependencies(filePath: string): string[] {
return this.graphManager.getFileDependencies(filePath);
}
/**
* Get dependents of a file
*
* @param filePath - Path to the file
* @returns Array of file paths that depend on this file
*/
getFileDependents(filePath: string): string[] {
return this.graphManager.getFileDependents(filePath);
}
/**
* Find circular dependencies in the codebase
*
* @returns Array of cycles, each cycle is an array of file paths
*/
findCircularDependencies(): string[][] {
return this.graphManager.findCircularDependencies();
}
/**
* Find dead code (unreferenced symbols)
*
* @param kinds - Node kinds to check (default: functions, methods, classes)
* @returns Array of unreferenced nodes
*/
findDeadCode(kinds?: Node['kind'][]): Node[] {
return this.graphManager.findDeadCode(kinds);
}
/**
* Get complexity metrics for a node
*
* @param nodeId - ID of the node
* @returns Object containing various complexity metrics
*/
getNodeMetrics(nodeId: string): {
incomingEdgeCount: number;
outgoingEdgeCount: number;
callCount: number;
callerCount: number;
childCount: number;
depth: number;
} {
return this.graphManager.getNodeMetrics(nodeId);
}
// ===========================================================================
// Context Building
// ===========================================================================
/**
* Get the source code for a node
*
* Reads the file and extracts the code between startLine and endLine.
*
* @param nodeId - ID of the node
* @returns Code string or null if not found
*/
async getCode(nodeId: string): Promise<string | null> {
return this.contextBuilder.getCode(nodeId);
}
/**
* Find relevant subgraph for a query
*
* Combines semantic search with graph traversal to find the most
* relevant nodes and their relationships for a given query.
*
* @param query - Natural language query describing the task
* @param options - Search and traversal options
* @returns Subgraph of relevant nodes and edges
*/
async findRelevantContext(
query: string,
options?: FindRelevantContextOptions
): Promise<Subgraph> {
return this.contextBuilder.findRelevantContext(query, options);
}
/**
* Build context for a task
*
* Creates comprehensive context by:
* 1. Running FTS search to find entry points
* 2. Expanding the graph around entry points
* 3. Extracting code blocks for key nodes
* 4. Formatting output for Claude
*
* @param input - Task description (string or {title, description})
* @param options - Build options (maxNodes, includeCode, format, etc.)
* @returns TaskContext object or formatted string (markdown/JSON)
*/
async buildContext(
input: TaskInput,
options?: BuildContextOptions
): Promise<TaskContext | string> {
return this.contextBuilder.buildContext(input, options);
}
// ===========================================================================
// Database Management
// ===========================================================================
/**
* Optimize the database (vacuum and analyze)
*/
optimize(): void {
this.db.optimize();
}
/**
* Clear all data from the graph
*/
clear(): void {
this.queries.clear();
}
/**
* Alias for close() for backwards compatibility.
* @deprecated Use close() instead
*/
destroy(): void {
this.close();
}
/**
* Completely remove CodeGraph from the project.
* This closes the database and deletes the .CodeGraph directory.
*
* WARNING: This permanently deletes all CodeGraph data for the project.
*/
uninitialize(): void {
this.close();
removeDirectory(this.projectRoot);
}
}
// Default export
export default CodeGraph;