1+ import type { Reranker , RerankCandidate , RerankResult , RerankOptions } from './types' ;
2+
3+ // ---------------------------------------------------------------------------
4+ // Defaults
5+ // ---------------------------------------------------------------------------
6+
7+ const DEFAULT_WEIGHTS = {
8+ phraseWeight : 3.0 ,
9+ phraseRepeatBonus : 0.5 ,
10+ termWeight : 1.0 ,
11+ termRepeatBonus : 0.2 ,
12+ substringWeight : 0.3 ,
13+ headingTermBonus : 2.0 ,
14+ headingPhraseBonus : 2.5 ,
15+ originalScoreCarry : 0.1 ,
16+ } as const ;
17+
18+ // ---------------------------------------------------------------------------
19+ // KeywordReranker — lexical overlap scoring
20+ // ---------------------------------------------------------------------------
21+
22+ /**
23+ * Reranker that scores candidates by keyword / phrase overlap with the query.
24+ *
25+ * All scoring weights are configurable via constructor options.
26+ * Scores are normalised to [0, 1] via min-max scaling.
27+ */
28+ export class KeywordReranker implements Reranker {
29+ private readonly weights : Record < string , number > ;
30+
31+ constructor ( options ?: RerankOptions ) {
32+ this . weights = {
33+ phraseWeight : options ?. phraseWeight ?? DEFAULT_WEIGHTS . phraseWeight ,
34+ phraseRepeatBonus : options ?. phraseRepeatBonus ?? DEFAULT_WEIGHTS . phraseRepeatBonus ,
35+ termWeight : options ?. termWeight ?? DEFAULT_WEIGHTS . termWeight ,
36+ termRepeatBonus : options ?. termRepeatBonus ?? DEFAULT_WEIGHTS . termRepeatBonus ,
37+ substringWeight : options ?. substringWeight ?? DEFAULT_WEIGHTS . substringWeight ,
38+ headingTermBonus : options ?. headingTermBonus ?? DEFAULT_WEIGHTS . headingTermBonus ,
39+ headingPhraseBonus : options ?. headingPhraseBonus ?? DEFAULT_WEIGHTS . headingPhraseBonus ,
40+ originalScoreCarry : options ?. originalScoreCarry ?? DEFAULT_WEIGHTS . originalScoreCarry ,
41+ } ;
42+ }
43+
44+ async rerank ( query : string , candidates : RerankCandidate [ ] ) : Promise < RerankResult [ ] > {
45+ if ( candidates . length === 0 ) return [ ] ;
46+
47+ const queryLower = query . toLowerCase ( ) ;
48+ const queryTerms = tokenizeQuery ( queryLower ) ;
49+ const queryPhrase = queryLower . trim ( ) ;
50+ const w = this . weights ;
51+
52+ const scored = candidates . map ( ( c ) => {
53+ const contentLower = c . content . toLowerCase ( ) ;
54+ let score = 0 ;
55+
56+ // 1. Exact phrase match — strongest signal
57+ if ( contentLower . includes ( queryPhrase ) ) {
58+ score += w . phraseWeight ;
59+ const phraseCount = countOccurrences ( contentLower , queryPhrase ) ;
60+ score += ( phraseCount - 1 ) * w . phraseRepeatBonus ;
61+ }
62+
63+ // 2. Per-term matching
64+ for ( const term of queryTerms ) {
65+ if ( contentLower . includes ( term ) ) {
66+ if ( isWordBoundary ( contentLower , term ) ) {
67+ score += w . termWeight ;
68+ const termCount = countTermMatches ( contentLower , term ) ;
69+ score += ( termCount - 1 ) * w . termRepeatBonus ;
70+ } else {
71+ score += w . substringWeight ;
72+ }
73+ }
74+ }
75+
76+ // 3. Heading path bonus
77+ if ( c . headingPath ) {
78+ const headingLower = c . headingPath . toLowerCase ( ) ;
79+ for ( const term of queryTerms ) {
80+ if ( headingLower . includes ( term ) ) {
81+ score += w . headingTermBonus ;
82+ }
83+ }
84+ if ( queryPhrase . length > 2 && headingLower . includes ( queryPhrase ) ) {
85+ score += w . headingPhraseBonus ;
86+ }
87+ }
88+
89+ // 4. Carry over a fraction of the original vector score
90+ score += c . score * w . originalScoreCarry ;
91+
92+ return { id : c . id , score } ;
93+ } ) ;
94+
95+ // Min-max normalise to [0, 1]
96+ const scores = scored . map ( ( s ) => s . score ) ;
97+ const min = Math . min ( ...scores ) ;
98+ const max = Math . max ( ...scores ) ;
99+ const range = max - min || 1 ;
100+
101+ return scored . map ( ( s ) => ( {
102+ id : s . id ,
103+ score : ( s . score - min ) / range ,
104+ } ) ) ;
105+ }
106+ }
107+
108+ // ---------------------------------------------------------------------------
109+ // Helpers
110+ // ---------------------------------------------------------------------------
111+
112+ /** Split a query into meaningful tokens. */
113+ function tokenizeQuery ( query : string ) : string [ ] {
114+ const raw = query
115+ . split ( / [ \s , , 。 . ! ! ? ? 、 : : ; ; ] + / )
116+ . filter ( Boolean ) ;
117+
118+ const tokens : string [ ] = [ ] ;
119+ for ( const r of raw ) {
120+ tokens . push ( r ) ;
121+ if ( / [ 一 - 鿿 ] { 3 , } / . test ( r ) ) {
122+ for ( let i = 0 ; i + 2 <= r . length ; i ++ ) {
123+ tokens . push ( r . slice ( i , i + 2 ) ) ;
124+ }
125+ }
126+ }
127+ return [ ...new Set ( tokens ) ] ;
128+ }
129+
130+ /** Count non-overlapping occurrences of a substring. */
131+ function countOccurrences ( text : string , sub : string ) : number {
132+ let count = 0 ;
133+ let pos = 0 ;
134+ while ( ( pos = text . indexOf ( sub , pos ) ) !== - 1 ) {
135+ count ++ ;
136+ pos += sub . length ;
137+ }
138+ return count ;
139+ }
140+
141+ /** Count whole-word matches of a term. */
142+ function countTermMatches ( text : string , term : string ) : number {
143+ let count = 0 ;
144+ let pos = 0 ;
145+ while ( ( pos = text . indexOf ( term , pos ) ) !== - 1 ) {
146+ if ( isWordBoundary ( text , term , pos ) ) {
147+ count ++ ;
148+ }
149+ pos += term . length ;
150+ }
151+ return count ;
152+ }
153+
154+ /** Check if a substring occurrence is at a word boundary. */
155+ function isWordBoundary (
156+ text : string ,
157+ term : string ,
158+ pos ?: number ,
159+ ) : boolean {
160+ const idx = pos ?? text . indexOf ( term ) ;
161+ if ( idx === - 1 ) return false ;
162+ const before = idx === 0 || / [ \s \n . , ; : ! ? , 。 ! ? 、 : ; " ' ( ( 【 《 \- _ ] / . test ( text [ idx - 1 ] ) ;
163+ const afterIdx = idx + term . length ;
164+ const after = afterIdx >= text . length || / [ \s \n . , ; : ! ? , 。 ! ? 、 : ; " ' ) ) 】 》 \- _ ] / . test ( text [ afterIdx ] ) ;
165+ return before && after ;
166+ }
0 commit comments