forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueries.ts
More file actions
1448 lines (1310 loc) · 47 KB
/
queries.ts
File metadata and controls
1448 lines (1310 loc) · 47 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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Database Queries
*
* Prepared statements for CRUD operations on the knowledge graph.
*/
import { SqliteDatabase, SqliteStatement } from './sqlite-adapter';
import {
Node,
Edge,
FileRecord,
UnresolvedReference,
NodeKind,
EdgeKind,
Language,
GraphStats,
SearchOptions,
SearchResult,
} from '../types';
import { safeJsonParse } from '../utils';
import { kindBonus, nameMatchBonus, scorePathRelevance } from '../search/query-utils';
import { parseQuery, boundedEditDistance } from '../search/query-parser';
/**
* Database row types (snake_case from SQLite)
*/
interface NodeRow {
id: string;
kind: string;
name: string;
qualified_name: string;
file_path: string;
language: string;
start_line: number;
end_line: number;
start_column: number;
end_column: number;
docstring: string | null;
signature: string | null;
visibility: string | null;
is_exported: number;
is_async: number;
is_static: number;
is_abstract: number;
decorators: string | null;
type_parameters: string | null;
updated_at: number;
}
interface EdgeRow {
id: number;
source: string;
target: string;
kind: string;
metadata: string | null;
line: number | null;
col: number | null;
provenance: string | null;
}
interface FileRow {
path: string;
content_hash: string;
language: string;
size: number;
modified_at: number;
indexed_at: number;
node_count: number;
errors: string | null;
}
interface UnresolvedRefRow {
id: number;
from_node_id: string;
reference_name: string;
reference_kind: string;
line: number;
col: number;
candidates: string | null;
file_path: string;
language: string;
}
/**
* Convert database row to Node object
*/
function rowToNode(row: NodeRow): Node {
return {
id: row.id,
kind: row.kind as NodeKind,
name: row.name,
qualifiedName: row.qualified_name,
filePath: row.file_path,
language: row.language as Language,
startLine: row.start_line,
endLine: row.end_line,
startColumn: row.start_column,
endColumn: row.end_column,
docstring: row.docstring ?? undefined,
signature: row.signature ?? undefined,
visibility: row.visibility as Node['visibility'],
isExported: row.is_exported === 1,
isAsync: row.is_async === 1,
isStatic: row.is_static === 1,
isAbstract: row.is_abstract === 1,
decorators: row.decorators ? safeJsonParse(row.decorators, undefined) : undefined,
typeParameters: row.type_parameters ? safeJsonParse(row.type_parameters, undefined) : undefined,
updatedAt: row.updated_at,
};
}
/**
* Convert database row to Edge object
*/
function rowToEdge(row: EdgeRow): Edge {
return {
source: row.source,
target: row.target,
kind: row.kind as EdgeKind,
metadata: row.metadata ? safeJsonParse(row.metadata, undefined) : undefined,
line: row.line ?? undefined,
column: row.col ?? undefined,
provenance: row.provenance as Edge['provenance'],
};
}
/**
* Convert database row to FileRecord object
*/
function rowToFileRecord(row: FileRow): FileRecord {
return {
path: row.path,
contentHash: row.content_hash,
language: row.language as Language,
size: row.size,
modifiedAt: row.modified_at,
indexedAt: row.indexed_at,
nodeCount: row.node_count,
errors: row.errors ? safeJsonParse(row.errors, undefined) : undefined,
};
}
/**
* Query builder for the knowledge graph database
*/
export class QueryBuilder {
private db: SqliteDatabase;
// Node cache for frequently accessed nodes (LRU-style, max 1000 entries)
private nodeCache: Map<string, Node> = new Map();
private readonly maxCacheSize = 1000;
// Prepared statements (lazily initialized)
private stmts: {
insertNode?: SqliteStatement;
updateNode?: SqliteStatement;
deleteNode?: SqliteStatement;
deleteNodesByFile?: SqliteStatement;
getNodeById?: SqliteStatement;
getNodesByFile?: SqliteStatement;
getNodesByKind?: SqliteStatement;
insertEdge?: SqliteStatement;
upsertFile?: SqliteStatement;
deleteEdgesBySource?: SqliteStatement;
deleteEdgesByTarget?: SqliteStatement;
getEdgesBySource?: SqliteStatement;
getEdgesByTarget?: SqliteStatement;
insertFile?: SqliteStatement;
updateFile?: SqliteStatement;
deleteFile?: SqliteStatement;
getFileByPath?: SqliteStatement;
getAllFiles?: SqliteStatement;
insertUnresolved?: SqliteStatement;
deleteUnresolvedByNode?: SqliteStatement;
getUnresolvedByName?: SqliteStatement;
getNodesByName?: SqliteStatement;
getNodesByQualifiedNameExact?: SqliteStatement;
getNodesByLowerName?: SqliteStatement;
getUnresolvedCount?: SqliteStatement;
getUnresolvedBatch?: SqliteStatement;
getAllFilePaths?: SqliteStatement;
getAllNodeNames?: SqliteStatement;
} = {};
constructor(db: SqliteDatabase) {
this.db = db;
}
// ===========================================================================
// Node Operations
// ===========================================================================
/**
* Insert a new node
*/
insertNode(node: Node): void {
if (!this.stmts.insertNode) {
this.stmts.insertNode = this.db.prepare(`
INSERT OR REPLACE INTO nodes (
id, kind, name, qualified_name, file_path, language,
start_line, end_line, start_column, end_column,
docstring, signature, visibility,
is_exported, is_async, is_static, is_abstract,
decorators, type_parameters, updated_at
) VALUES (
@id, @kind, @name, @qualifiedName, @filePath, @language,
@startLine, @endLine, @startColumn, @endColumn,
@docstring, @signature, @visibility,
@isExported, @isAsync, @isStatic, @isAbstract,
@decorators, @typeParameters, @updatedAt
)
`);
}
// Validate required fields to prevent SQLite bind errors
if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
console.error('[CodeGraph] Skipping node with missing required fields:', {
id: node.id,
kind: node.kind,
name: node.name,
filePath: node.filePath,
language: node.language,
});
return;
}
try {
this.stmts.insertNode.run({
id: node.id,
kind: node.kind,
name: node.name,
qualifiedName: node.qualifiedName ?? node.name,
filePath: node.filePath,
language: node.language,
startLine: node.startLine ?? 0,
endLine: node.endLine ?? 0,
startColumn: node.startColumn ?? 0,
endColumn: node.endColumn ?? 0,
docstring: node.docstring ?? null,
signature: node.signature ?? null,
visibility: node.visibility ?? null,
isExported: node.isExported ? 1 : 0,
isAsync: node.isAsync ? 1 : 0,
isStatic: node.isStatic ? 1 : 0,
isAbstract: node.isAbstract ? 1 : 0,
decorators: node.decorators ? JSON.stringify(node.decorators) : null,
typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
updatedAt: node.updatedAt ?? Date.now(),
});
} catch (error) {
throw error;
}
}
/**
* Insert multiple nodes in a transaction
*/
insertNodes(nodes: Node[]): void {
this.db.transaction(() => {
for (const node of nodes) {
this.insertNode(node);
}
})();
}
/**
* Update an existing node
*/
updateNode(node: Node): void {
if (!this.stmts.updateNode) {
this.stmts.updateNode = this.db.prepare(`
UPDATE nodes SET
kind = @kind,
name = @name,
qualified_name = @qualifiedName,
file_path = @filePath,
language = @language,
start_line = @startLine,
end_line = @endLine,
start_column = @startColumn,
end_column = @endColumn,
docstring = @docstring,
signature = @signature,
visibility = @visibility,
is_exported = @isExported,
is_async = @isAsync,
is_static = @isStatic,
is_abstract = @isAbstract,
decorators = @decorators,
type_parameters = @typeParameters,
updated_at = @updatedAt
WHERE id = @id
`);
}
// Invalidate cache before update
this.nodeCache.delete(node.id);
// Validate required fields
if (!node.id || !node.kind || !node.name || !node.filePath || !node.language) {
console.error('[CodeGraph] Skipping node update with missing required fields:', node.id);
return;
}
this.stmts.updateNode.run({
id: node.id,
kind: node.kind,
name: node.name,
qualifiedName: node.qualifiedName ?? node.name,
filePath: node.filePath,
language: node.language,
startLine: node.startLine ?? 0,
endLine: node.endLine ?? 0,
startColumn: node.startColumn ?? 0,
endColumn: node.endColumn ?? 0,
docstring: node.docstring ?? null,
signature: node.signature ?? null,
visibility: node.visibility ?? null,
isExported: node.isExported ? 1 : 0,
isAsync: node.isAsync ? 1 : 0,
isStatic: node.isStatic ? 1 : 0,
isAbstract: node.isAbstract ? 1 : 0,
decorators: node.decorators ? JSON.stringify(node.decorators) : null,
typeParameters: node.typeParameters ? JSON.stringify(node.typeParameters) : null,
updatedAt: node.updatedAt ?? Date.now(),
});
}
/**
* Delete a node by ID
*/
deleteNode(id: string): void {
if (!this.stmts.deleteNode) {
this.stmts.deleteNode = this.db.prepare('DELETE FROM nodes WHERE id = ?');
}
// Invalidate cache
this.nodeCache.delete(id);
this.stmts.deleteNode.run(id);
}
/**
* Delete all nodes for a file
*/
deleteNodesByFile(filePath: string): void {
if (!this.stmts.deleteNodesByFile) {
this.stmts.deleteNodesByFile = this.db.prepare('DELETE FROM nodes WHERE file_path = ?');
}
// Invalidate cache for nodes in this file
for (const [id, node] of this.nodeCache) {
if (node.filePath === filePath) {
this.nodeCache.delete(id);
}
}
this.stmts.deleteNodesByFile.run(filePath);
}
/**
* Get a node by ID
*/
getNodeById(id: string): Node | null {
// Check cache first
if (this.nodeCache.has(id)) {
const cached = this.nodeCache.get(id)!;
// Move to end to implement LRU (delete and re-add)
this.nodeCache.delete(id);
this.nodeCache.set(id, cached);
return cached;
}
if (!this.stmts.getNodeById) {
this.stmts.getNodeById = this.db.prepare('SELECT * FROM nodes WHERE id = ?');
}
const row = this.stmts.getNodeById.get(id) as NodeRow | undefined;
if (!row) {
return null;
}
const node = rowToNode(row);
this.cacheNode(node);
return node;
}
/**
* Add a node to the cache, evicting oldest if needed
*/
private cacheNode(node: Node): void {
if (this.nodeCache.size >= this.maxCacheSize) {
// Evict oldest (first) entry
const firstKey = this.nodeCache.keys().next().value;
if (firstKey) {
this.nodeCache.delete(firstKey);
}
}
this.nodeCache.set(node.id, node);
}
/**
* Clear the node cache
*/
clearCache(): void {
this.nodeCache.clear();
}
/**
* Get all nodes in a file
*/
getNodesByFile(filePath: string): Node[] {
if (!this.stmts.getNodesByFile) {
this.stmts.getNodesByFile = this.db.prepare(
'SELECT * FROM nodes WHERE file_path = ? ORDER BY start_line'
);
}
const rows = this.stmts.getNodesByFile.all(filePath) as NodeRow[];
return rows.map(rowToNode);
}
/**
* Get all nodes of a specific kind
*/
getNodesByKind(kind: NodeKind): Node[] {
if (!this.stmts.getNodesByKind) {
this.stmts.getNodesByKind = this.db.prepare('SELECT * FROM nodes WHERE kind = ?');
}
const rows = this.stmts.getNodesByKind.all(kind) as NodeRow[];
return rows.map(rowToNode);
}
/**
* Get all nodes in the database
*/
getAllNodes(): Node[] {
const rows = this.db.prepare('SELECT * FROM nodes').all() as NodeRow[];
return rows.map(rowToNode);
}
/**
* Get nodes by exact name match (uses idx_nodes_name index)
*/
getNodesByName(name: string): Node[] {
if (!this.stmts.getNodesByName) {
this.stmts.getNodesByName = this.db.prepare('SELECT * FROM nodes WHERE name = ?');
}
const rows = this.stmts.getNodesByName.all(name) as NodeRow[];
return rows.map(rowToNode);
}
/**
* Get nodes by exact qualified name match (uses idx_nodes_qualified_name index)
*/
getNodesByQualifiedNameExact(qualifiedName: string): Node[] {
if (!this.stmts.getNodesByQualifiedNameExact) {
this.stmts.getNodesByQualifiedNameExact = this.db.prepare(
'SELECT * FROM nodes WHERE qualified_name = ?'
);
}
const rows = this.stmts.getNodesByQualifiedNameExact.all(qualifiedName) as NodeRow[];
return rows.map(rowToNode);
}
/**
* Get nodes by lowercase name match (uses idx_nodes_lower_name expression index)
*/
getNodesByLowerName(lowerName: string): Node[] {
if (!this.stmts.getNodesByLowerName) {
this.stmts.getNodesByLowerName = this.db.prepare(
'SELECT * FROM nodes WHERE lower(name) = ?'
);
}
const rows = this.stmts.getNodesByLowerName.all(lowerName) as NodeRow[];
return rows.map(rowToNode);
}
/**
* Search nodes by name using FTS with fallback to LIKE for better matching
*
* Search strategy:
* 1. Try FTS5 prefix match (query*) for word-start matching
* 2. If no results, try LIKE for substring matching (e.g., "signIn" finds "signInWithGoogle")
* 3. Score results based on match quality
*/
searchNodes(query: string, options: SearchOptions = {}): SearchResult[] {
const { limit = 100, offset = 0 } = options;
// Parse field-qualified bits out of the raw query (kind:, lang:,
// path:, name:). Anything not recognised stays in `text` and goes
// to FTS unchanged. Filters compose with the SearchOptions arg —
// both are applied (intersection-style).
const parsed = parseQuery(query);
const mergedKinds =
parsed.kinds.length > 0
? Array.from(new Set([...(options.kinds ?? []), ...parsed.kinds]))
: options.kinds;
const mergedLanguages =
parsed.languages.length > 0
? Array.from(new Set([...(options.languages ?? []), ...parsed.languages]))
: options.languages;
const pathFilters = parsed.pathFilters;
const nameFilters = parsed.nameFilters;
// The text portion drives FTS/LIKE; if all the user typed was
// filters (`kind:function`), we still need *some* candidate set,
// so synthesise an empty-text path that returns everything matching
// the filters.
const text = parsed.text;
const kinds = mergedKinds;
const languages = mergedLanguages;
// First try FTS5 with prefix matching
let results = text
? this.searchNodesFTS(text, { kinds, languages, limit, offset })
// Over-fetch by 5× when running filter-only (no text). The
// post-scoring path: + name: filters can be very selective, so
// a smaller multiplier risks returning fewer than `limit`
// results despite the DB having plenty of matches.
: this.searchAllByFilters({ kinds, languages, limit: limit * 5 });
// If no FTS results, try LIKE-based substring search
if (results.length === 0 && text.length >= 2) {
results = this.searchNodesLike(text, { kinds, languages, limit, offset });
}
// Final fuzzy fallback: scan all known names and keep those within
// a tight Levenshtein distance. Only fires when both FTS and LIKE
// returned nothing AND there's a text portion long enough to be
// worth fuzzing (1-char queries would match too much).
if (results.length === 0 && text.length >= 3) {
results = this.searchNodesFuzzy(text, { kinds, languages, limit });
}
// Supplement: ensure exact name matches are always candidates.
// BM25 can bury short exact-match names (e.g. "getBean") under hundreds of
// compound names (e.g. "getBeanDescriptor") in large codebases,
// pushing them past the FTS fetch limit before post-hoc scoring can help.
// Use the max BM25 score as the base so the nameMatchBonus (exact=30 vs
// prefix=20) actually differentiates them after rescoring.
if (results.length > 0 && query) {
const existingIds = new Set(results.map(r => r.node.id));
const maxFtsScore = Math.max(...results.map(r => r.score));
const terms = query.split(/\s+/).filter(t => t.length >= 2);
for (const term of terms) {
let sql = 'SELECT * FROM nodes WHERE name = ? COLLATE NOCASE';
const params: (string | number)[] = [term];
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
sql += ' LIMIT 20';
const rows = this.db.prepare(sql).all(...params) as NodeRow[];
for (const row of rows) {
if (!existingIds.has(row.id)) {
results.push({ node: rowToNode(row), score: maxFtsScore });
existingIds.add(row.id);
}
}
}
}
// Apply multi-signal scoring
if (results.length > 0 && (text || query)) {
const scoringQuery = text || query;
results = results.map(r => ({
...r,
score: r.score
+ kindBonus(r.node.kind)
+ scorePathRelevance(r.node.filePath, scoringQuery)
+ nameMatchBonus(r.node.name, scoringQuery),
}));
results.sort((a, b) => b.score - a.score);
// Trim to requested limit after rescoring
if (results.length > limit) {
results = results.slice(0, limit);
}
}
// Apply path: + name: filters AFTER scoring. Scoring already uses
// path/name as a soft signal; the explicit filters here are a hard
// gate. Done last so the FTS limit fetched plenty of candidates to
// narrow from.
if (pathFilters.length > 0) {
const lowered = pathFilters.map((p) => p.toLowerCase());
results = results.filter((r) => {
const fp = r.node.filePath.toLowerCase();
return lowered.some((p) => fp.includes(p));
});
}
if (nameFilters.length > 0) {
const lowered = nameFilters.map((n) => n.toLowerCase());
results = results.filter((r) => {
const nm = r.node.name.toLowerCase();
return lowered.some((n) => nm.includes(n));
});
}
return results;
}
/**
* Match-everything path used when the user supplied only field
* filters (`kind:function lang:typescript`) with no text. Returns
* candidates ordered by name; the caller's filter pass narrows to
* what was asked for.
*/
private searchAllByFilters(options: {
kinds?: NodeKind[];
languages?: Language[];
limit: number;
}): SearchResult[] {
const { kinds, languages, limit } = options;
let sql = 'SELECT * FROM nodes WHERE 1=1';
const params: (string | number)[] = [];
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
sql += ' ORDER BY name LIMIT ?';
params.push(limit);
const rows = this.db.prepare(sql).all(...params) as NodeRow[];
return rows.map((row) => ({ node: rowToNode(row), score: 1 }));
}
/**
* Fuzzy fallback: when zero FTS/LIKE hits, try an edit-distance
* sweep over the distinct symbol-name set. Caps `maxDist` at 2 so
* `getUssr` finds `getUser` but `process` doesn't match `prosody`.
* Bounded edit distance keeps each comparison cheap; the per-query
* scan is O(distinct-name-count) which is far smaller than total
* node count on any real codebase.
*/
private searchNodesFuzzy(
text: string,
options: { kinds?: NodeKind[]; languages?: Language[]; limit: number }
): SearchResult[] {
const { kinds, languages, limit } = options;
const lowered = text.toLowerCase();
const maxDist = lowered.length <= 4 ? 1 : 2;
// Pull the distinct name list once. The set is cached on QueryBuilder
// by getAllNodeNames(); even on a 200k-node project the distinct
// name set is typically O(10k) because most names repeat. The
// candidate-cap below bounds memory regardless.
const allNames = this.getAllNodeNames();
const candidates: Array<{ name: string; dist: number }> = [];
for (const name of allNames) {
const dist = boundedEditDistance(name.toLowerCase(), lowered, maxDist);
if (dist <= maxDist) candidates.push({ name, dist });
}
candidates.sort((a, b) => a.dist - b.dist);
// Cap the per-name follow-up queries. Each survivor triggers a
// separate `SELECT * FROM nodes WHERE name = ?`; without this cap
// a project with many similar names (`getUser1`, `getUser2`...)
// could fan out far beyond `limit` queries before the inner-loop
// limit kicks in.
const FUZZY_FOLLOWUP_CAP = Math.max(limit * 2, 50);
const cappedCandidates = candidates.slice(0, FUZZY_FOLLOWUP_CAP);
const results: SearchResult[] = [];
const seen = new Set<string>();
for (const c of cappedCandidates) {
if (results.length >= limit) break;
let sql = 'SELECT * FROM nodes WHERE name = ?';
const params: (string | number)[] = [c.name];
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
sql += ' LIMIT 5';
const rows = this.db.prepare(sql).all(...params) as NodeRow[];
for (const row of rows) {
if (seen.has(row.id)) continue;
seen.add(row.id);
// Lower the score for each edit step away from the query so
// exact-match fallbacks (dist 0) outrank dist-2 typos.
results.push({ node: rowToNode(row), score: 1 / (1 + c.dist) });
if (results.length >= limit) break;
}
}
return results;
}
/**
* FTS5 search with prefix matching
*/
private searchNodesFTS(query: string, options: SearchOptions): SearchResult[] {
const { kinds, languages, limit = 100, offset = 0 } = options;
// Add prefix wildcard for better matching (e.g., "auth" matches "AuthService", "authenticate")
// Escape special FTS5 characters and add prefix wildcard
const ftsQuery = query
.replace(/['"*():^]/g, '') // Remove FTS5 special chars
.split(/\s+/)
.filter(term => term.length > 0)
// Strip FTS5 boolean operators to prevent query manipulation
.filter(term => !/^(AND|OR|NOT|NEAR)$/i.test(term))
.map(term => `"${term}"*`) // Prefix match each term
.join(' OR ');
if (!ftsQuery) {
return [];
}
// BM25 column weights: id=0, name=20, qualified_name=5, docstring=1, signature=2
// Heavy name weight ensures exact/prefix name matches rank above incidental
// mentions in long docstrings or qualified names of nested symbols.
// Fetch 5x requested limit so post-hoc rescoring (kindBonus, pathRelevance,
// nameMatchBonus) can promote results that BM25 alone undervalues.
const ftsLimit = Math.max(limit * 5, 100);
let sql = `
SELECT nodes.*, bm25(nodes_fts, 0, 20, 5, 1, 2) as score
FROM nodes_fts
JOIN nodes ON nodes_fts.id = nodes.id
WHERE nodes_fts MATCH ?
`;
const params: (string | number)[] = [ftsQuery];
if (kinds && kinds.length > 0) {
sql += ` AND nodes.kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND nodes.language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
sql += ' ORDER BY score LIMIT ? OFFSET ?';
params.push(ftsLimit, offset);
try {
const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
return rows.map((row) => ({
node: rowToNode(row),
score: Math.abs(row.score), // bm25 returns negative scores
}));
} catch {
// FTS query failed, return empty
return [];
}
}
/**
* LIKE-based substring search for cases where FTS doesn't match
* Useful for camelCase matching (e.g., "signIn" finds "signInWithGoogle")
*/
private searchNodesLike(query: string, options: SearchOptions): SearchResult[] {
const { kinds, languages, limit = 100, offset = 0 } = options;
let sql = `
SELECT nodes.*,
CASE
WHEN name = ? THEN 1.0
WHEN name LIKE ? THEN 0.9
WHEN name LIKE ? THEN 0.8
WHEN qualified_name LIKE ? THEN 0.7
ELSE 0.5
END as score
FROM nodes
WHERE (
name LIKE ? OR
qualified_name LIKE ? OR
name LIKE ?
)
`;
// Pattern variants for better matching
const exactMatch = query;
const startsWith = `${query}%`;
const contains = `%${query}%`;
const params: (string | number)[] = [
exactMatch, // Exact match score
startsWith, // Starts with score
contains, // Contains score
contains, // Qualified name score
contains, // WHERE: name contains
contains, // WHERE: qualified_name contains
startsWith, // WHERE: name starts with
];
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
sql += ' ORDER BY score DESC, length(name) ASC LIMIT ? OFFSET ?';
params.push(limit, offset);
const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
return rows.map((row) => ({
node: rowToNode(row),
score: row.score,
}));
}
/**
* Find nodes by exact name match
*
* Used for hybrid search - looks up symbols by exact name or case-insensitive match.
* Returns high-confidence matches for known symbol names extracted from query.
*
* @param names - Array of symbol names to look up
* @param options - Search options (kinds, languages, limit)
* @returns SearchResult array with exact matches scored at 1.0
*/
findNodesByExactName(names: string[], options: SearchOptions = {}): SearchResult[] {
if (names.length === 0) return [];
const { kinds, languages, limit = 50 } = options;
// Two-pass approach to handle common names (e.g., "run" has 40+ matches):
// Pass 1: Find which files contain distinctive (rare) symbols from the query.
// Pass 2: Query each name, boosting results that co-locate with distinctive symbols.
// Pass 1: Find files containing each queried name, identify distinctive names
const nameToFiles = new Map<string, Set<string>>();
for (const name of names) {
let sql = 'SELECT DISTINCT file_path FROM nodes WHERE name COLLATE NOCASE = ?';
const params: (string | number)[] = [name];
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
sql += ' LIMIT 100';
const rows = this.db.prepare(sql).all(...params) as { file_path: string }[];
nameToFiles.set(name.toLowerCase(), new Set(rows.map(r => r.file_path)));
}
// Distinctive names are those with fewer than 10 file matches (e.g., "scrapeLoop" = 1 file)
const distinctiveFiles = new Set<string>();
for (const [, files] of nameToFiles) {
if (files.size > 0 && files.size < 10) {
for (const f of files) distinctiveFiles.add(f);
}
}
// Pass 2: Query each name with per-name limit, scoring by co-location
const perNameLimit = Math.max(8, Math.ceil(limit / names.length));
const allResults: SearchResult[] = [];
const seenIds = new Set<string>();
for (const name of names) {
let sql = `
SELECT nodes.*, 1.0 as score
FROM nodes
WHERE name COLLATE NOCASE = ?
`;
const params: (string | number)[] = [name];
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
// Fetch enough to find co-located results among common names
sql += ' LIMIT ?';
params.push(Math.max(perNameLimit * 3, 50));
const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
const nameResults: SearchResult[] = [];
for (const row of rows) {
const node = rowToNode(row);
if (seenIds.has(node.id)) continue;
// Boost results in files that also contain distinctive symbols
const coLocationBoost = distinctiveFiles.has(node.filePath) ? 20 : 0;
nameResults.push({ node, score: row.score + coLocationBoost });
}
// Sort by score (co-located first), take per-name limit
nameResults.sort((a, b) => b.score - a.score);
for (const r of nameResults.slice(0, perNameLimit)) {
seenIds.add(r.node.id);
allResults.push(r);
}
}
// Sort all results by score so co-located results bubble up
allResults.sort((a, b) => b.score - a.score);
return allResults.slice(0, limit);
}
/**
* Find nodes whose name contains a substring (LIKE-based).
* Useful for CamelCase-part matching where FTS fails because
* e.g. "TransportSearchAction" is one FTS token, not matchable by "Search"*.
*
* Results are ordered by name length (shorter = more likely to be the core type).
*/
findNodesByNameSubstring(
substring: string,
options: SearchOptions & { excludePrefix?: boolean } = {}
): SearchResult[] {
const { kinds, languages, limit = 30, excludePrefix } = options;
let sql = `
SELECT nodes.*, 1.0 as score
FROM nodes
WHERE name LIKE ?
`;
const params: (string | number)[] = [`%${substring}%`];
// Exclude prefix matches (handled by FTS-based prefix search in Step 2b)
if (excludePrefix) {
sql += ` AND name NOT LIKE ?`;
params.push(`${substring}%`);
}
if (kinds && kinds.length > 0) {
sql += ` AND kind IN (${kinds.map(() => '?').join(',')})`;
params.push(...kinds);
}
if (languages && languages.length > 0) {
sql += ` AND language IN (${languages.map(() => '?').join(',')})`;
params.push(...languages);
}
sql += ' ORDER BY length(name) ASC LIMIT ?';
params.push(limit);
const rows = this.db.prepare(sql).all(...params) as (NodeRow & { score: number })[];
return rows.map((row) => ({
node: rowToNode(row),
score: row.score,
}));
}
// ===========================================================================
// Edge Operations
// ===========================================================================
/**
* Insert a new edge
*/
insertEdge(edge: Edge): void {
if (!this.stmts.insertEdge) {
this.stmts.insertEdge = this.db.prepare(`
INSERT OR IGNORE INTO edges (source, target, kind, metadata, line, col, provenance)
VALUES (@source, @target, @kind, @metadata, @line, @col, @provenance)
`);
}
this.stmts.insertEdge.run({
source: edge.source,
target: edge.target,
kind: edge.kind,
metadata: edge.metadata ? JSON.stringify(edge.metadata) : null,
line: edge.line ?? null,
col: edge.column ?? null,
provenance: edge.provenance ?? null,
});
}
/**
* Insert multiple edges in a transaction
*/
insertEdges(edges: Edge[]): void {
this.db.transaction(() => {
for (const edge of edges) {
this.insertEdge(edge);
}
})();
}
/**
* Delete all edges from a source node
*/
deleteEdgesBySource(sourceId: string): void {
if (!this.stmts.deleteEdgesBySource) {
this.stmts.deleteEdgesBySource = this.db.prepare('DELETE FROM edges WHERE source = ?');
}
this.stmts.deleteEdgesBySource.run(sourceId);
}
/**
* Get outgoing edges from a node
*/