@@ -6,245 +6,138 @@ import {
66 QueryOptions ,
77 QueryResult ,
88 Document ,
9+ LoadedDoc ,
910 LoadPhase ,
1011 LoadProgress ,
1112} from './types' ;
12- import { resolveEmbedder } from './embedder' ;
13- import type { Embedder , EmbedderInfo } from './embedder' ;
14- import { Loader , MarkdownLoader , JsonLoader , TextLoader } from './loaders' ;
13+ import { Embedder } from './embedder' ;
14+
15+ type EmbedderInfo = { dimensions : number } ;
16+ import { getLoader } from './loaders' ;
17+ import { pathToId } from './utils/doc' ;
1518import { Store } from './storage/store' ;
1619import type { ZvecDoc } from './storage/zvec-store' ;
17- import { pathToId } from './loaders/util' ;
1820import {
1921 createReranker ,
20- SynonymExpander ,
21- NoopExpander ,
22- safeParseMeta ,
22+ safeJsonParse ,
2323 computeContentHash ,
24- selectSampleFiles ,
24+ loadSampleText ,
2525} from './utils' ;
26- import type { Reranker , RerankCandidate , QueryExpander } from './utils' ;
26+ import { expand } from './expander' ;
27+ import type { Reranker , RerankCandidate } from './utils' ;
2728
2829// ---------------------------------------------------------------------------
2930// Context class
3031// ---------------------------------------------------------------------------
3132
3233export class Context {
33- private readonly basePath : string ;
34+ private readonly options : ContextOptions ;
3435 private readonly embedder : Embedder ;
35- private readonly _embedderInfo : EmbedderInfo ;
36+ readonly embedderInfo : EmbedderInfo ;
3637 private readonly store : Store ;
37- private readonly loaders : Loader [ ] ;
3838 private readonly reranker : Reranker | null ;
39- private readonly queryExpander : QueryExpander ;
40- private readonly _onProgress ?: ( phase : LoadPhase , detail : LoadProgress ) => void ;
4139
4240 private constructor ( options : ContextOptions , embedder : Embedder , embedderInfo : EmbedderInfo ) {
43- this . basePath = options . basePath ?? process . cwd ( ) ;
41+ this . options = {
42+ basePath : process . cwd ( ) ,
43+ vectorsDir : '.context/vectors' ,
44+ ...options ,
45+ } ;
4446 this . embedder = embedder ;
45- this . _embedderInfo = embedderInfo ;
46- this . store = new Store ( options . vectorsDir , embedder , options ) ;
47- this . loaders = [ new MarkdownLoader ( ) , new JsonLoader ( ) , new TextLoader ( ) ] ;
48- this . reranker = createReranker ( options . rerankWeights ) ;
49- this . queryExpander =
50- options . queryExpansion === false
51- ? new NoopExpander ( )
52- : new SynonymExpander (
53- options . queryExpansion && typeof options . queryExpansion === 'object'
54- ? options . queryExpansion . synonyms
55- : undefined ,
56- ) ;
57- this . _onProgress = options . onProgress ;
47+ this . embedderInfo = embedderInfo ;
48+ this . store = new Store ( this . options . vectorsDir ! , embedder , this . options ) ;
49+ this . reranker = createReranker ( this . options . rerankWeights ) ;
5850 }
5951
6052 static async create ( options : ContextOptions ) : Promise < Context > {
61- const result = await resolveEmbedder ( ) ;
62- const embedder = result . embedder ;
63- const embedderInfo = result . info ;
64-
65- // Ensure vectors directory exists
66- if ( ! fs . existsSync ( options . vectorsDir ) ) {
67- fs . mkdirSync ( options . vectorsDir , { recursive : true } ) ;
68- }
53+ const embedder = new Embedder ( ) ;
54+ await embedder . embed ( 'probe' ) ;
6955
70- const ctx = new Context ( options , embedder , embedderInfo ) ;
56+ const vectorsDir = options . vectorsDir ?? '.context/vectors' ;
7157
72- return ctx ;
73- }
74-
75- /**
76- * Diagnostic information about the active embedder.
77- */
78- get embedderInfo ( ) : EmbedderInfo {
79- return this . _embedderInfo ;
80- }
58+ if ( ! fs . existsSync ( vectorsDir ) ) {
59+ fs . mkdirSync ( vectorsDir , { recursive : true } ) ;
60+ }
8161
82- private getLoader ( filePath : string ) : Loader | undefined {
83- return this . loaders . find ( ( loader ) => loader . canHandle ( filePath ) ) ;
62+ return new Context ( options , embedder , { dimensions : embedder . dimensions } ) ;
8463 }
8564
86- /**
87- * Load documents into a library with automatic vectorization.
88- *
89- * Deduplication uses zvec's native document catalog as the single source
90- * of truth — already-loaded documents whose content hasn't changed
91- * (same contentHash) are skipped. No separate registry file is needed.
92- *
93- * @param library Library name for organizing documents.
94- * @param pattern Glob pattern(s) matching files to load.
95- */
9665 async load ( library : string , pattern : string | string [ ] ) : Promise < void > {
9766 const patterns = Array . isArray ( pattern ) ? pattern : [ pattern ] ;
9867 const files = await glob ( patterns , { absolute : true } ) ;
9968
100- // Sample multiple files for FTS tokenizer auto-detection.
101- let sampleText : string | undefined ;
102- if ( files . length > 0 ) {
103- try {
104- const sampleFiles = selectSampleFiles ( files , 5 ) ;
105- const samples = await Promise . allSettled (
106- sampleFiles . map ( ( f ) => fs . promises . readFile ( f , 'utf-8' ) ) ,
107- ) ;
108- const validSamples = samples
109- . filter ( ( r ) => r . status === 'fulfilled' )
110- . map ( ( r ) => ( r as PromiseFulfilledResult < string > ) . value ) ;
111- if ( validSamples . length > 0 ) {
112- sampleText = validSamples . join ( '\n' ) ;
113- }
114- } catch {
115- // Sample failure is non-fatal — fall back to default tokenizer
116- }
117- }
69+ const sampleText = await loadSampleText ( files ) ;
11870
11971 await this . store . create ( library , sampleText ) ;
12072
121- // Internal type that extends Document with load-phase metadata.
122- interface LoadedDoc extends Document {
123- id : string ;
124- contentHash : string ;
125- sourceFilePath : string ;
126- }
127-
128- // Phase 1: Load all files concurrently and collect candidates.
129- const loadSettled = await Promise . allSettled (
73+ const docs : LoadedDoc [ ] = await Promise . all (
13074 files . map ( async ( filePath ) => {
131- const loader = this . getLoader ( filePath ) ;
132- if ( ! loader ) return null ;
75+ const loader = getLoader ( filePath ) ;
76+ if ( ! loader ) throw new Error ( `No loader for ${ filePath } ` ) ;
13377
13478 const doc = await loader . load ( filePath ) ;
135- const relativePath = path . relative ( this . basePath , filePath ) ;
136- const docId = pathToId ( relativePath ) ;
137- const contentHash = computeContentHash ( doc . content ) ;
138-
139- return { ...doc , id : docId , contentHash, sourceFilePath : relativePath } ;
79+ const relativePath = path . relative ( this . options . basePath ! , filePath ) ;
80+ return {
81+ ...doc ,
82+ id : pathToId ( relativePath ) ,
83+ contentHash : computeContentHash ( doc . content ) ,
84+ path : relativePath ,
85+ } ;
14086 } ) ,
14187 ) ;
14288
143- const candidates : LoadedDoc [ ] = [ ] ;
144- let failCount = 0 ;
145- for ( const r of loadSettled ) {
146- if ( r . status === 'fulfilled' && r . value !== null ) {
147- candidates . push ( r . value ) ;
148- } else if ( r . status === 'rejected' ) {
149- failCount ++ ;
150- }
151- }
152- if ( failCount > 0 ) {
153- console . warn (
154- `[context] ${ failCount } /${ files . length } file(s) failed to load in library "${ library } " and were skipped.` ,
155- ) ;
156- }
89+ const docIds = docs . map ( ( d ) => d . id ) ;
90+ const existing = await this . store . fetchDocs ( library , docIds , [ 'contentHash' ] ) ;
15791
158- if ( candidates . length === 0 ) return ;
159-
160- // Phase 1b: Dedup via zvec — batch-fetch stored contentHashes.
161- // Zvec is the single source of truth; no separate registry needed.
162- const candidateIds = candidates . map ( ( d ) => d . id ) ;
163- const existing = await this . store . fetchDocs ( library , candidateIds , [ 'contentHash' ] ) ;
164-
165- const docsToEmbed : LoadedDoc [ ] = [ ] ;
166- for ( const doc of candidates ) {
167- const stored = existing [ doc . id ] ;
168- if ( ! stored ) {
169- // New document — embed and insert
170- docsToEmbed . push ( doc ) ;
171- } else if ( stored . fields . contentHash !== doc . contentHash ) {
172- // Content changed — re-embed and update
173- docsToEmbed . push ( doc ) ;
174- }
175- // else: contentHash matches → skip (already up to date)
176- }
92+ const docsToEmbed = docs . filter (
93+ ( doc ) => ! existing [ doc . id ] || existing [ doc . id ] . fields . contentHash !== doc . contentHash ,
94+ ) ;
17795
178- // Progress: load phase complete
179- if ( this . _onProgress ) {
180- this . _onProgress ( 'load' , { loaded : docsToEmbed . length , total : files . length } ) ;
96+ if ( this . options . onProgress ) {
97+ this . options . onProgress ( 'load' , { loaded : docsToEmbed . length , total : files . length } ) ;
18198 }
18299
183100 if ( docsToEmbed . length === 0 ) return ;
184101
185- // Phase 2: Batch embed all items for better performance
186102 const contents = docsToEmbed . map ( ( doc ) => doc . content ) ;
187103 const vectors = await this . embedder . embedBatch ( contents ) ;
188104
189- // Progress: embed phase complete
190- if ( this . _onProgress ) {
191- this . _onProgress ( 'embed' , { loaded : vectors . length , total : docsToEmbed . length } ) ;
105+ if ( this . options . onProgress ) {
106+ this . options . onProgress ( 'embed' , { loaded : vectors . length , total : docsToEmbed . length } ) ;
192107 }
193108
194- // Phase 3: Batch insert into store (upsert — handles both new and changed docs)
195109 const zvecDocs : ZvecDoc [ ] = docsToEmbed . map ( ( doc , index ) => ( {
196110 id : doc . id ,
197111 vector : vectors [ index ] ,
198112 fields : {
199113 content : doc . content ,
200- meta : doc . meta && Object . keys ( doc . meta ) . length > 0 ? JSON . stringify ( doc . meta ) : '' ,
201- sourceFilePath : doc . sourceFilePath ?? '' ,
114+ meta : doc . meta ? JSON . stringify ( doc . meta ) : '' ,
115+ path : doc . path ,
202116 contentHash : doc . contentHash ,
203117 } ,
204118 } ) ) ;
205119
206120 await this . store . addDoc ( library , zvecDocs ) ;
207121
208- // Progress: insert phase complete
209- if ( this . _onProgress ) {
210- this . _onProgress ( 'insert' , { loaded : zvecDocs . length , total : docsToEmbed . length } ) ;
122+ if ( this . options . onProgress ) {
123+ this . options . onProgress ( 'insert' , { loaded : zvecDocs . length , total : docsToEmbed . length } ) ;
211124 }
212125 }
213126
214- /**
215- * Query documents by semantic similarity.
216- *
217- * Default mode is `'hybrid'` which combines vector similarity + FTS text
218- * matching via RRF fusion for better recall. Use `mode: 'vector'` for
219- * pure semantic search when FTS is not needed.
220- *
221- * @param text Query text.
222- * @param options Query options (library, topK, mode).
223- * @returns Ranked results with content and score.
224- */
225127 async query ( text : string , options : QueryOptions ) : Promise < QueryResult [ ] > {
226- const library = options . library ;
128+ const opt = { topK : 5 , mode : 'hybrid' as const , rerank : { rerankFactor : 3 , minCandidates : 10 } , ...options } ;
129+
130+ const { library, topK, mode, rerank } = opt ;
227131
228132 // Expand the query with synonyms / cross-language bridging terms.
229- // The expanded text is used for both embedding and FTS, so a single
230- // expanded query can match CN and EN documents simultaneously.
231- const expandedText = this . queryExpander . expand ( text ) ;
133+ const expandedText = expand ( text , this . options . queryExpansion ) ;
134+
232135 const vector = await this . embedder . embed ( expandedText ) ;
233- const topK = options . topK ?? 5 ;
234- const mode = options . mode ?? 'hybrid' ;
235- const rerankEnabled = options . rerank !== false ;
236-
237- // Reranking pipeline: pull extra candidates from the coarse search so the
238- // reranker has a larger pool to select from. Without reranking, search
239- // exactly topK for efficiency.
240- const rerankFactor =
241- ( options . rerank && typeof options . rerank === 'object'
242- ? options . rerank . rerankFactor
243- : undefined ) ?? 3 ;
244- const minCandidates =
245- ( options . rerank && typeof options . rerank === 'object'
246- ? options . rerank . minCandidates
247- : undefined ) ?? 10 ;
136+
137+ const rerankConfig = typeof rerank === 'object' ? rerank : null ;
138+ const rerankEnabled = rerankConfig !== null ;
139+ const rerankFactor = rerankConfig ?. rerankFactor ?? 3 ;
140+ const minCandidates = rerankConfig ?. minCandidates ?? 10 ;
248141 const searchTopK = rerankEnabled ? Math . max ( topK * rerankFactor , minCandidates ) : topK ;
249142
250143 const searchResults = await this . store . queryDoc ( library , {
@@ -255,38 +148,32 @@ export class Context {
255148 filter : options . filter ,
256149 } ) ;
257150
258- if ( searchResults . length === 0 ) return [ ] ;
259-
260- const allResults : QueryResult [ ] = searchResults . map ( ( result ) => {
151+ const queryResults : QueryResult [ ] = searchResults . map ( ( result ) => {
261152 const content = String ( result . fields ?. content ?? '' ) ;
262153 const metaStr = result . fields ?. meta as string | undefined ;
263- const meta = safeParseMeta ( metaStr ) ;
154+ const meta = safeJsonParse ( metaStr ) as Record < string , unknown > | undefined ;
264155
265156 return {
266157 id : result . id ,
267158 content,
268159 score : result . score ,
269160 scoreMode : mode === 'hybrid' ? ( 'hybrid' as const ) : ( 'vector' as const ) ,
270161 meta,
271- sourceFilePath : result . fields ?. sourceFilePath as string | undefined ,
272- embedderKind : this . _embedderInfo . kind ,
162+ path : result . fields ?. path as string | undefined ,
273163 } ;
274164 } ) ;
275165
276- // Stage 2: Rerank the candidate pool for precision (when enabled).
277- // Pull extra candidates, re-score each against the query, then keep topK.
278- if ( rerankEnabled && allResults . length > topK ) {
279- const candidates : RerankCandidate [ ] = allResults . map ( ( r ) => ( {
166+ if ( rerankEnabled && queryResults . length > topK ) {
167+ const docs : RerankCandidate [ ] = queryResults . map ( ( r ) => ( {
280168 id : r . id ,
281169 content : r . content ,
282170 score : r . score ,
283171 } ) ) ;
284172
285- const reranked = await this . reranker ! . rerank ( text , candidates ) ;
173+ const reranked = await this . reranker ! . rerank ( text , docs ) ;
286174
287- // Merge reranked scores back into results
288175 const scoreMap = new Map ( reranked . map ( ( r ) => [ r . id , r . score ] ) ) ;
289- for ( const result of allResults ) {
176+ for ( const result of queryResults ) {
290177 const newScore = scoreMap . get ( result . id ) ;
291178 if ( newScore !== undefined ) {
292179 result . score = newScore ;
@@ -295,18 +182,11 @@ export class Context {
295182 }
296183 }
297184
298- // Final sort by (possibly reranked) score and return topK
299- allResults . sort ( ( a , b ) => b . score - a . score ) ;
300- return allResults . slice ( 0 , topK ) ;
185+ queryResults . sort ( ( a , b ) => b . score - a . score ) ;
186+ return queryResults . slice ( 0 , topK ) ;
301187 }
302188
303- /**
304- * Close all stores and release resources.
305- *
306- * Call this when you are done using the Context instance (e.g. at process
307- * exit or before re-creating a new instance).
308- */
309189 async close ( ) : Promise < void > {
310190 await this . store . closeAll ( ) ;
311191 }
312- }
192+ }
0 commit comments