-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathsearch.ts
More file actions
1189 lines (1033 loc) · 37.7 KB
/
search.ts
File metadata and controls
1189 lines (1033 loc) · 37.7 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
/**
* Hybrid search combining semantic vector search with keyword matching
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import Fuse from 'fuse.js';
import path from 'path';
import { promises as fs } from 'fs';
import { CodeChunk, SearchResult, SearchFilters } from '../types/index.js';
import { EmbeddingProvider, getEmbeddingProvider } from '../embeddings/index.js';
import { VectorStorageProvider, getStorageProvider } from '../storage/index.js';
import { analyzerRegistry } from './analyzer-registry.js';
import { IndexCorruptedError } from '../errors/index.js';
import { isTestingRelatedQuery } from '../preflight/query-scope.js';
import { assessSearchQuality } from './search-quality.js';
import { rerank } from './reranker.js';
import { type IndexMeta, readIndexMeta, validateIndexArtifacts } from './index-meta.js';
import {
CODEBASE_CONTEXT_DIRNAME,
INTELLIGENCE_FILENAME,
KEYWORD_INDEX_FILENAME,
VECTOR_DB_DIRNAME
} from '../constants/codebase-context.js';
export interface SearchOptions {
useSemanticSearch?: boolean;
useKeywordSearch?: boolean;
semanticWeight?: number;
keywordWeight?: number;
profile?: SearchIntentProfile;
enableQueryExpansion?: boolean;
enableLowConfidenceRescue?: boolean;
candidateFloor?: number;
/** Enable stage-2 cross-encoder reranking when top scores are ambiguous. Default: true. */
enableReranker?: boolean;
}
export type SearchIntentProfile = 'explore' | 'edit' | 'refactor' | 'migrate';
type QueryIntent = 'EXACT_NAME' | 'CONCEPTUAL' | 'FLOW' | 'CONFIG' | 'WIRING';
interface QueryVariant {
query: string;
weight: number;
}
interface IntentWeights {
semantic: number;
keyword: number;
}
const DEFAULT_SEARCH_OPTIONS: SearchOptions = {
useSemanticSearch: true,
useKeywordSearch: true,
// semanticWeight/keywordWeight intentionally omitted —
// intent classification provides per-query weights.
// Callers can still override by passing explicit values.
profile: 'explore',
enableQueryExpansion: true,
enableLowConfidenceRescue: true,
candidateFloor: 30,
enableReranker: true
};
const QUERY_EXPANSION_HINTS: Array<{ pattern: RegExp; terms: string[] }> = [
{
pattern: /\b(auth|authentication|login|signin|sign-in|session|token|oauth)\b/i,
terms: ['auth', 'login', 'token', 'session', 'guard', 'oauth']
},
{
pattern: /\b(route|routes|routing|router|navigate|navigation|redirect|path)\b/i,
terms: ['router', 'route', 'navigation', 'redirect', 'path']
},
{
pattern: /\b(config|configuration|configure|setup|register|provider|providers|bootstrap)\b/i,
terms: ['config', 'setup', 'register', 'provider', 'bootstrap']
},
{
pattern: /\b(role|roles|permission|permissions|authorization|authorisation|access)\b/i,
terms: ['roles', 'permissions', 'access', 'policy', 'guard']
},
{
pattern: /\b(interceptor|middleware|request|response|http)\b/i,
terms: ['interceptor', 'middleware', 'http', 'request', 'response']
},
{
pattern: /\b(theme|styles?|styling|palette|color|branding|upload)\b/i,
terms: ['theme', 'styles', 'palette', 'color', 'branding', 'upload']
}
];
const QUERY_STOP_WORDS = new Set([
'the',
'a',
'an',
'to',
'of',
'for',
'and',
'or',
'with',
'in',
'on',
'by',
'how',
'are',
'is',
'after',
'before'
]);
export class CodebaseSearcher {
private rootPath: string;
private storagePath: string;
private indexMeta: IndexMeta | null = null;
private fuseIndex: Fuse<CodeChunk> | null = null;
private chunks: CodeChunk[] = [];
private embeddingProvider: EmbeddingProvider | null = null;
private storageProvider: VectorStorageProvider | null = null;
private initialized = false;
// Pattern intelligence for trend detection
private patternIntelligence: {
decliningPatterns: Set<string>;
risingPatterns: Set<string>;
patternWarnings: Map<string, string>;
} | null = null;
private importCentrality: Map<string, number> | null = null;
constructor(rootPath: string) {
this.rootPath = rootPath;
this.storagePath = path.join(rootPath, CODEBASE_CONTEXT_DIRNAME, VECTOR_DB_DIRNAME);
}
async initialize(): Promise<void> {
if (this.initialized) return;
try {
// Fail closed on version mismatch/corruption before serving any results.
this.indexMeta = await readIndexMeta(this.rootPath);
await validateIndexArtifacts(this.rootPath, this.indexMeta);
await this.loadKeywordIndex();
await this.loadPatternIntelligence();
this.embeddingProvider = await getEmbeddingProvider();
this.storageProvider = await getStorageProvider({
path: this.storagePath
});
this.initialized = true;
} catch (error) {
if (error instanceof IndexCorruptedError) {
throw error; // Propagate to handler for auto-heal
}
console.warn('Partial initialization (keyword search only):', error);
this.initialized = true;
}
}
private async loadKeywordIndex(): Promise<void> {
try {
const indexPath = path.join(this.rootPath, CODEBASE_CONTEXT_DIRNAME, KEYWORD_INDEX_FILENAME);
const content = await fs.readFile(indexPath, 'utf-8');
const parsed = JSON.parse(content) as any;
if (Array.isArray(parsed)) {
throw new IndexCorruptedError(
'Legacy keyword index format detected (missing header). Rebuild required.'
);
}
const chunks = parsed && Array.isArray(parsed.chunks) ? parsed.chunks : null;
if (!chunks) {
throw new IndexCorruptedError('Keyword index corrupted: expected { header, chunks }');
}
this.chunks = chunks;
this.fuseIndex = new Fuse(this.chunks, {
keys: [
{ name: 'content', weight: 0.4 },
{ name: 'metadata.componentName', weight: 0.25 },
{ name: 'filePath', weight: 0.15 },
{ name: 'relativePath', weight: 0.15 },
{ name: 'componentType', weight: 0.15 },
{ name: 'layer', weight: 0.1 },
{ name: 'tags', weight: 0.15 }
],
includeScore: true,
threshold: 0.4,
useExtendedSearch: true,
ignoreLocation: true
});
} catch (error) {
if (error instanceof IndexCorruptedError) {
throw error;
}
throw new IndexCorruptedError(
`Keyword index load failed (rebuild required): ${error instanceof Error ? error.message : String(error)}`
);
}
}
/**
* Load pattern intelligence for trend detection and warnings
*/
private async loadPatternIntelligence(): Promise<void> {
try {
const intelligencePath = path.join(
this.rootPath,
CODEBASE_CONTEXT_DIRNAME,
INTELLIGENCE_FILENAME
);
const content = await fs.readFile(intelligencePath, 'utf-8');
const intelligence = JSON.parse(content);
const decliningPatterns = new Set<string>();
const risingPatterns = new Set<string>();
const patternWarnings = new Map<string, string>();
// Extract pattern indicators from intelligence data
if (intelligence.patterns) {
for (const [_category, data] of Object.entries(intelligence.patterns)) {
const patternData = data as any;
// Track primary pattern
if (patternData.primary?.trend === 'Rising') {
risingPatterns.add(patternData.primary.name.toLowerCase());
}
// Track declining alternatives
if (patternData.alsoDetected) {
for (const alt of patternData.alsoDetected) {
if (alt.trend === 'Declining') {
decliningPatterns.add(alt.name.toLowerCase());
patternWarnings.set(
alt.name.toLowerCase(),
`WARNING: Uses declining pattern: ${alt.name} (${alt.guidance || 'consider modern alternatives'})`
);
} else if (alt.trend === 'Rising') {
risingPatterns.add(alt.name.toLowerCase());
}
}
}
}
}
this.patternIntelligence = { decliningPatterns, risingPatterns, patternWarnings };
console.error(
`[search] Loaded pattern intelligence: ${decliningPatterns.size} declining, ${risingPatterns.size} rising patterns`
);
this.importCentrality = new Map<string, number>();
if (intelligence.internalFileGraph && intelligence.internalFileGraph.imports) {
// Count how many files import each file (in-degree centrality)
const importCounts = new Map<string, number>();
for (const [_importingFile, importedFiles] of Object.entries(
intelligence.internalFileGraph.imports
)) {
const imports = importedFiles as string[];
for (const imported of imports) {
importCounts.set(imported, (importCounts.get(imported) || 0) + 1);
}
}
// Normalize centrality to 0-1 range
const maxImports = Math.max(...Array.from(importCounts.values()), 1);
for (const [file, count] of importCounts) {
this.importCentrality.set(file, count / maxImports);
}
console.error(`[search] Computed import centrality for ${importCounts.size} files`);
}
} catch (error) {
console.warn(
'Pattern intelligence load failed (will proceed without trend detection):',
error
);
this.patternIntelligence = null;
this.importCentrality = null;
}
}
/**
* Detect pattern trend from chunk content
*/
private detectChunkTrend(chunk: CodeChunk): {
trend: 'Rising' | 'Stable' | 'Declining' | undefined;
warning?: string;
} {
if (!this.patternIntelligence || chunk.content == null) {
return { trend: undefined };
}
const content = chunk.content.toLowerCase();
const { decliningPatterns, risingPatterns, patternWarnings } = this.patternIntelligence;
// Check for declining patterns
for (const pattern of decliningPatterns) {
if (content.includes(pattern)) {
return {
trend: 'Declining',
warning: patternWarnings.get(pattern)
};
}
}
// Check for rising patterns
for (const pattern of risingPatterns) {
if (content.includes(pattern)) {
return { trend: 'Rising' };
}
}
return { trend: 'Stable' };
}
private isTestFile(filePath: string): boolean {
const normalized = filePath.toLowerCase().replace(/\\/g, '/');
return (
normalized.includes('.spec.') ||
normalized.includes('.test.') ||
normalized.includes('/e2e/') ||
normalized.includes('/__tests__/')
);
}
private normalizeQueryTerms(query: string): string[] {
return query
.toLowerCase()
.split(/[^a-z0-9_]+/)
.filter((term) => term.length > 2 && !QUERY_STOP_WORDS.has(term));
}
/**
* Classify query intent based on heuristic patterns
*/
private classifyQueryIntent(query: string): { intent: QueryIntent; weights: IntentWeights } {
const lowerQuery = query.toLowerCase();
// EXACT_NAME: Contains PascalCase or camelCase tokens (literal class/component names)
if (/[A-Z][a-z]+[A-Z]/.test(query) || /[a-z][A-Z]/.test(query)) {
return {
intent: 'EXACT_NAME',
weights: { semantic: 0.4, keyword: 0.6 } // Keyword search dominates for exact names
};
}
// CONFIG: Configuration/setup queries
const configKeywords = [
'config',
'setup',
'routing',
'providers',
'configuration',
'bootstrap'
];
if (configKeywords.some((kw) => lowerQuery.includes(kw))) {
return {
intent: 'CONFIG',
weights: { semantic: 0.5, keyword: 0.5 } // Balanced
};
}
// WIRING: DI/registration queries
const wiringKeywords = [
'provide',
'inject',
'dependency',
'register',
'wire',
'bootstrap',
'module'
];
if (wiringKeywords.some((kw) => lowerQuery.includes(kw))) {
return {
intent: 'WIRING',
weights: { semantic: 0.5, keyword: 0.5 } // Balanced
};
}
// FLOW: Action/navigation queries
const flowVerbs = [
'navigate',
'redirect',
'route',
'handle',
'process',
'execute',
'trigger',
'dispatch'
];
if (flowVerbs.some((verb) => lowerQuery.includes(verb))) {
return {
intent: 'FLOW',
weights: { semantic: 0.6, keyword: 0.4 } // Semantic helps with flow understanding
};
}
// CONCEPTUAL: Natural language without code tokens (default)
return {
intent: 'CONCEPTUAL',
weights: { semantic: 0.7, keyword: 0.3 } // Semantic dominates for concepts
};
}
private buildQueryVariants(query: string, maxExpansions: number): QueryVariant[] {
const variants: QueryVariant[] = [{ query, weight: 1 }];
if (maxExpansions <= 0) return variants;
const normalized = query.toLowerCase();
const terms = new Set(this.normalizeQueryTerms(query));
for (const hint of QUERY_EXPANSION_HINTS) {
if (!hint.pattern.test(query)) continue;
for (const term of hint.terms) {
if (!normalized.includes(term)) {
terms.add(term);
}
}
}
const addedTerms = Array.from(terms).filter((term) => !normalized.includes(term));
if (addedTerms.length === 0) return variants;
const firstExpansion = `${query} ${addedTerms.slice(0, 6).join(' ')}`.trim();
if (firstExpansion !== query) {
variants.push({ query: firstExpansion, weight: 0.35 });
}
if (maxExpansions > 1 && addedTerms.length > 6) {
const secondExpansion = `${query} ${addedTerms.slice(6, 12).join(' ')}`.trim();
if (secondExpansion !== query) {
variants.push({ query: secondExpansion, weight: 0.25 });
}
}
return variants.slice(0, 1 + maxExpansions);
}
private isTemplateOrStyleFile(filePath: string): boolean {
const ext = path.extname(filePath).toLowerCase();
return ['.html', '.scss', '.css', '.less', '.sass', '.styl'].includes(ext);
}
private isCompositionRootFile(filePath: string): boolean {
const normalized = filePath.toLowerCase().replace(/\\/g, '/');
const base = path.basename(normalized);
if (/^(main|index|bootstrap|startup)\./.test(base)) return true;
return (
normalized.includes('/routes') ||
normalized.includes('/routing') ||
normalized.includes('/router') ||
normalized.includes('/config') ||
normalized.includes('/providers')
);
}
private queryPathTokenOverlap(filePath: string, query: string): number {
const queryTerms = new Set(this.normalizeQueryTerms(query));
if (queryTerms.size === 0) return 0;
const pathTerms = this.normalizeQueryTerms(filePath.replace(/\\/g, '/'));
return pathTerms.reduce((count, term) => (queryTerms.has(term) ? count + 1 : count), 0);
}
private isLikelyWiringOrFlowQuery(query: string): boolean {
return /\b(route|router|routing|navigate|navigation|redirect|auth|authentication|login|provider|register|config|configuration|interceptor|middleware)\b/i.test(
query
);
}
private isActionOrHowQuery(query: string): boolean {
return /\b(how|where|configure|configured|setup|register|wire|wiring|navigate|redirect|login|authenticate|copy|upload|handle|create|update|delete)\b/i.test(
query
);
}
private isDefinitionHeavyResult(chunk: CodeChunk): boolean {
const normalizedPath = chunk.filePath.toLowerCase().replace(/\\/g, '/');
const componentType = (chunk.componentType || '').toLowerCase();
if (['type', 'interface', 'enum', 'constant'].includes(componentType)) return true;
return (
normalizedPath.includes('/models/') ||
normalizedPath.includes('/interfaces/') ||
normalizedPath.includes('/types/') ||
normalizedPath.includes('/constants')
);
}
private scoreAndSortResults(
query: string,
limit: number,
results: {
semantic: Map<string, { chunk: CodeChunk; ranks: Array<{ rank: number; weight: number }> }>;
keyword: Map<string, { chunk: CodeChunk; ranks: Array<{ rank: number; weight: number }> }>;
},
profile: SearchIntentProfile,
intent: QueryIntent,
totalVariantWeight: number
): SearchResult[] {
const likelyWiringQuery = this.isLikelyWiringOrFlowQuery(query);
const actionQuery = this.isActionOrHowQuery(query);
// RRF: k=60 is the standard parameter (proven robust in Elasticsearch + TOSS paper arXiv:2208.11274)
const RRF_K = 60;
// Collect all unique chunks from both retrieval channels
const allChunks = new Map<string, CodeChunk>();
const rrfScores = new Map<string, number>();
// Gather all chunks
for (const [id, entry] of results.semantic) {
allChunks.set(id, entry.chunk);
}
for (const [id, entry] of results.keyword) {
if (!allChunks.has(id)) {
allChunks.set(id, entry.chunk);
}
}
// Calculate RRF scores: RRF(d) = SUM(weight_i / (k + rank_i))
for (const [id] of allChunks) {
let rrfScore = 0;
// Add contributions from semantic ranks
const semanticEntry = results.semantic.get(id);
if (semanticEntry) {
for (const { rank, weight } of semanticEntry.ranks) {
rrfScore += weight / (RRF_K + rank);
}
}
// Add contributions from keyword ranks
const keywordEntry = results.keyword.get(id);
if (keywordEntry) {
for (const { rank, weight } of keywordEntry.ranks) {
rrfScore += weight / (RRF_K + rank);
}
}
rrfScores.set(id, rrfScore);
}
// Normalize by theoretical maximum (rank-0 in every list), NOT by actual max.
// Using actual max makes top result always 1.0, breaking quality confidence gating.
const theoreticalMaxRrf = totalVariantWeight / (RRF_K + 0);
const maxRrfScore = Math.max(theoreticalMaxRrf, 0.01);
// Separate test files from implementation files before scoring
const isNonTestQuery = !isTestingRelatedQuery(query);
const implementationChunks: Array<[string, CodeChunk]> = [];
const testChunks: Array<[string, CodeChunk]> = [];
for (const [id, chunk] of allChunks.entries()) {
if (this.isTestFile(chunk.filePath)) {
testChunks.push([id, chunk]);
} else {
implementationChunks.push([id, chunk]);
}
}
// For non-test queries: filter test files from candidate pool, keep max 1 test file only if < 3 implementation matches
const chunksToScore = isNonTestQuery ? implementationChunks : Array.from(allChunks.entries());
const scoredResults = chunksToScore
.map(([id, chunk]) => {
// RRF score normalized to [0,1] range. Boosts below are unclamped
// to preserve score differentiation — only relative ordering matters.
let combinedScore = rrfScores.get(id)! / maxRrfScore;
// Slight boost when analyzer identified a concrete component type
if (chunk.componentType && chunk.componentType !== 'unknown') {
combinedScore *= 1.1;
}
// Boost if layer is detected
if (chunk.layer && chunk.layer !== 'unknown') {
combinedScore *= 1.1;
}
if (actionQuery && this.isDefinitionHeavyResult(chunk)) {
combinedScore *= 0.82;
}
if (
actionQuery &&
['service', 'component', 'interceptor', 'guard', 'module', 'resolver'].includes(
(chunk.componentType || '').toLowerCase()
)
) {
combinedScore *= 1.06;
}
// Demote template/style files for behavioral queries — they describe
// structure/presentation, not implementation logic.
if (
(intent === 'FLOW' || intent === 'WIRING' || actionQuery) &&
this.isTemplateOrStyleFile(chunk.filePath)
) {
combinedScore *= 0.75;
}
// Light intent-aware boost for likely wiring/configuration queries.
if (likelyWiringQuery && profile !== 'explore') {
if (this.isCompositionRootFile(chunk.filePath)) {
combinedScore *= 1.12;
}
}
if (intent === 'FLOW') {
// Boost service/guard/interceptor files for action/navigation queries
if (
['service', 'guard', 'interceptor', 'middleware'].includes(
(chunk.componentType || '').toLowerCase()
)
) {
combinedScore *= 1.15;
}
} else if (intent === 'CONFIG') {
// Boost composition-root files for configuration queries
if (this.isCompositionRootFile(chunk.filePath)) {
combinedScore *= 1.2;
}
} else if (intent === 'WIRING') {
// Boost DI/module files for wiring queries
if (
['module', 'provider', 'config'].some((type) =>
(chunk.componentType || '').toLowerCase().includes(type)
)
) {
combinedScore *= 1.18;
}
if (this.isCompositionRootFile(chunk.filePath)) {
combinedScore *= 1.22;
}
}
const pathOverlap = this.queryPathTokenOverlap(chunk.filePath, query);
if (pathOverlap >= 2) {
combinedScore *= 1.08;
}
if (this.importCentrality) {
const normalizedRoot = this.rootPath.replace(/\\/g, '/').replace(/\/?$/, '/');
const normalizedPath = chunk.filePath.replace(/\\/g, '/').replace(normalizedRoot, '');
const centrality = this.importCentrality.get(normalizedPath);
if (centrality !== undefined && centrality > 0.1) {
// Boost files with high centrality (many imports)
const centralityBoost = 1.0 + centrality * 0.15; // Up to +15% for max centrality
combinedScore *= centralityBoost;
}
}
// Detect pattern trend and apply momentum boost
const { trend, warning } = this.detectChunkTrend(chunk);
if (trend === 'Rising') {
combinedScore *= 1.15; // +15% for modern patterns
} else if (trend === 'Declining') {
combinedScore *= 0.9; // -10% for legacy patterns
}
const summary = this.generateSummary(chunk);
const snippet = this.generateSnippet(chunk.content ?? '');
return {
summary,
snippet,
filePath: chunk.filePath,
startLine: chunk.startLine,
endLine: chunk.endLine,
score: combinedScore,
relevanceReason: this.generateRelevanceReason(chunk, query),
language: chunk.language,
framework: chunk.framework,
componentType: chunk.componentType,
layer: chunk.layer,
metadata: chunk.metadata,
trend,
patternWarning: warning
} as SearchResult;
})
.sort((a, b) => b.score - a.score);
// SEARCH-01: Definition-first boost for EXACT_NAME intent
// Boost results where symbolName matches query (case-insensitive)
if (intent === 'EXACT_NAME') {
const queryNormalized = query.toLowerCase();
for (const result of scoredResults) {
const symbolName = result.metadata?.symbolName;
if (symbolName && symbolName.toLowerCase() === queryNormalized) {
result.score *= 1.15; // +15% boost for definition
}
}
// Re-sort after boost
scoredResults.sort((a, b) => b.score - a.score);
}
// File-level deduplication
const seenFiles = new Set<string>();
const deduped: SearchResult[] = [];
for (const result of scoredResults) {
const normalizedPath = result.filePath.toLowerCase().replace(/\\/g, '/');
if (seenFiles.has(normalizedPath)) continue;
seenFiles.add(normalizedPath);
deduped.push(result);
if (deduped.length >= limit) break;
}
// SEARCH-01: Symbol-level deduplication
// Within each symbol group (symbolPath), keep only the highest-scoring chunk
const seenSymbols = new Map<string, SearchResult>();
const symbolDeduped: SearchResult[] = [];
for (const result of deduped) {
const symbolPath = result.metadata?.symbolPath;
if (!symbolPath) {
// No symbol info, keep as-is
symbolDeduped.push(result);
continue;
}
const symbolPathKey = Array.isArray(symbolPath) ? symbolPath.join('.') : String(symbolPath);
const existing = seenSymbols.get(symbolPathKey);
if (!existing || result.score > existing.score) {
if (existing) {
// Replace lower-scoring version
const idx = symbolDeduped.indexOf(existing);
if (idx >= 0) {
symbolDeduped[idx] = result;
}
} else {
symbolDeduped.push(result);
}
seenSymbols.set(symbolPathKey, result);
}
}
const finalResults = symbolDeduped;
if (
isNonTestQuery &&
finalResults.length < 3 &&
finalResults.length < limit &&
testChunks.length > 0
) {
// Find the highest-scoring test file
const bestTestChunk = testChunks
.map(([id, chunk]) => ({
id,
chunk,
score: rrfScores.get(id)! / maxRrfScore
}))
.sort((a, b) => b.score - a.score)[0];
if (bestTestChunk) {
const { trend, warning } = this.detectChunkTrend(bestTestChunk.chunk);
const summary = this.generateSummary(bestTestChunk.chunk);
const snippet = this.generateSnippet(bestTestChunk.chunk.content ?? '');
finalResults.push({
summary,
snippet,
filePath: bestTestChunk.chunk.filePath,
startLine: bestTestChunk.chunk.startLine,
endLine: bestTestChunk.chunk.endLine,
score: bestTestChunk.score * 0.5, // Demote below implementation files
relevanceReason:
this.generateRelevanceReason(bestTestChunk.chunk, query) + ' (test file)',
language: bestTestChunk.chunk.language,
framework: bestTestChunk.chunk.framework,
componentType: bestTestChunk.chunk.componentType,
layer: bestTestChunk.chunk.layer,
metadata: bestTestChunk.chunk.metadata,
trend,
patternWarning: warning
} as SearchResult);
}
}
return finalResults;
}
private pickBetterResultSet(
query: string,
primary: SearchResult[],
rescue: SearchResult[]
): SearchResult[] {
const primaryQuality = assessSearchQuality(query, primary);
const rescueQuality = assessSearchQuality(query, rescue);
if (
rescueQuality.status === 'ok' &&
primaryQuality.status === 'low_confidence' &&
rescueQuality.confidence >= primaryQuality.confidence
) {
return rescue;
}
if (rescueQuality.confidence >= primaryQuality.confidence + 0.05) {
return rescue;
}
return primary;
}
private async collectHybridMatches(
queryVariants: QueryVariant[],
candidateLimit: number,
filters: SearchFilters | undefined,
useSemanticSearch: boolean,
useKeywordSearch: boolean,
semanticWeight: number,
keywordWeight: number
): Promise<{
semantic: Map<string, { chunk: CodeChunk; ranks: Array<{ rank: number; weight: number }> }>;
keyword: Map<string, { chunk: CodeChunk; ranks: Array<{ rank: number; weight: number }> }>;
}> {
const semanticRanks: Map<
string,
{ chunk: CodeChunk; ranks: Array<{ rank: number; weight: number }> }
> = new Map();
const keywordRanks: Map<
string,
{ chunk: CodeChunk; ranks: Array<{ rank: number; weight: number }> }
> = new Map();
// RRF uses ranks instead of scores for fusion robustness
if (useSemanticSearch && this.embeddingProvider && this.storageProvider) {
try {
for (const variant of queryVariants) {
const vectorResults = await this.semanticSearch(variant.query, candidateLimit, filters);
// Assign ranks based on retrieval order (0-indexed)
vectorResults.forEach((result, index) => {
const id = result.chunk.id;
const rank = index; // 0-indexed rank
const weight = semanticWeight * variant.weight;
const existing = semanticRanks.get(id);
if (existing) {
existing.ranks.push({ rank, weight });
} else {
semanticRanks.set(id, {
chunk: result.chunk,
ranks: [{ rank, weight }]
});
}
});
}
} catch (error) {
if (error instanceof IndexCorruptedError) {
throw error; // Propagate to handler for auto-heal
}
console.warn('Semantic search failed:', error);
}
}
if (useKeywordSearch && this.fuseIndex) {
try {
for (const variant of queryVariants) {
const keywordResults = await this.keywordSearch(variant.query, candidateLimit, filters);
// Assign ranks based on retrieval order (0-indexed)
keywordResults.forEach((result, index) => {
const id = result.chunk.id;
const rank = index; // 0-indexed rank
const weight = keywordWeight * variant.weight;
const existing = keywordRanks.get(id);
if (existing) {
existing.ranks.push({ rank, weight });
} else {
keywordRanks.set(id, {
chunk: result.chunk,
ranks: [{ rank, weight }]
});
}
});
}
} catch (error) {
console.warn('Keyword search failed:', error);
}
}
return { semantic: semanticRanks, keyword: keywordRanks };
}
async search(
query: string,
limit: number = 5,
filters?: SearchFilters,
options: SearchOptions = DEFAULT_SEARCH_OPTIONS
): Promise<SearchResult[]> {
if (!this.initialized) {
await this.initialize();
}
const merged = {
...DEFAULT_SEARCH_OPTIONS,
...options
};
const {
useSemanticSearch,
useKeywordSearch,
profile,
enableQueryExpansion,
enableLowConfidenceRescue,
candidateFloor,
enableReranker
} = merged;
const { intent, weights: intentWeights } = this.classifyQueryIntent(query);
// Intent weights are the default; caller-supplied weights override them
const finalSemanticWeight = merged.semanticWeight ?? intentWeights.semantic;
const finalKeywordWeight = merged.keywordWeight ?? intentWeights.keyword;
const candidateLimit = Math.max(limit * 2, candidateFloor || 30);
const primaryVariants = this.buildQueryVariants(query, enableQueryExpansion ? 1 : 0);
const primaryMatches = await this.collectHybridMatches(
primaryVariants,
candidateLimit,
filters,
Boolean(useSemanticSearch),
Boolean(useKeywordSearch),
finalSemanticWeight,
finalKeywordWeight
);
const primaryTotalWeight =
primaryVariants.reduce((sum, v) => sum + v.weight, 0) *
(finalSemanticWeight + finalKeywordWeight);
const primaryResults = this.scoreAndSortResults(
query,
limit,
primaryMatches,
(profile || 'explore') as SearchIntentProfile,
intent,
primaryTotalWeight
);
let bestResults = primaryResults;
if (enableLowConfidenceRescue) {
const primaryQuality = assessSearchQuality(query, primaryResults);
if (primaryQuality.status === 'low_confidence') {
const rescueVariants = this.buildQueryVariants(query, 2).slice(1);
if (rescueVariants.length > 0) {
const rescueMatches = await this.collectHybridMatches(
rescueVariants.map((variant, index) => ({
query: variant.query,
weight: index === 0 ? 1 : 0.8
})),
candidateLimit,
filters,
Boolean(useSemanticSearch),
Boolean(useKeywordSearch),
finalSemanticWeight,
finalKeywordWeight
);
const rescueVariantWeights = rescueVariants.map((_, i) => (i === 0 ? 1 : 0.8));
const rescueTotalWeight =
rescueVariantWeights.reduce((sum, w) => sum + w, 0) *
(finalSemanticWeight + finalKeywordWeight);
const rescueResults = this.scoreAndSortResults(
query,
limit,
rescueMatches,
(profile || 'explore') as SearchIntentProfile,
intent,
rescueTotalWeight
);
bestResults = this.pickBetterResultSet(query, primaryResults, rescueResults);
}
}
}
// Stage-2: cross-encoder reranking when top scores are ambiguous
if (enableReranker) {
try {
bestResults = await rerank(query, bestResults);
} catch (error) {
// Reranker is non-critical — log and return unranked results
console.warn('[reranker] Failed, returning original order:', error);
}
}