ripvec-core 2.0.0

Semantic code + document search engine. Cacheless static-embedding + cross-encoder rerank by default; optional ModernBERT/BGE transformer engines with GPU backends. Tree-sitter chunking, hybrid BM25 + PageRank, composable ranking layers.
Documentation
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
//! `RipvecIndex` orchestrator and PageRank-layered ranking.
//!
//! Port of `~/src/semble/src/semble/index/index.py:RipvecIndex`. Owns
//! the corpus state (chunks, file mapping, language mapping, BM25,
//! dense embeddings, encoder) and dispatches search by mode.
//!
//! ## Port-plus-ripvec scope
//!
//! Per `docs/PLAN.md`, after the ripvec engine's own `rerank_topk` runs, ripvec's
//! [`boost_with_pagerank`](crate::hybrid::boost_with_pagerank) is
//! applied as a final ranking layer. The PageRank lookup is built from
//! the repo graph and stored alongside the corpus when one is provided
//! at construction; the layer no-ops when no graph is present.

use std::collections::HashMap;
use std::path::Path;

use crate::chunk::CodeChunk;
use crate::embed::SearchConfig;
use crate::encoder::VectorEncoder;
use crate::encoder::ripvec::bm25::{Bm25Index, search_bm25};
use crate::encoder::ripvec::dense::StaticEncoder;
use crate::encoder::ripvec::hybrid::{search_hybrid, search_semantic};
use crate::hybrid::SearchMode;
use crate::profile::Profiler;

/// Combined orchestrator for the ripvec retrieval pipeline.
///
/// Constructed via [`RipvecIndex::from_root`] which walks files,
/// chunks them with ripvec's chunker, embeds with the static encoder,
/// and builds the BM25 index.
pub struct RipvecIndex {
    chunks: Vec<CodeChunk>,
    embeddings: Vec<Vec<f32>>,
    bm25: Bm25Index,
    encoder: StaticEncoder,
    file_mapping: HashMap<String, Vec<usize>>,
    language_mapping: HashMap<String, Vec<usize>>,
    pagerank_lookup: Option<HashMap<String, f32>>,
    pagerank_alpha: f32,
    corpus_class: CorpusClass,
}

/// Index-time classification of the corpus by file mix.
///
/// Drives the corpus-aware rerank gate: docs and mixed corpora get
/// the L-12 cross-encoder fired (when the query is NL-shaped); pure
/// code corpora skip it because the ms-marco-trained model is
/// out-of-domain for code regardless of impl quality.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CorpusClass {
    /// Less than 30% of chunks are in prose files. Pure or near-pure
    /// code corpora — rerank skipped.
    Code,
    /// Between 30% and 70% prose chunks. Mixed corpora — rerank fires
    /// on NL queries to recover the prose-dominant relevance signal.
    Mixed,
    /// At least 70% prose chunks. Documentation, book sets, knowledge
    /// bases — rerank fires by default.
    Docs,
}

impl CorpusClass {
    /// Classify a chunk set by the fraction of chunks from prose files.
    /// Empty input is classified as `Code` (degenerate but defined).
    #[must_use]
    pub fn classify(chunks: &[CodeChunk]) -> Self {
        if chunks.is_empty() {
            return Self::Code;
        }
        let prose = chunks
            .iter()
            .filter(|c| {
                crate::encoder::ripvec::ranking::is_prose_path(&c.file_path)
            })
            .count();
        #[expect(
            clippy::cast_precision_loss,
            reason = "chunk count never exceeds f32 mantissa precision in practice"
        )]
        let frac = prose as f32 / chunks.len() as f32;
        if frac >= 0.7 {
            Self::Docs
        } else if frac >= 0.3 {
            Self::Mixed
        } else {
            Self::Code
        }
    }

    /// Whether the cross-encoder rerank should run on this corpus for
    /// a non-symbol NL query. Pure code corpora skip rerank; mixed
    /// and docs corpora enable it.
    #[must_use]
    pub fn rerank_eligible(self) -> bool {
        matches!(self, Self::Mixed | Self::Docs)
    }
}

impl RipvecIndex {
    /// Build a [`RipvecIndex`] by walking `root` and indexing every
    /// supported file. Uses `encoder.embed_root` (ripvec's chunker +
    /// model2vec encode) and builds a fresh BM25 index over the
    /// resulting chunks.
    ///
    /// `pagerank_lookup` is the optional structural-prior map (file
    /// path → normalized PageRank) used by the final ranking layer;
    /// pass `None` to disable. `pagerank_alpha` is the corresponding
    /// boost strength.
    ///
    /// # Errors
    ///
    /// Returns the underlying error if `embed_root` fails.
    pub fn from_root(
        root: &Path,
        encoder: StaticEncoder,
        cfg: &SearchConfig,
        profiler: &Profiler,
        pagerank_lookup: Option<HashMap<String, f32>>,
        pagerank_alpha: f32,
    ) -> crate::Result<Self> {
        let (chunks, embeddings) = encoder.embed_root(root, cfg, profiler)?;
        let bm25 = {
            let _g = profiler.phase("bm25_build");
            Bm25Index::build(&chunks)
        };
        let (file_mapping, language_mapping) = {
            let _g = profiler.phase("mappings");
            build_mappings(&chunks)
        };
        let corpus_class = CorpusClass::classify(&chunks);
        Ok(Self {
            chunks,
            embeddings,
            bm25,
            encoder,
            file_mapping,
            language_mapping,
            pagerank_lookup,
            pagerank_alpha,
            corpus_class,
        })
    }

    /// The index's corpus classification, computed at build time.
    ///
    /// Used by the MCP rerank gate to decide whether the L-12
    /// cross-encoder fires on a given query.
    #[must_use]
    pub fn corpus_class(&self) -> CorpusClass {
        self.corpus_class
    }

    /// Number of indexed chunks.
    #[must_use]
    pub fn len(&self) -> usize {
        self.chunks.len()
    }

    /// Whether the index has zero chunks.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.chunks.is_empty()
    }

    /// Indexed chunks (read-only access).
    #[must_use]
    pub fn chunks(&self) -> &[CodeChunk] {
        &self.chunks
    }

    /// Indexed embeddings (read-only access).
    ///
    /// One row per chunk in the same order as [`chunks`](Self::chunks).
    /// Each row is L2-normalized, so cosine similarity reduces to a
    /// dot product. Used by callers that need to do their own
    /// similarity arithmetic outside the canonical hybrid search —
    /// `find_similar` (rank-by-source-embedding) and
    /// `find_duplicates` (all-pairs cosine).
    #[must_use]
    pub fn embeddings(&self) -> &[Vec<f32>] {
        &self.embeddings
    }

    /// Search the index and return ranked `(chunk_index, score)` pairs.
    ///
    /// `mode = SearchMode::Hybrid` (default) fuses semantic + BM25 via
    /// RRF; `Semantic` and `Keyword` use one signal each.
    ///
    /// `filter_languages` and `filter_paths` build a selector mask
    /// that restricts retrieval to chunks in the named files /
    /// languages.
    #[must_use]
    pub fn search(
        &self,
        query: &str,
        top_k: usize,
        mode: SearchMode,
        alpha: Option<f32>,
        filter_languages: Option<&[String]>,
        filter_paths: Option<&[String]>,
    ) -> Vec<(usize, f32)> {
        if self.is_empty() || query.trim().is_empty() {
            return Vec::new();
        }
        let selector = self.build_selector(filter_languages, filter_paths);

        let raw = match mode {
            SearchMode::Keyword => search_bm25(query, &self.bm25, top_k, selector.as_deref()),
            SearchMode::Semantic => {
                let q_emb = self.encoder.encode_query(query);
                search_semantic(&q_emb, &self.embeddings, top_k, selector.as_deref())
            }
            SearchMode::Hybrid => {
                let q_emb = self.encoder.encode_query(query);
                search_hybrid(
                    query,
                    &q_emb,
                    &self.embeddings,
                    &self.chunks,
                    &self.bm25,
                    top_k,
                    alpha,
                    selector.as_deref(),
                )
            }
        };

        self.apply_pagerank_layer(raw)
    }

    /// Build a selector mask from optional language/path filters.
    /// Returns `None` when no filters are set (search runs over the
    /// full corpus).
    fn build_selector(
        &self,
        filter_languages: Option<&[String]>,
        filter_paths: Option<&[String]>,
    ) -> Option<Vec<usize>> {
        let mut selector: Vec<usize> = Vec::new();
        if let Some(langs) = filter_languages {
            for lang in langs {
                if let Some(ids) = self.language_mapping.get(lang) {
                    selector.extend(ids.iter().copied());
                }
            }
        }
        if let Some(paths) = filter_paths {
            for path in paths {
                if let Some(ids) = self.file_mapping.get(path) {
                    selector.extend(ids.iter().copied());
                }
            }
        }
        if selector.is_empty() {
            None
        } else {
            selector.sort_unstable();
            selector.dedup();
            Some(selector)
        }
    }

    /// Layer ripvec's PageRank boost on top of semble's ranked results.
    ///
    /// No-op when `pagerank_lookup` is `None` or the boost strength
    /// is zero. Otherwise re-uses
    /// [`crate::hybrid::boost_with_pagerank`] so the PageRank semantic
    /// stays consistent with ripvec's other code paths.
    fn apply_pagerank_layer(&self, mut results: Vec<(usize, f32)>) -> Vec<(usize, f32)> {
        let Some(lookup) = &self.pagerank_lookup else {
            return results;
        };
        if results.is_empty() || self.pagerank_alpha <= 0.0 {
            return results;
        }
        // Uses the shared `ranking::PageRankBoost` layer for behavioral
        // parity with the BERT CLI, MCP `search_code`, and LSP paths.
        // All five callers now apply the same sigmoid-on-percentile
        // curve.
        let layers: Vec<Box<dyn crate::ranking::RankingLayer>> = vec![Box::new(
            crate::ranking::PageRankBoost::new(lookup.clone(), self.pagerank_alpha),
        )];
        crate::ranking::apply_chain(&mut results, &self.chunks, &layers);
        results
    }
}

impl crate::searchable::SearchableIndex for RipvecIndex {
    fn chunks(&self) -> &[CodeChunk] {
        RipvecIndex::chunks(self)
    }

    /// Trait-shape search: text-only, no engine-specific knobs.
    ///
    /// The trait surface is the LSP-callers' common ground. Filters
    /// (language, path) and the alpha auto-detect override are not
    /// surfaced through the trait because no LSP module uses them.
    fn search(&self, query_text: &str, top_k: usize, mode: SearchMode) -> Vec<(usize, f32)> {
        RipvecIndex::search(self, query_text, top_k, mode, None, None, None)
    }

    /// Use chunk `chunk_idx`'s own embedding as the query vector and
    /// rank everything else by cosine similarity (semantic-only) or
    /// blend with BM25 (hybrid). Falls back to text-only keyword
    /// search when the chunk index is out of range.
    ///
    /// Mirrors the [`HybridIndex`] equivalent so `goto_definition`
    /// and `goto_implementation` work identically across engines.
    fn search_from_chunk(
        &self,
        chunk_idx: usize,
        query_text: &str,
        top_k: usize,
        mode: SearchMode,
    ) -> Vec<(usize, f32)> {
        // RipvecIndex stores embeddings; if the source chunk is in
        // range we can rank by similarity against its vector. Out of
        // range or keyword-only mode: fall back to text search.
        let Some(source) = self.embeddings().get(chunk_idx) else {
            return RipvecIndex::search(
                self,
                query_text,
                top_k,
                SearchMode::Keyword,
                None,
                None,
                None,
            );
        };
        match mode {
            SearchMode::Keyword => RipvecIndex::search(
                self,
                query_text,
                top_k,
                SearchMode::Keyword,
                None,
                None,
                None,
            ),
            SearchMode::Semantic | SearchMode::Hybrid => {
                // Cosine via dot product over L2-normalized rows.
                let mut scored: Vec<(usize, f32)> = self
                    .embeddings()
                    .iter()
                    .enumerate()
                    .filter(|(i, _)| *i != chunk_idx)
                    .map(|(i, row)| {
                        let dot: f32 = source.iter().zip(row.iter()).map(|(a, b)| a * b).sum();
                        (i, dot)
                    })
                    .collect();
                scored.sort_unstable_by(|a, b| b.1.total_cmp(&a.1));
                scored.truncate(top_k);
                scored
            }
        }
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Build (file_path → chunk indices, language → chunk indices) mappings.
fn build_mappings(
    chunks: &[CodeChunk],
) -> (HashMap<String, Vec<usize>>, HashMap<String, Vec<usize>>) {
    let mut file_to_id: HashMap<String, Vec<usize>> = HashMap::new();
    let mut lang_to_id: HashMap<String, Vec<usize>> = HashMap::new();
    for (i, chunk) in chunks.iter().enumerate() {
        file_to_id
            .entry(chunk.file_path.clone())
            .or_default()
            .push(i);
        // The semble port's chunker stores language inferentially (via
        // extension); the per-chunk `language` field isn't populated on
        // this path. The mapping is keyed on file extension as a proxy
        // so `filter_languages: Some(&["rs"])` works.
        if let Some(ext) = Path::new(&chunk.file_path)
            .extension()
            .and_then(|e| e.to_str())
        {
            lang_to_id.entry(ext.to_string()).or_default().push(i);
        }
    }
    (file_to_id, lang_to_id)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Compile-time check that `RipvecIndex` carries the right method
    /// shape for the CLI to call.
    #[test]
    fn semble_index_search_signature_compiles() {
        fn shape_check(
            idx: &RipvecIndex,
            query: &str,
            top_k: usize,
            mode: SearchMode,
        ) -> Vec<(usize, f32)> {
            idx.search(query, top_k, mode, None, None, None)
        }
        // Reference to keep type-check live across dead-code analysis.
        let _ = shape_check;
    }

    /// `behavior:pagerank-no-op-when-graph-absent` — when constructed
    /// without a PageRank lookup, the layer is a pure pass-through.
    /// (Asserted via the `apply_pagerank_layer` early-return path.)
    #[test]
    fn pagerank_layer_no_op_when_graph_absent() {
        // We can't easily build a RipvecIndex without a real encoder
        // (which requires a model download). Instead, exercise the
        // pass-through logic on a hand-built struct via the private
        // method. The function returns its input unchanged when
        // pagerank_lookup is None.
        //
        // Structural assertion: apply_pagerank_layer's first match
        // statement returns the input directly when lookup is None;
        // this is a single-branch invariant verified by inspection.
        // Behavioural verification is part of P5.1's parity test.
        let _ = "see apply_pagerank_layer docs";
    }
}