ripvec-core 4.1.15

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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
//! `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, PathBuf};

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::encoder::ripvec::manifest::{Diff, FileEntry, Manifest, diff_against_walk};
use crate::hybrid::SearchMode;
use crate::profile::Profiler;
use crate::walk::{WalkOptions, collect_files_with_options};

/// 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>,
    /// Row-major contiguous embedding matrix; row `i` is the
    /// L2-normalized embedding of chunk `i`. Held as `Array2<f32>` so
    /// cosine queries (dot product over normalized rows) dispatch to
    /// BLAS `sgemv` via ndarray's `cpu-accelerate` feature instead of
    /// pointer-chasing through `Vec<Vec<f32>>`. The change is a
    /// ~150x theoretical lift on per-query dense scoring at 1M chunks
    /// (memory-bandwidth-bound).
    embeddings: ndarray::Array2<f32>,
    bm25: Bm25Index,
    /// Shared by `Arc` so [`Self::apply_diff`] can produce a new index
    /// that reuses the same loaded model without cloning the ~32 MB
    /// embedding table. The encoder is immutable after construction.
    encoder: std::sync::Arc<StaticEncoder>,
    file_mapping: HashMap<String, Vec<usize>>,
    language_mapping: HashMap<String, Vec<usize>>,
    pagerank_lookup: Option<std::sync::Arc<HashMap<String, f32>>>,
    pagerank_alpha: f32,
    corpus_class: CorpusClass,
    /// Canonical root the index was built against. Used by
    /// [`RipvecIndex::diff_against_filesystem`] to walk the same tree
    /// for reconciliation.
    root: PathBuf,
    /// Walk filters captured at build time so reconciliation honors the
    /// same `.gitignore`, extension whitelist, ignore-pattern set as
    /// the original index.
    walk_options: WalkOptions,
    /// Per-file fingerprint table (mtime, size, inode, blake3) for
    /// online change detection. Built during [`Self::from_root`] and
    /// queried by [`Self::diff_against_filesystem`]. See
    /// [`crate::encoder::ripvec::manifest`] for the algorithm.
    manifest: Manifest,
}

/// 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 dominated by prose.
    ///
    /// A chunk counts as "prose" when **either** of the following holds:
    /// - its file extension is in [`crate::encoder::ripvec::ranking::is_prose_path`]
    ///   (e.g. `.md`, `.rst`, `.txt`), OR
    /// - its content is dominated by docstring/comment text per
    ///   [`chunk_is_prose_dominated`] (the I#64 / B-0028 path —
    ///   docstring-heavy Python, JS-doc-heavy code, etc.).
    ///
    /// The second branch matters: a Mnemosyne-class Python corpus where
    /// every class has a substantial docstring is classified as `Code`
    /// by the file-extension test alone, even though >50% of its bytes
    /// are prose. The within-chunk content test catches this case so
    /// `Auto`-policy rerank fires on NL queries against such corpora.
    ///
    /// 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)
                    || chunk_is_prose_dominated(c)
            })
            .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 >= prose_density::CORPUS_DOCS_FRAC {
            Self::Docs
        } else if frac >= prose_density::CORPUS_MIXED_FRAC {
            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)
    }
}

/// Tunables for the prose-density signal that decides whether the
/// cross-encoder reranker fires on `rerank=auto` queries.
///
/// All three thresholds gate the same I#64 decision chain:
///
/// 1. **Per chunk** — [`CHUNK_DOMINANCE_FRAC`] is the fraction of a
///    single chunk's bytes that must lie inside docstring / comment
///    constructs before the chunk counts as "prose-dominated".
/// 2. **Per corpus** — once chunks are classified, the fraction of
///    prose-dominated chunks in the corpus picks
///    [`super::CorpusClass`]: ≥ [`CORPUS_DOCS_FRAC`] → `Docs`,
///    ≥ [`CORPUS_MIXED_FRAC`] → `Mixed`, otherwise `Code`.
///
/// The numbers come from the I#64 issue text and the agent's first
/// implementation pass; they are knobs, not invariants. Tune here when
/// retrieval evidence (NDCG@10 against the mnemosyne / textual /
/// docstring-heavy corpora) suggests a different cut.
pub(super) mod prose_density {
    /// Per-chunk prose-byte fraction that promotes a chunk to
    /// "prose-dominated". 50% is the natural "more prose than code" cut.
    pub const CHUNK_DOMINANCE_FRAC: f32 = 0.5;

    /// Fraction of prose-dominated chunks that promotes a corpus to
    /// [`super::super::CorpusClass::Mixed`] — the threshold at which
    /// `rerank=auto` fires on Code / All corpus queries.
    pub const CORPUS_MIXED_FRAC: f32 = 0.3;

    /// Fraction of prose-dominated chunks that promotes a corpus to
    /// [`super::super::CorpusClass::Docs`] — at this density we treat
    /// the corpus as prose-first and always rerank.
    pub const CORPUS_DOCS_FRAC: f32 = 0.7;
}

/// Whether this chunk's content is dominated by docstring / comment
/// prose rather than code syntax.
///
/// Pragmatic, language-agnostic heuristic: scan the chunk's `content`
/// (raw source, not enriched) and sum the bytes inside common prose
/// constructs — Python triple-quoted strings (`"""..."""` / `'''...'''`),
/// C-style block comments (`/* ... */`), and line comments
/// (`#`, `//`, `///`). When that prose-byte fraction exceeds
/// [`prose_density::CHUNK_DOMINANCE_FRAC`] (50%), the chunk reads more
/// like a docstring than like code.
///
/// This is intentionally **not** a tree-sitter parse: the prose-density
/// signal feeds a coarse corpus-level threshold (30% prose chunks → fire
/// rerank), so per-chunk noise washes out. A tree-sitter parse here would
/// add chunker dependencies and per-chunk parse cost for a coarse signal.
///
/// Whitespace-only and empty chunks return `false` (degenerate;
/// they don't push the corpus toward "prose-dominated").
#[must_use]
fn chunk_is_prose_dominated(chunk: &CodeChunk) -> bool {
    let total = chunk.content.len();
    if total == 0 {
        return false;
    }
    #[expect(
        clippy::cast_precision_loss,
        reason = "chunk content length never exceeds f32 mantissa precision in practice"
    )]
    let ratio = prose_byte_count(&chunk.content) as f32 / total as f32;
    ratio > prose_density::CHUNK_DOMINANCE_FRAC
}

/// Count bytes inside docstring/comment constructs within `source`.
///
/// Recognised constructs:
/// - Python triple-quoted strings (`"""..."""`, `'''...'''`) — the
///   docstring shape that motivates I#64.
/// - C-style block comments (`/* ... */`) — JS-doc, Rust block docs,
///   Java/C/C++.
/// - Line comments starting with `#`, `//`, or `///` — Python, shell,
///   Rust, JS/TS, Go, etc.
///
/// Bytes inside both a string and a comment are counted once
/// (the scanner is a single-pass state machine). The scanner is
/// deliberately simple: it does not honour escape sequences inside
/// strings or detect string-vs-comment precedence across all languages.
/// It is calibrated for the corpus-level "is this prose-dominated"
/// question, not for syntactic correctness.
#[must_use]
fn prose_byte_count(source: &str) -> usize {
    let bytes = source.as_bytes();
    let mut prose = 0usize;
    let mut i = 0usize;
    while i < bytes.len() {
        let rest = &bytes[i..];
        // Triple-quoted Python docstrings.
        if rest.starts_with(b"\"\"\"") || rest.starts_with(b"'''") {
            let quote = &rest[..3];
            let start = i + 3;
            // Search for the matching closing triple-quote.
            let mut j = start;
            while j + 3 <= bytes.len() && &bytes[j..j + 3] != quote {
                j += 1;
            }
            let end = (j + 3).min(bytes.len());
            prose += end - i;
            i = end;
            continue;
        }
        // Block comment /* ... */.
        if rest.starts_with(b"/*") {
            let mut j = i + 2;
            while j + 2 <= bytes.len() && &bytes[j..j + 2] != b"*/" {
                j += 1;
            }
            let end = (j + 2).min(bytes.len());
            prose += end - i;
            i = end;
            continue;
        }
        // Line comment // or /// (handle /// as a superset of //).
        if rest.starts_with(b"//") {
            let mut j = i;
            while j < bytes.len() && bytes[j] != b'\n' {
                j += 1;
            }
            prose += j - i;
            i = j;
            continue;
        }
        // Line comment # (Python, shell). Guard against `#!` shebangs:
        // still counts as a line comment (it's prose-ish content), so
        // no special case needed.
        if bytes[i] == b'#' {
            let mut j = i;
            while j < bytes.len() && bytes[j] != b'\n' {
                j += 1;
            }
            prose += j - i;
            i = j;
            continue;
        }
        i += 1;
    }
    prose
}

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> {
        // Wrap once at construction. The per-query `apply_pagerank_layer`
        // path clones the Arc (pointer bump), not the HashMap (10K+ String
        // allocs on a 1M-chunk corpus).
        let pagerank_lookup = pagerank_lookup.map(std::sync::Arc::new);
        let (chunks, embeddings_vec) = encoder.embed_root(root, cfg, profiler)?;
        // Convert Vec<Vec<f32>> -> Array2<f32> at the boundary. The
        // upstream embed_root produces ragged-friendly Vec<Vec<>>; we
        // pack into one contiguous row-major buffer so BLAS sgemv can
        // do per-query cosine in one call. Cost is a single sequential
        // memcpy pass (~1 GB at memory bandwidth = ~5 ms on a 1M-chunk
        // corpus) — negligible against the 60 s build phase.
        let hidden_dim = embeddings_vec.first().map_or(0, std::vec::Vec::len);
        let n_chunks = embeddings_vec.len();
        let mut flat: Vec<f32> = Vec::with_capacity(n_chunks * hidden_dim);
        for row in embeddings_vec {
            debug_assert_eq!(
                row.len(),
                hidden_dim,
                "ragged embeddings: row of {} vs expected {hidden_dim}",
                row.len()
            );
            flat.extend(row);
        }
        let embeddings = ndarray::Array2::from_shape_vec((n_chunks, hidden_dim), flat)
            .map_err(|e| crate::Error::Other(anyhow::anyhow!("embeddings reshape: {e}")))?;
        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);
        // Capture walk options for future reconciles, and populate the
        // manifest from the same file set the indexer consumed. We
        // re-walk + re-read here because `embed_root` doesn't surface
        // the per-file bytes back to us; the redundant read is paid
        // once at index build time, not per query. On reconcile we
        // only re-read files whose stat tuple changed.
        let walk_options = cfg.walk_options();
        let root_buf = root.to_path_buf();
        let manifest = {
            let _g = profiler.phase("manifest_build");
            build_manifest(&root_buf, &walk_options)
        };
        Ok(Self {
            chunks,
            embeddings,
            bm25,
            encoder: std::sync::Arc::new(encoder),
            file_mapping,
            language_mapping,
            pagerank_lookup,
            pagerank_alpha,
            corpus_class,
            root: root_buf,
            walk_options,
            manifest,
        })
    }

    /// Build a new index by incrementally applying `diff` against
    /// `self`.
    ///
    /// **The selective-rebuild path that v3.1.0 punted on.** Re-embeds
    /// only the dirty + new files, splices them into the existing
    /// chunks/embeddings, drops deleted files' chunks, rebuilds BM25
    /// and the per-file/per-language mappings from the new chunk set,
    /// reclassifies the corpus, and refreshes the manifest entries
    /// for the affected files.
    ///
    /// # Cost shape
    ///
    /// Roughly `O(|diff.dirty| + |diff.new|)` chunk + embed work plus
    /// `O(|self.chunks|)` BM25 rebuild. On a 5000-chunk corpus with
    /// one file changed: ~5-10 ms (embed one file) + ~50 ms (BM25
    /// rebuild) = ~60 ms — vs. ~270 ms-1 s for a full
    /// [`Self::from_root`] rebuild. The full-build cost is paid only
    /// at cold start.
    ///
    /// # BM25
    ///
    /// BM25 is rebuilt from scratch over the new chunks vec rather
    /// than incrementally updated. Inverted-postings incremental
    /// update is correct but adds significant code; full rebuild at
    /// our chunk counts is fast enough that the simpler path wins.
    ///
    /// # Errors
    ///
    /// Returns the underlying error if [`StaticEncoder::embed_paths`]
    /// fails or if the embedding matrix shape is invalid.
    pub fn apply_diff(&self, diff: &Diff, profiler: &Profiler) -> crate::Result<Self> {
        use std::collections::HashSet;

        // 1. Identify which existing chunk indices to drop. `file_mapping`
        //    keys are the rel_paths the chunker wrote. Manifest paths are
        //    absolute. Map manifest paths to rel_paths by stripping
        //    `self.root` (the same operation `chunk_one_file` performs).
        let rel_path_for = |p: &Path| -> String {
            p.strip_prefix(&self.root)
                .unwrap_or(p)
                .display()
                .to_string()
        };
        let mut removed_indices: HashSet<usize> = HashSet::new();
        for path in diff
            .deleted
            .iter()
            .chain(diff.dirty.iter())
            .chain(diff.new.iter())
        {
            let rel = rel_path_for(path);
            if let Some(indices) = self.file_mapping.get(&rel) {
                removed_indices.extend(indices.iter().copied());
            }
        }

        // 2. Build the kept chunks + embeddings from `self`. Cloning the
        //    embedding rows is one allocation per kept chunk; for a 5k-
        //    chunk corpus that's a single sequential pass over 5 MB.
        let mut kept_chunks: Vec<CodeChunk> = Vec::with_capacity(self.chunks.len());
        let mut kept_emb_rows: Vec<Vec<f32>> = Vec::with_capacity(self.chunks.len());
        for (i, chunk) in self.chunks.iter().enumerate() {
            if removed_indices.contains(&i) {
                continue;
            }
            kept_chunks.push(chunk.clone());
            kept_emb_rows.push(self.embeddings.row(i).to_vec());
        }

        // 3. Embed the dirty + new files. (Dirty files were already
        //    dropped from `kept_chunks` above; their new chunks come in
        //    here as fresh entries.)
        let mut to_embed: Vec<std::path::PathBuf> = Vec::new();
        to_embed.extend(diff.new.iter().cloned());
        to_embed.extend(diff.dirty.iter().cloned());
        let (new_chunks, new_embs) = if to_embed.is_empty() {
            (Vec::new(), Vec::new())
        } else {
            let _g = profiler.phase("apply_diff_embed");
            self.encoder.embed_paths(&self.root, &to_embed, profiler)?
        };
        kept_chunks.extend(new_chunks);
        kept_emb_rows.extend(new_embs);

        // 4. Re-pack embeddings into a contiguous Array2 so BLAS sgemv
        //    still works at query time.
        let n = kept_emb_rows.len();
        let hidden_dim = kept_emb_rows
            .first()
            .map_or(self.embeddings.ncols(), Vec::len);
        let mut flat: Vec<f32> = Vec::with_capacity(n * hidden_dim);
        for row in kept_emb_rows {
            flat.extend(row);
        }
        let embeddings = if n == 0 {
            ndarray::Array2::<f32>::zeros((0, hidden_dim))
        } else {
            ndarray::Array2::from_shape_vec((n, hidden_dim), flat).map_err(|e| {
                crate::Error::Other(anyhow::anyhow!("apply_diff embeddings reshape: {e}"))
            })?
        };

        // 5. Rebuild BM25 from the new chunks (simpler than incremental
        //    postings update; cheap at our chunk counts). Rebuild
        //    mappings + corpus_class from the new chunks too.
        let bm25 = {
            let _g = profiler.phase("apply_diff_bm25");
            Bm25Index::build(&kept_chunks)
        };
        let (file_mapping, language_mapping) = {
            let _g = profiler.phase("apply_diff_mappings");
            build_mappings(&kept_chunks)
        };
        let corpus_class = CorpusClass::classify(&kept_chunks);

        // 6. Refresh manifest: drop deleted entries, refresh dirty
        //    entries with new (mtime, size, ino, blake3), insert new
        //    entries. blake3 requires the file bytes, so this re-reads
        //    each changed file once. Negligible (~10 µs/file warm).
        //
        //    Also apply `diff.touched_clean`: these are files whose stat
        //    tuple changed but whose content (blake3) is identical. The
        //    `diff_against_filesystem` path clones `self.manifest` before
        //    calling `diff_against_walk`, so the in-place stat-tuple
        //    refresh inside `diff_against_walk` is discarded. Without this
        //    step, every touched-but-unchanged file pays one blake3 read
        //    per reconcile cycle instead of zero. Applying the entries here
        //    — using the refreshed `FileEntry` already computed by
        //    `diff_against_walk` — restores the "one blake3 then zero"
        //    invariant on the new index.
        let mut manifest = self.manifest.clone();
        for path in &diff.deleted {
            manifest.files.remove(path);
        }
        for path in diff.new.iter().chain(diff.dirty.iter()) {
            if let Ok(entry) = FileEntry::from_path(path) {
                manifest.insert(path.clone(), entry);
            }
        }
        // Apply touched_clean refreshes: stat tuple already computed by
        // diff_against_walk; no re-read or re-hash needed.
        for (path, refreshed_entry) in &diff.touched_clean {
            if let Some(entry_mut) = manifest.files.get_mut(path) {
                entry_mut.mtime = refreshed_entry.mtime;
                entry_mut.size = refreshed_entry.size;
                entry_mut.ino = refreshed_entry.ino;
                // blake3 is unchanged (that's the definition of touched_clean)
                // but we overwrite defensively for consistency.
                entry_mut.blake3 = refreshed_entry.blake3;
            }
        }

        Ok(Self {
            chunks: kept_chunks,
            embeddings,
            bm25,
            encoder: std::sync::Arc::clone(&self.encoder),
            file_mapping,
            language_mapping,
            pagerank_lookup: self.pagerank_lookup.clone(),
            pagerank_alpha: self.pagerank_alpha,
            corpus_class,
            root: self.root.clone(),
            walk_options: self.walk_options.clone(),
            manifest,
        })
    }

    /// Compare the manifest captured at build time against the current
    /// filesystem state under [`Self::root`], using the same
    /// [`WalkOptions`] used for the original index build.
    ///
    /// Returns a [`Diff`] enumerating dirty, new, and deleted files.
    /// A zero-cost ([`Diff::is_empty`]) result means the index is
    /// up-to-date and no rebuild is needed.
    ///
    /// # Cost
    ///
    /// Walk + per-file `stat()` for the cheap-path files (typically all
    /// of them between successive queries). Blake3 verification is paid
    /// only on the rare files where the stat tuple mismatches. On a
    /// 200-file repo with no changes: sub-millisecond. On a 92k-file
    /// repo with no changes: ~100-130 ms (the walk dominates).
    ///
    /// # Mutation
    ///
    /// This method takes `&self` and works on a clone of the manifest,
    /// so the optimization of "refresh touched-but-unchanged stat
    /// tuples" from [`diff_against_walk`] is discarded here. In
    /// practice that means a file repeatedly touched without content
    /// change pays one blake3 read per reconcile rather than zero —
    /// negligible at our file sizes.
    #[must_use]
    pub fn diff_against_filesystem(&self) -> Diff {
        let files = collect_files_with_options(&self.root, &self.walk_options);
        let mut manifest = self.manifest.clone();
        diff_against_walk(&mut manifest, &files)
    }

    /// Canonical root the index was built against.
    #[must_use]
    pub fn root(&self) -> &Path {
        &self.root
    }

    /// Walk options captured at build time.
    #[must_use]
    pub fn walk_options(&self) -> &WalkOptions {
        &self.walk_options
    }

    /// Manifest of tracked files (read-only access).
    #[must_use]
    pub fn manifest(&self) -> &Manifest {
        &self.manifest
    }

    /// 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).
    ///
    /// `Array2<f32>` of shape `[n_chunks, hidden_dim]`, row-major. Row
    /// `i` is the L2-normalized embedding of chunk `i`, so cosine
    /// similarity reduces to a dot product. Callers that need their
    /// own similarity arithmetic (`find_similar`, `find_duplicates`)
    /// should use `embeddings.row(i)` for a single-row view or
    /// `embeddings.dot(&query)` for a one-call BLAS GEMV.
    #[must_use]
    pub fn embeddings(&self) -> &ndarray::Array2<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.
        // `lookup` is `Arc<HashMap<_,_>>`; cloning the Arc is a pointer
        // bump, not a HashMap copy. The earlier `lookup.clone()` here
        // cloned the entire map per query (~10K String allocations on
        // a 1M-chunk corpus).
        let layers: Vec<Box<dyn crate::ranking::RankingLayer>> = vec![Box::new(
            crate::ranking::PageRankBoost::new(std::sync::Arc::clone(lookup), 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.
        if chunk_idx >= self.embeddings().nrows() {
            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.
                // Parallel sgemv across row-shards to saturate
                // aggregate memory bandwidth instead of the single-core
                // sgemv ceiling.
                let source = self.embeddings().row(chunk_idx);
                let scores =
                    crate::encoder::ripvec::hybrid::parallel_sgemv(self.embeddings(), &source);
                let mut scored: Vec<(usize, f32)> = scores
                    .iter()
                    .enumerate()
                    .filter(|(i, _)| *i != chunk_idx)
                    .map(|(i, &s)| (i, s))
                    .collect();
                if scored.len() > top_k {
                    scored.select_nth_unstable_by(top_k - 1, |a, b| {
                        b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))
                    });
                    scored.truncate(top_k);
                }
                scored.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
                scored
            }
        }
    }

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

/// Locate the chunk index for a given file path and 1-based line number.
///
/// Used by `find_similar` (ripvec-mcp) to resolve an `lsp_location` whose
/// `start_line` may be the symbol-identifier line (as returned by
/// `get_repo_map`'s `symbols[].lsp_location`) rather than the chunk's own
/// `start_line` (the block-start, which may precede the identifier by the
/// length of doc-comments, attributes, or decorators).
///
/// # Lookup strategy (I#50 three-step spec)
///
/// 1. **Exact start-line match**: return the first chunk whose
///    `start_line == target_line_1based`. Cheap O(n) scan that covers the
///    common case where the caller already has a chunk-start coordinate.
///
/// 2. **Range containment**: return the first chunk whose closed interval
///    `[start_line, end_line]` contains `target_line_1based`. Covers the
///    I#50 failure case where `get_repo_map.symbols[].lsp_location.start_line`
///    is the identifier line (inside the chunk) rather than the block start.
///
/// 3. **Miss**: return `None`. The caller is responsible for returning empty
///    results — `find_similar` must NOT propagate this as an internal error.
///
/// # Path matching
///
/// Matches on a strict suffix: a chunk at path `a/b/c.rs` matches a query
/// for `b/c.rs` or `c.rs` (the suffix is separated by `/`). Absolute paths
/// are compared directly. This mirrors the convention used throughout
/// `find_similar_chunk_idx` in `ripvec-mcp`.
///
/// # Arguments
///
/// * `chunks` — the indexed chunk slice (from `RipvecIndex::chunks()`).
/// * `file_path` — path to match against `chunk.file_path`.
/// * `target_line_1based` — the 1-based line to locate, matching the
///   1-based `lsp_location.start_line` → `target_line_1based` convention.
#[must_use]
pub fn find_chunk_containing_line(
    chunks: &[CodeChunk],
    file_path: &str,
    target_line_1based: usize,
) -> Option<usize> {
    let path_matches = |chunk: &CodeChunk| -> bool {
        let cp = &chunk.file_path;
        cp == file_path
            || (cp.len() > file_path.len()
                && cp.ends_with(file_path)
                && cp.as_bytes()[cp.len() - file_path.len() - 1] == b'/')
    };

    // Step 1: exact start_line match.
    if let Some(idx) = chunks
        .iter()
        .position(|c| path_matches(c) && c.start_line == target_line_1based)
    {
        return Some(idx);
    }

    // Step 2: range containment — find the first chunk whose [start_line,
    // end_line] interval contains the target line.
    chunks.iter().position(|c| {
        path_matches(c) && c.start_line <= target_line_1based && target_line_1based <= c.end_line
    })
}

/// Build (file_path → chunk indices, language → chunk indices) mappings.
/// Build the per-file manifest by walking `root` with `walk_options`
/// and stat + read + blake3 each file. Used at index construction; on
/// reconcile, [`RipvecIndex::diff_against_filesystem`] uses the cheap
/// stat-tuple path and only re-reads files whose tuple mismatches the
/// stored entry.
///
/// Files that can't be read or stat'd are silently skipped; they will
/// re-appear in the diff as `new` if they become readable later, or
/// as missing on the next reconcile.
fn build_manifest(root: &Path, walk_options: &WalkOptions) -> Manifest {
    let mut manifest = Manifest::new();
    let files = collect_files_with_options(root, walk_options);
    for path in files {
        let (Ok(metadata), Ok(bytes)) = (std::fs::metadata(&path), std::fs::read(&path)) else {
            continue;
        };
        let entry = FileEntry::from_bytes(&metadata, &bytes);
        manifest.insert(path, entry);
    }
    manifest
}

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::*;

    // ── I#64 / B-0028: within-chunk prose-density signal ─────────────────────

    /// Helper: build a chunk on a `.py` path with the given source content.
    /// `.py` file-extension classifies as Code via `is_prose_path`, so the
    /// resulting prose classification depends purely on chunk content.
    fn py_chunk(content: &str) -> crate::chunk::CodeChunk {
        crate::chunk::CodeChunk {
            file_path: "src/foo.py".to_string(),
            name: "test".to_string(),
            kind: "function_definition".to_string(),
            content_kind: crate::chunk::ContentKind::Code,
            start_line: 1,
            end_line: 10,
            symbol_line: 1,
            content: content.to_string(),
            enriched_content: content.to_string(),
            qualified_name: None,
        }
    }

    /// A chunk dominated by a Python triple-quoted docstring is prose.
    #[test]
    fn chunk_is_prose_dominated_python_docstring() {
        let c = py_chunk(
            "def handle_error(self, exc):\n    \"\"\"This is the docstring \
             that explains the error-handling contract. It dwarfs the body \
             and so the chunk is dominated by prose.\"\"\"\n    return None\n",
        );
        assert!(
            chunk_is_prose_dominated(&c),
            "Python triple-quoted docstring dominating the chunk must be \
             recognised as prose-dominated"
        );
    }

    /// A chunk dominated by code syntax is not prose.
    #[test]
    fn chunk_is_prose_dominated_pure_code_is_false() {
        let c = py_chunk("def f(x, y):\n    z = x * y + 2\n    return z * z - (x + y)\n");
        assert!(
            !chunk_is_prose_dominated(&c),
            "Pure code chunk (no docstring, no comments) must not be \
             prose-dominated"
        );
    }

    /// A chunk dominated by `//` line comments is prose.
    #[test]
    fn chunk_is_prose_dominated_line_comments() {
        // ~80% comment bytes vs ~20% code.
        let c = py_chunk(
            "// This is a long-form explanation of why the function exists.\n\
             // It spans multiple lines and dominates the chunk by byte count.\n\
             // The actual code is a tiny one-liner.\n\
             fn f() { 1 }\n",
        );
        assert!(
            chunk_is_prose_dominated(&c),
            "Chunk dominated by `//` line comments must be prose-dominated"
        );
    }

    /// A chunk dominated by a `/* ... */` block comment is prose.
    #[test]
    fn chunk_is_prose_dominated_block_comment() {
        let c = py_chunk(
            "/* JS-doc style block comment describing the function in detail \
             and taking up most of the chunk by byte volume. */\nfn g() {}\n",
        );
        assert!(
            chunk_is_prose_dominated(&c),
            "Chunk dominated by `/* ... */` block comment must be \
             prose-dominated"
        );
    }

    /// Empty chunk content does not push corpus toward prose.
    #[test]
    fn chunk_is_prose_dominated_empty_is_false() {
        let c = py_chunk("");
        assert!(
            !chunk_is_prose_dominated(&c),
            "Empty chunk content must classify as not-prose (degenerate case)"
        );
    }

    /// `CorpusClass::classify`: synthetic (prose=10, code=20) → Mixed.
    /// Matches the issue text's pure-unit test shape — given a chunk-count
    /// summary, assert the policy.
    #[test]
    fn corpus_class_classify_10_prose_20_code_is_mixed() {
        let prose = py_chunk(
            "def f():\n    \"\"\"A substantial docstring whose byte count \
             dominates the chunk.\"\"\"\n    pass\n",
        );
        let code = py_chunk("def g(x):\n    return x + 1\n");
        // Pre-condition: helper agrees.
        assert!(chunk_is_prose_dominated(&prose));
        assert!(!chunk_is_prose_dominated(&code));

        let mut chunks = Vec::new();
        for _ in 0..10 {
            chunks.push(prose.clone());
        }
        for _ in 0..20 {
            chunks.push(code.clone());
        }
        assert_eq!(
            CorpusClass::classify(&chunks),
            CorpusClass::Mixed,
            "10 prose : 20 code (~33% prose chunks) must classify as Mixed; \
             threshold is >= 30% prose"
        );
        assert!(
            CorpusClass::classify(&chunks).rerank_eligible(),
            "Mixed must be rerank-eligible — the I#64 / B-0028 fire path"
        );
    }

    /// `CorpusClass::classify`: synthetic (prose=20, code=10) → Mixed,
    /// rerank-eligible (still under the 70% Docs cut but well over the
    /// 30% Mixed cut).
    #[test]
    fn corpus_class_classify_20_prose_10_code_is_rerank_eligible() {
        let prose = py_chunk(
            "def f():\n    \"\"\"Substantial docstring that dominates the \
             chunk's bytes — a Mnemosyne-class signature.\"\"\"\n    pass\n",
        );
        let code = py_chunk("def g(x):\n    return x + 1\n");
        let mut chunks = Vec::new();
        for _ in 0..20 {
            chunks.push(prose.clone());
        }
        for _ in 0..10 {
            chunks.push(code.clone());
        }
        let class = CorpusClass::classify(&chunks);
        assert!(
            class.rerank_eligible(),
            "20 prose : 10 code (~67% prose chunks) must be rerank-eligible"
        );
    }

    /// `CorpusClass::classify`: synthetic (prose=2, code=28) → Code, not
    /// rerank-eligible. Tests that low prose density correctly stays off.
    #[test]
    fn corpus_class_classify_low_prose_is_code() {
        let prose = py_chunk("def f():\n    \"\"\"Docstring dominating the chunk's bytes.\"\"\"\n");
        let code = py_chunk("def g(x):\n    return x + 1\n");
        let mut chunks = Vec::new();
        for _ in 0..2 {
            chunks.push(prose.clone());
        }
        for _ in 0..28 {
            chunks.push(code.clone());
        }
        assert_eq!(
            CorpusClass::classify(&chunks),
            CorpusClass::Code,
            "2:28 prose:code (~7% prose chunks) must classify as Code"
        );
    }

    /// `is_prose_path` and chunk-content density are independent signals
    /// and stack (a `.md` file is prose regardless of content; a `.py`
    /// file becomes prose iff its chunk content is prose-dominated).
    #[test]
    fn corpus_class_classify_path_and_content_signals_compose() {
        let md_chunk = crate::chunk::CodeChunk {
            file_path: "README.md".to_string(),
            name: "readme".to_string(),
            kind: "paragraph".to_string(),
            content_kind: crate::chunk::ContentKind::Docs,
            start_line: 1,
            end_line: 5,
            symbol_line: 1,
            content: "function foo() { return 1; }".to_string(), // code-like content
            enriched_content: "function foo() { return 1; }".to_string(),
            qualified_name: None,
        };
        // Even though the content is code-like, the .md extension means
        // this counts as prose under the path signal.
        let chunks = vec![md_chunk];
        assert_eq!(
            CorpusClass::classify(&chunks),
            CorpusClass::Docs,
            "A .md path counts as prose under is_prose_path even if its \
             content is code-like — path and content signals OR together"
        );
    }

    // ── existing tests below ─────────────────────────────────────────────────

    /// Test-only constructor that bypasses `from_root` to allow unit
    /// tests to inject pre-built state (chunks, embeddings, mappings,
    /// manifest) without requiring a real model download.
    ///
    /// For tests that call `apply_diff` with a non-empty `diff.new` or
    /// `diff.dirty`, the caller must supply a real encoder because
    /// `apply_diff` calls `encoder.embed_paths`.
    #[allow(clippy::too_many_arguments)]
    fn new_for_test(
        chunks: Vec<crate::chunk::CodeChunk>,
        embeddings: ndarray::Array2<f32>,
        encoder: std::sync::Arc<StaticEncoder>,
        file_mapping: HashMap<String, Vec<usize>>,
        language_mapping: HashMap<String, Vec<usize>>,
        manifest: Manifest,
        root: std::path::PathBuf,
        walk_options: WalkOptions,
    ) -> RipvecIndex {
        let bm25 = Bm25Index::build(&chunks);
        let corpus_class = CorpusClass::classify(&chunks);
        RipvecIndex {
            chunks,
            embeddings,
            bm25,
            encoder,
            file_mapping,
            language_mapping,
            pagerank_lookup: None,
            pagerank_alpha: 0.0,
            corpus_class,
            root,
            walk_options,
            manifest,
        }
    }

    /// 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";
    }

    /// Corner case: a file appears in `diff.new` (absent from manifest)
    /// but `file_mapping` still holds stale chunk indices for it from a
    /// prior partial reconcile. Without the R4.1 fix, `apply_diff` skips
    /// clearing those stale chunks before re-embedding → duplicates.
    ///
    /// Gated `#[ignore]` because `apply_diff` calls `encoder.embed_paths`
    /// for files in `diff.new`, which requires the Model2Vec weights.
    /// Run once model is cached:
    ///   `cargo test -p ripvec-core apply_diff_idempotent -- --ignored`
    #[test]
    #[ignore = "requires Model2Vec download (~32 MB on first run)"]
    fn apply_diff_idempotent_when_new_file_already_has_chunks() {
        use crate::encoder::ripvec::dense::{DEFAULT_MODEL_REPO, StaticEncoder};
        use crate::profile::Profiler;
        use std::fs;

        let encoder = StaticEncoder::from_pretrained(DEFAULT_MODEL_REPO).expect("encoder load");
        let encoder_arc = std::sync::Arc::new(encoder);

        // Temporary corpus: one file (file_a.rs).
        let tmp = tempfile::TempDir::new().unwrap();
        let file_a = tmp.path().join("file_a.rs");
        fs::write(
            &file_a,
            "pub fn alpha() -> u32 { 1 }\npub fn beta() -> u32 { 2 }\n",
        )
        .unwrap();

        // Embed file_a.rs once to obtain its canonical chunks/embeddings.
        let (real_chunks, real_embs) = encoder_arc
            .embed_paths(tmp.path(), std::slice::from_ref(&file_a), &Profiler::noop())
            .expect("embed_paths");
        let n_real = real_chunks.len();
        assert!(n_real > 0, "file_a.rs must produce at least one chunk");

        let hidden_dim = real_embs[0].len();
        let mut flat: Vec<f32> = Vec::with_capacity(n_real * hidden_dim);
        for row in &real_embs {
            flat.extend(row);
        }
        let embeddings = ndarray::Array2::from_shape_vec((n_real, hidden_dim), flat).unwrap();

        // file_mapping holds stale indices pointing at file_a.rs chunks.
        let rel_key = "file_a.rs".to_string();
        let indices: Vec<usize> = (0..n_real).collect();
        let file_mapping = HashMap::from([(rel_key, indices)]);

        // Manifest is EMPTY: simulates a prior reconcile whose manifest
        // update failed, so diff_against_filesystem classifies file_a.rs
        // as "new" even though file_mapping still references its chunks.
        let manifest = Manifest::new();

        let index = new_for_test(
            real_chunks,
            embeddings,
            std::sync::Arc::clone(&encoder_arc),
            file_mapping,
            HashMap::new(),
            manifest,
            tmp.path().to_path_buf(),
            WalkOptions::default(),
        );

        let diff = index.diff_against_filesystem();
        assert!(
            diff.new.iter().any(|p| p.ends_with("file_a.rs")),
            "file_a.rs must appear in diff.new when manifest is empty; got {:?}",
            diff.new
        );
        assert!(diff.dirty.is_empty(), "no dirty expected");
        assert!(diff.deleted.is_empty(), "no deleted expected");

        // With the fix (diff.new also processed in removed_indices), stale
        // chunks are dropped before re-embedding → chunk count equals
        // one fresh-embed pass. Without the fix, old + new chunks both
        // survive → count is doubled.
        let updated = index
            .apply_diff(&diff, &Profiler::noop())
            .expect("apply_diff");

        let file_a_count = updated
            .chunks()
            .iter()
            .filter(|c| c.file_path.ends_with("file_a.rs"))
            .count();

        assert_eq!(
            file_a_count, n_real,
            "file_a.rs chunk count must equal one fresh-embed pass ({n_real}); \
             got {file_a_count} — stale chunks from file_mapping not cleared"
        );
        assert_eq!(
            updated.embeddings().nrows(),
            updated.chunks().len(),
            "embeddings row count must match chunk count"
        );
    }

    /// Derived: applying an empty diff twice must yield identical chunk
    /// counts — no accumulation from repeated no-op reconciles.
    ///
    /// Gated `#[ignore]` because building a real index requires the
    /// Model2Vec encoder (~32 MB).
    #[test]
    #[ignore = "requires Model2Vec download (~32 MB on first run)"]
    fn apply_diff_no_duplicate_chunks_after_two_passes() {
        use crate::embed::SearchConfig;
        use crate::encoder::ripvec::dense::{DEFAULT_MODEL_REPO, StaticEncoder};
        use crate::profile::Profiler;
        use std::fs;

        let tmp = tempfile::TempDir::new().unwrap();
        fs::write(
            tmp.path().join("main.rs"),
            "fn main() { println!(\"hello\"); }\n",
        )
        .unwrap();

        let encoder = StaticEncoder::from_pretrained(DEFAULT_MODEL_REPO).expect("encoder load");
        let cfg = SearchConfig {
            batch_size: 32,
            max_tokens: 512,
            chunk: crate::chunk::ChunkConfig {
                max_chunk_bytes: 4096,
                window_size: 2048,
                window_overlap: 512,
            },
            text_mode: false,
            cascade_dim: None,
            file_type: None,
            exclude_extensions: Vec::new(),
            include_extensions: Vec::new(),
            ignore_patterns: Vec::new(),
            corpus: crate::embed::Scope::All,
            mode: crate::hybrid::SearchMode::Hybrid,
        };
        let index = RipvecIndex::from_root(tmp.path(), encoder, &cfg, &Profiler::noop(), None, 0.0)
            .expect("from_root");

        let original_count = index.chunks().len();

        let diff1 = index.diff_against_filesystem();
        assert!(diff1.is_empty(), "fresh index must yield empty diff");
        let pass1 = index
            .apply_diff(&diff1, &Profiler::noop())
            .expect("apply_diff pass 1");
        assert_eq!(
            pass1.chunks().len(),
            original_count,
            "chunk count must be unchanged after empty-diff pass 1"
        );

        let diff2 = pass1.diff_against_filesystem();
        assert!(
            diff2.is_empty(),
            "pass1 against unchanged FS must yield empty diff"
        );
        let pass2 = pass1
            .apply_diff(&diff2, &Profiler::noop())
            .expect("apply_diff pass 2");
        assert_eq!(
            pass2.chunks().len(),
            original_count,
            "chunk count must be unchanged after empty-diff pass 2"
        );
    }
}