lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
//! Tests for the BM25 index. Extracted from `bm25_index/mod.rs`;
//! `super::*` resolves to the `bm25_index` module.

use super::*;
use crate::core::context_admission::stores::StoreAdmission;
use tempfile::tempdir;

fn admission() -> StoreAdmission {
    StoreAdmission::current()
}

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

#[test]
fn tokenize_splits_code() {
    let tokens = tokenize("fn calculate_total(items: Vec<Item>) -> f64");
    assert!(tokens.contains(&"calculate_total".to_string()));
    assert!(tokens.contains(&"items".to_string()));
    assert!(tokens.contains(&"Vec".to_string()));
}

#[test]
fn format_search_results_normalizes_windows_separators() {
    // Issue #324: Windows backslash paths in search output were dropped or
    // escape-mangled by client render layers. They must come out with
    // forward slashes.
    let r = SearchResult {
        chunk_idx: 0,
        score: 1.0,
        file_path: r"C:\Users\zir\AppData\Local\Temp\win-build-log.txt".to_string(),
        symbol_name: "main".to_string(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 2,
        snippet: "x".to_string(),
    };
    let compact = format_search_results(std::slice::from_ref(&r), true);
    assert!(compact.contains("C:/Users/zir/AppData/Local/Temp/win-build-log.txt"));
    assert!(!compact.contains('\\'));

    let verbose = format_search_results(std::slice::from_ref(&r), false);
    assert!(verbose.contains("C:/Users/zir/AppData/Local/Temp/win-build-log.txt"));
    assert!(!verbose.contains('\\'));
}

#[test]
fn format_search_results_leaves_external_uris_untouched() {
    // Provider results (e.g. github://) are not OS paths and must not be
    // rewritten.
    let r = SearchResult {
        chunk_idx: 0,
        score: 1.0,
        file_path: "github://owner/repo/issues/42".to_string(),
        symbol_name: "issue".to_string(),
        kind: ChunkKind::Module,
        start_line: 0,
        end_line: 0,
        snippet: "y".to_string(),
    };
    let out = format_search_results(std::slice::from_ref(&r), true);
    assert!(out.contains("github://owner/repo/issues/42"));
}

#[test]
fn camel_case_splitting() {
    let tokens = split_camel_case_tokens(&["calculateTotal".to_string()]);
    assert!(tokens.contains(&"calculateTotal".to_string()));
    assert!(tokens.contains(&"calculate".to_string()));
    assert!(tokens.contains(&"Total".to_string()));
}

#[test]
fn detect_rust_function() {
    let (name, kind) = detect_symbol("pub fn process_request(req: Request) -> Response {").unwrap();
    assert_eq!(name, "process_request");
    assert_eq!(kind, ChunkKind::Function);
}

#[test]
fn bm25_search_finds_relevant() {
    let mut index = BM25Index::new();
    index.add_chunk(CodeChunk {
        file_path: "auth.rs".into(),
        symbol_name: "validate_token".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 10,
        content: "fn validate_token(token: &str) -> bool { check_jwt_expiry(token) }".into(),
        tokens: tokenize("fn validate_token token str bool check_jwt_expiry token"),
        token_count: 8,
    });
    index.add_chunk(CodeChunk {
        file_path: "db.rs".into(),
        symbol_name: "connect_database".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 5,
        content: "fn connect_database(url: &str) -> Pool { create_pool(url) }".into(),
        tokens: tokenize("fn connect_database url str Pool create_pool url"),
        token_count: 7,
    });
    index.finalize();

    let results = index.search("jwt token validation", 5);
    assert!(!results.is_empty());
    assert_eq!(results[0].symbol_name, "validate_token");
}

#[test]
fn structural_signals_disambiguate_same_named_cross_subsystem_results() {
    let mut index = BM25Index::new();
    let mut add = |file: &str, symbol: &str, content: &str| {
        let tokens = tokenize(content);
        let token_count = tokens.len();
        index.add_chunk(CodeChunk {
            file_path: file.into(),
            symbol_name: symbol.into(),
            kind: ChunkKind::Function,
            start_line: 1,
            end_line: 5,
            content: content.into(),
            tokens,
            token_count,
        });
    };
    add(
        "charger/easee/types.go",
        "CircuitSettings",
        "Current Current Current Current GetMaxCurrent circuit settings",
    );
    add(
        "api/actionconfig.go",
        "GetMaxCurrent",
        "GetMaxCurrent returns configured Current",
    );
    add(
        "charger/ocpp.go",
        "GetMaxCurrent",
        "GetMaxCurrent reads Current Offered measurand",
    );
    add(
        "README.md",
        "OCPP",
        "OCPP charger GetMaxCurrent Current Offered",
    );
    index.finalize();

    let results = index.search(
        "OCPP charger GetMaxCurrent Current.Offered measurand CurrentGetter",
        4,
    );

    assert_eq!(results[0].file_path, "charger/ocpp.go");
    let docs = results
        .iter()
        .find(|result| result.file_path == "README.md")
        .expect("documentation result remains available");
    assert!(docs.score < results[0].score);
}

#[test]
fn bm25_search_sorts_ties_deterministically() {
    let mut index = BM25Index::new();

    // Insert in reverse path order to ensure the sort tie-break matters.
    index.add_chunk(CodeChunk {
        file_path: "b.rs".into(),
        symbol_name: "same".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 1,
        content: "fn same() {}".into(),
        tokens: tokenize("same token"),
        token_count: 2,
    });
    index.add_chunk(CodeChunk {
        file_path: "a.rs".into(),
        symbol_name: "same".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 1,
        content: "fn same() {}".into(),
        tokens: tokenize("same token"),
        token_count: 2,
    });
    index.finalize();

    let results = index.search("same", 10);
    assert!(results.len() >= 2);
    assert_eq!(results[0].file_path, "a.rs");
    assert_eq!(results[1].file_path, "b.rs");
}

#[test]
fn bm25_index_is_stale_when_any_indexed_file_is_missing() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write a.rs");

    let idx = BM25Index::build_from_directory(root);
    assert!(!bm25_index_looks_stale(&idx, root));

    std::fs::remove_file(root.join("a.rs")).expect("remove a.rs");
    assert!(bm25_index_looks_stale(&idx, root));
}

#[test]
#[cfg(unix)]
fn bm25_incremental_rebuild_reuses_unchanged_files_without_reading() {
    let td = tempdir().expect("tempdir");
    let root = td.path();

    std::fs::write(root.join("a.rs"), "pub fn a() { println!(\"A\"); }\n").expect("write a.rs");
    std::fs::write(root.join("b.rs"), "pub fn b() { println!(\"B\"); }\n").expect("write b.rs");

    let idx1 = BM25Index::build_from_directory(root);
    assert!(idx1.files.contains_key("a.rs"));
    assert!(idx1.files.contains_key("b.rs"));

    // Make a.rs unreadable. Incremental rebuild must keep it indexed by reusing prior chunks.
    let a_path = root.join("a.rs");
    let mut perms = std::fs::metadata(&a_path).expect("meta a.rs").permissions();
    perms.set_mode(0o000);
    std::fs::set_permissions(&a_path, perms).expect("chmod a.rs");

    // Change b.rs (size changes) to force a re-read for that file.
    std::fs::write(root.join("b.rs"), "pub fn b() { println!(\"B2\"); }\n").expect("rewrite b.rs");

    let idx2 = BM25Index::rebuild_incremental(root, &idx1);
    assert!(
        idx2.files.contains_key("a.rs"),
        "a.rs should be kept via reuse"
    );
    assert!(idx2.files.contains_key("b.rs"));

    let b_has_b2 = idx2
        .chunks
        .iter()
        .any(|c| c.file_path == "b.rs" && c.content.contains("B2"));
    assert!(b_has_b2, "b.rs should be re-read and re-chunked");

    // Restore permissions to avoid cleanup surprises.
    let mut perms = std::fs::metadata(&a_path).expect("meta a.rs").permissions();
    perms.set_mode(0o644);
    let _ = std::fs::set_permissions(&a_path, perms);
}

#[test]
fn add_chunk_truncates_content_to_10_lines() {
    let mut index = BM25Index::new();
    let body_20 = (0..20)
        .map(|i| format!("line{i}"))
        .collect::<Vec<_>>()
        .join("\n");
    index.add_chunk(CodeChunk {
        file_path: "big.rs".into(),
        symbol_name: "big".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 20,
        content: body_20,
        tokens: Vec::new(),
        token_count: 0,
    });
    index.add_chunk(CodeChunk {
        file_path: "small.rs".into(),
        symbol_name: "small".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 3,
        content: "a\nb\nc".into(),
        tokens: Vec::new(),
        token_count: 0,
    });

    let big = index
        .chunks
        .iter()
        .find(|c| c.file_path == "big.rs")
        .unwrap();
    assert_eq!(
        big.content.lines().count(),
        10,
        "20-line body truncated to 10"
    );
    assert!(big.content.starts_with("line0"));
    assert!(
        !big.content.contains("line10"),
        "lines beyond snippet dropped"
    );

    let small = index
        .chunks
        .iter()
        .find(|c| c.file_path == "small.rs")
        .unwrap();
    assert_eq!(small.content, "a\nb\nc", "short body left untouched");
}

#[test]
fn shrink_resident_trims_long_bodies_keeps_short_and_flags() {
    let mut index = BM25Index::new();
    let long_body = (0..20)
        .map(|i| format!("line{i}"))
        .collect::<Vec<_>>()
        .join("\n");
    index.add_chunk(CodeChunk {
        file_path: "long.rs".into(),
        symbol_name: "long".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 20,
        content: long_body,
        tokens: tokenize("long body"),
        token_count: 2,
    });
    index.add_chunk(CodeChunk {
        file_path: "short.rs".into(),
        symbol_name: "short".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 2,
        content: "fn short() {}".into(),
        tokens: tokenize("short body"),
        token_count: 2,
    });
    index.finalize();

    let before = index.memory_usage_bytes();
    assert!(!index.content_truncated);

    index.shrink_resident_content_to_snippet(5);

    assert!(index.content_truncated, "flag must be set after shrink");
    let long_chunk = index
        .chunks
        .iter()
        .find(|c| c.file_path == "long.rs")
        .unwrap();
    assert_eq!(
        long_chunk.content.lines().count(),
        5,
        "long body trimmed to 5 lines"
    );
    assert!(long_chunk.content.starts_with("line0"));
    assert!(
        !long_chunk.content.contains("line5"),
        "lines beyond the snippet window are dropped"
    );

    let short_chunk = index
        .chunks
        .iter()
        .find(|c| c.file_path == "short.rs")
        .unwrap();
    assert_eq!(
        short_chunk.content, "fn short() {}",
        "short body left untouched"
    );

    assert!(
        index.memory_usage_bytes() < before,
        "shrink should reduce reported heap usage"
    );

    // Keyword search snippet still works off the retained lines.
    let results = index.search("line0", 5);
    assert!(!results.is_empty());

    // Idempotent: second shrink is a no-op on already-short content.
    index.shrink_resident_content_to_snippet(5);
    let long_chunk = index
        .chunks
        .iter()
        .find(|c| c.file_path == "long.rs")
        .unwrap();
    assert_eq!(long_chunk.content.lines().count(), 5);
}

#[test]
fn shrink_resident_is_not_persisted_to_disk() {
    let _env = crate::core::data_dir::test_env_lock();
    let data_dir = tempdir().expect("data_dir");
    crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "512");
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(
        root.join("big.rs"),
        "pub fn big() {\n  let a = 1;\n  let b = 2;\n  let c = 3;\n  let d = 4;\n  let e = 5;\n  let f = 6;\n}\n",
    )
    .expect("write");

    let mut index = BM25Index::build_from_directory(root);
    let full_lines: usize = index
        .chunks
        .iter()
        .map(|c| c.content.lines().count())
        .max()
        .unwrap();
    assert!(full_lines > 5, "fixture body must exceed snippet window");

    // add_chunk already truncates to 10-line snippets (#790); the 8-line fixture
    // stays below that threshold so saved content equals the original body.
    // shrink_resident further tightens to 5 lines (resident-only, not persisted).
    index.save(root).expect("save full-content index");
    index.shrink_resident_content_to_snippet(5);
    assert!(index.content_truncated);

    // Reloading from the already-persisted file restores the FULL body, and the
    // resident-only `content_truncated` flag never survives serialization.
    let reloaded = BM25Index::load(root).expect("load");
    assert!(!reloaded.content_truncated, "flag must not survive reload");
    let max_lines: usize = reloaded
        .chunks
        .iter()
        .map(|c| c.content.lines().count())
        .max()
        .unwrap();
    assert_eq!(max_lines, full_lines, "reload restores full content");

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
    crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
}

#[test]
fn load_quarantines_oversized_index() {
    let _env = crate::core::data_dir::test_env_lock();
    let td = tempdir().expect("tempdir");
    let root = td.path();
    let dir = crate::core::index_namespace::vectors_dir(root);
    std::fs::create_dir_all(&dir).expect("create vectors dir");

    let index_path = dir.join("bm25_index.json");
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "0");
    std::fs::write(&index_path, r#"{"chunks":[]}"#).expect("write index");

    let result = BM25Index::load(root);
    assert!(result.is_none(), "oversized index should return None");
    assert!(
        !index_path.exists(),
        "original index should be removed after quarantine"
    );
    assert!(
        dir.join("bm25_index.json.quarantined").exists(),
        "quarantined file should exist"
    );

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
}

#[test]
fn save_refuses_oversized_output() {
    let _env = crate::core::data_dir::test_env_lock();
    let data_dir = tempdir().expect("data_dir");
    crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "0");

    let td = tempdir().expect("tempdir");
    let root = td.path();

    let mut index = BM25Index::new();
    index.add_chunk(CodeChunk {
        file_path: "a.rs".into(),
        symbol_name: "a".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 1,
        content: "fn a() {}".into(),
        tokens: tokenize("fn a"),
        token_count: 2,
    });
    index.finalize();

    let outcome = index
        .save(root)
        .expect("save returns Ok even when refusing");
    assert!(
        matches!(outcome, SaveOutcome::SkippedTooLarge { .. }),
        "oversized save must report SkippedTooLarge (not a silent success), got {outcome:?}"
    );
    let index_path = BM25Index::index_file_path(root);
    assert!(
        !index_path.exists(),
        "save should refuse to persist oversized index"
    );

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
}

#[test]
fn save_reports_persisted_outcome() {
    let _env = crate::core::data_dir::test_env_lock();
    let data_dir = tempdir().expect("data_dir");
    crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "512");
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("a.rs"), "pub fn alpha() {}\n").expect("write");

    let index = BM25Index::build_from_directory(root);
    let outcome = index.save(root).expect("save");
    match outcome {
        SaveOutcome::Persisted { compressed_bytes } => {
            assert!(compressed_bytes > 0, "persisted size should be non-zero");
        }
        SaveOutcome::SkippedTooLarge { .. } => {
            panic!("expected Persisted, got {outcome:?}")
        }
    }

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
    crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
}

#[test]
fn persist_ceiling_honors_env_override() {
    // The public ceiling accessor (shared with doctor) must honor an explicit
    // override exactly, so operators can size it to their monorepo.
    let _env = crate::core::data_dir::test_env_lock();
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "777");
    assert_eq!(persist_ceiling_bytes(), 777 * 1024 * 1024);
    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
}

#[test]
fn save_writes_project_root_marker() {
    let _env = crate::core::data_dir::test_env_lock();
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write");

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
    let index = BM25Index::build_from_directory(root);
    index.save(root).expect("save");

    let dir = crate::core::index_namespace::vectors_dir(root);
    let marker = dir.join("project_root.txt");
    assert!(marker.exists(), "project_root.txt marker should exist");
    let content = std::fs::read_to_string(&marker).expect("read marker");
    assert_eq!(content, root.to_string_lossy());
}

#[test]
fn save_load_roundtrip_uses_zstd() {
    let _env = crate::core::data_dir::test_env_lock();
    let data_dir = tempdir().expect("data_dir");
    crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "512");
    let td = tempdir().expect("tempdir");
    let root = td.path();

    for i in 0..10 {
        std::fs::write(
            root.join(format!("mod{i}.rs")),
            format!(
                "pub fn handler_{i}() {{\n    println!(\"hello\");\n}}\n\n\
                     pub fn helper_{i}() {{\n    println!(\"world\");\n}}\n"
            ),
        )
        .expect("write");
    }

    let index = BM25Index::build_from_directory(root);
    assert!(index.doc_count > 0, "should have indexed chunks");
    index.save(root).expect("save");

    let dir = crate::core::index_namespace::vectors_dir(root);
    let zst = dir.join("bm25_index.bin.zst");
    assert!(zst.exists(), "should write .bin.zst");
    assert!(
        !dir.join("bm25_index.bin").exists(),
        ".bin should be deleted"
    );

    let loaded = BM25Index::load(root).expect("load compressed index");
    assert_eq!(loaded.doc_count, index.doc_count);
    assert_eq!(loaded.chunks.len(), index.chunks.len());

    // AP05-G8: the recorded root is the authority. Another root's index is
    // not loaded; the same root spelled differently (canonical) is.
    let marker = dir.join("project_root.txt");
    let other = tempdir().expect("other root");
    std::fs::write(&marker, other.path().to_string_lossy().as_bytes()).expect("marker");
    assert!(BM25Index::load(root).is_none());
    let canonical = root.canonicalize().expect("canonical root");
    std::fs::write(&marker, canonical.join(".").to_string_lossy().as_bytes()).expect("marker");
    assert!(BM25Index::load(root).is_some());

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
    crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
}

#[test]
fn auto_migrate_bin_to_zst() {
    let _env = crate::core::data_dir::test_env_lock();
    let data_dir = tempdir().expect("data_dir");
    crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "512");
    let td = tempdir().expect("tempdir");
    let root = td.path();

    std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write");
    let index = BM25Index::build_from_directory(root);

    let dir = crate::core::index_namespace::vectors_dir(root);
    std::fs::create_dir_all(&dir).expect("mkdir");
    let data = postcard::to_allocvec(&index).expect("encode");
    std::fs::write(dir.join("bm25_index.bin"), &data).expect("write bin");

    let loaded = BM25Index::load(root).expect("load should auto-migrate");
    assert_eq!(loaded.doc_count, index.doc_count);
    assert!(
        dir.join("bm25_index.bin.zst").exists(),
        ".bin.zst should be created"
    );
    assert!(
        !dir.join("bm25_index.bin").exists(),
        ".bin should be removed"
    );

    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
    crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
}

#[test]
fn postcard_roundtrip_and_garbage_is_graceful() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("a.rs"), "pub fn a() {}\npub fn b() {}\n").expect("write");
    let index = BM25Index::build_from_directory(root);
    assert!(
        index.doc_count > 0,
        "fixture must produce at least one chunk"
    );

    // (a) postcard round-trip: encode → decode → structural equality.
    let data = postcard::to_allocvec(&index).expect("postcard encode");
    let decoded: BM25Index = postcard::from_bytes(&data).expect("postcard decode");
    assert_eq!(
        decoded.doc_count, index.doc_count,
        "doc_count survives round-trip"
    );
    assert_eq!(
        decoded.chunks.len(),
        index.chunks.len(),
        "chunk count survives round-trip"
    );

    // (b) corrupt/legacy bytes must NOT panic — decode returns Err,
    //     which load() maps via .ok()? to None (→ rebuild), never a crash.
    let garbage = b"\x00\x01\x02not-a-valid-postcard-index\xff\xff";
    let res: Result<BM25Index, _> = postcard::from_bytes(garbage);
    assert!(
        res.is_err(),
        "corrupt/legacy bytes must decode to Err, not panic"
    );
}

#[test]
fn list_code_files_skips_default_vendor_ignores() {
    let td = tempdir().expect("tempdir");
    let root = td.path();

    std::fs::write(root.join("main.rs"), "pub fn main() {}\n").expect("write main");
    std::fs::create_dir_all(root.join("vendor/lib")).expect("mkdir vendor");
    std::fs::write(root.join("vendor/lib/dep.rs"), "pub fn dep() {}\n").expect("write vendor");
    std::fs::create_dir_all(root.join("dist")).expect("mkdir dist");
    std::fs::write(root.join("dist/bundle.js"), "function x() {}").expect("write dist");

    let files = list_code_files(root);
    assert!(
        files.iter().any(|f| f == "main.rs"),
        "main.rs should be included"
    );
    assert!(
        !files.iter().any(|f| f.starts_with("vendor/")),
        "vendor/ files should be excluded by DEFAULT_BM25_IGNORES"
    );
    assert!(
        !files.iter().any(|f| f.starts_with("dist/")),
        "dist/ files should be excluded by DEFAULT_BM25_IGNORES"
    );
}

#[test]
fn list_code_files_includes_extractable_pdf() {
    let td = tempdir().expect("tempdir");
    let root = td.path();

    std::fs::write(root.join("main.rs"), "pub fn main() {}\n").expect("write main");
    // A PDF is a binary document with a dedicated extractor: it must reach the
    // indexer (gate change) even though office binaries without one do not.
    std::fs::write(root.join("report.pdf"), b"%PDF-1.7\n%stub\n").expect("write pdf");
    std::fs::write(root.join("sheet.xlsx"), b"PK\x03\x04binary").expect("write xlsx");

    let files = list_code_files(root);
    assert!(
        files.iter().any(|f| f == "report.pdf"),
        "report.pdf should be ingestible via the extractor"
    );
    assert!(
        !files.iter().any(|f| f == "sheet.xlsx"),
        "office binaries without an extractor stay excluded"
    );
}

/// GHSA-rxv5-4c3x-g4q6 A: secret-like files never enter the persisted index,
/// even with the context gateway (store admission) switched off.
#[test]
fn list_code_files_skips_secret_like_paths() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("main.rs"), "pub fn main() {}\n").expect("main");
    std::fs::create_dir_all(root.join("config")).expect("mkdir config");
    std::fs::create_dir_all(root.join(".ssh")).expect("mkdir ssh");
    for rel in [
        ".env",
        ".env.production",
        "server.pem",
        "config/secrets.yaml",
        ".ssh/config",
    ] {
        std::fs::write(root.join(rel), "canary_value = 1\n").expect("write secret-like");
    }

    let files = list_code_files(root);
    assert_eq!(files, vec!["main.rs".to_string()], "{files:?}");
}

/// An index persisted before the exclusion (or with the gateway off) that
/// still tracks a secret-like file is stale, so the next load rebuilds it
/// without that file.
#[test]
fn persisted_index_tracking_a_secret_like_file_is_stale() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("main.rs"), "pub fn main() {}\n").expect("main");
    std::fs::write(root.join(".env"), "canary_value = 1\n").expect("env");
    let mut index = BM25Index::build_from_directory(root);
    assert!(!index.files.contains_key(".env"));
    assert!(!bm25_index_looks_stale(&index, root));
    let state = IndexedFileState::from_path(&root.join(".env")).expect("state");
    index.files.insert(".env".to_string(), state);
    index.add_chunk(CodeChunk {
        file_path: ".env".to_string(),
        symbol_name: ".env".to_string(),
        kind: ChunkKind::Module,
        start_line: 1,
        end_line: 1,
        content: "canary_value = 1".to_string(),
        tokens: Vec::new(),
        token_count: 0,
    });
    assert!(bm25_index_looks_stale(&index, root));
    assert!(bm25_index_looks_stale_fast(&index, root));
    let rebuilt = BM25Index::rebuild_incremental(root, &index);
    assert!(!rebuilt.files.contains_key(".env"));
    assert!(rebuilt.chunks.iter().all(|c| c.file_path != ".env"));
}

/// Rendered snippets are masked like `ctx_read`/`ctx_search` output.
#[test]
fn format_search_results_redacts_secret_values() {
    let _lock = crate::core::data_dir::test_env_lock();
    let key = concat!("AK", "IAIOSFODNN7EXAMPLE");
    let r = SearchResult {
        chunk_idx: 0,
        score: 1.0,
        file_path: "deploy/settings.py".to_string(),
        symbol_name: "settings".to_string(),
        kind: ChunkKind::Module,
        start_line: 1,
        end_line: 1,
        snippet: format!("AWS_ACCESS_KEY_ID = \"{key}\""),
    };
    let out = format_search_results(std::slice::from_ref(&r), false);
    assert!(!out.contains(key), "{out}");
    assert!(out.contains("deploy/settings.py"), "{out}");
}

#[test]
fn list_code_files_honors_bm25_max_files_config() {
    // The cap is handed in as a `Config` value, not through
    // LEAN_CTX_CONFIG_DIR: pointing the process-wide config at a
    // `bm25_max_files = 3` file leaked that cap into every parallel test that
    // reads the config without the env lock — e.g. the public
    // `build_from_directory` indexed 3 files where its own listing saw 41.
    let td = tempdir().expect("tempdir");
    let root = td.path();

    for i in 0..6 {
        std::fs::write(
            root.join(format!("f{i}.rs")),
            format!("pub fn f{i}() {{}}\n"),
        )
        .expect("write");
    }

    let cfg = crate::core::config::Config {
        bm25_max_files: 3,
        ..Default::default()
    };
    let files = list_code_files_with(root, &CorpusRules::from_config(&cfg));

    assert_eq!(
        files.len(),
        3,
        "bm25_max_files should bound the BM25 corpus"
    );
}

/// Regression: a semantic search scoped to a small directory of a project over
/// the file budget failed with "source file budget exceeded" — the whole
/// project was walked and counted before the scope was applied.
#[test]
fn scoped_listing_counts_only_in_scope_sources() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::create_dir_all(root.join("big")).expect("mkdir");
    std::fs::create_dir_all(root.join("small/inner")).expect("mkdir");
    for i in 0..6 {
        std::fs::write(root.join(format!("big/f{i}.rs")), "pub fn f() {}\n").expect("write");
    }
    std::fs::write(root.join("small/a.rs"), "pub fn a() {}\n").expect("write");
    std::fs::write(root.join("small/inner/b.py"), "def b(): pass\n").expect("write");

    let cfg = crate::core::config::Config {
        bm25_max_files: 3,
        ..Default::default()
    };
    let rules = CorpusRules::from_config(&cfg);
    let err = list_scoped_code_files(root, &rules, true, None, &|_| true)
        .expect_err("unscoped walk is over budget and fails closed");
    assert!(
        err.contains("bm25_max_files"),
        "error names the remedy: {err}"
    );

    let scoped = list_scoped_code_files(root, &rules, true, Some("small"), &|_| true)
        .expect("a scoped walk stays within budget");
    let scoped: Vec<String> = scoped.iter().map(|p| p.replace('\\', "/")).collect();
    assert_eq!(
        scoped,
        ["small/a.rs", "small/inner/b.py"],
        "paths stay project-relative"
    );

    let rust_only = list_scoped_code_files(root, &rules, true, None, &|p| {
        p.starts_with("small")
            && std::path::Path::new(p)
                .extension()
                .is_some_and(|e| e == "rs")
    })
    .expect("a filtered walk counts only matching files");
    assert_eq!(rust_only.len(), 1);
}

#[test]
fn max_bm25_cache_bytes_reads_env() {
    let _env = crate::core::data_dir::test_env_lock();
    crate::test_env::set_var("LEAN_CTX_BM25_MAX_CACHE_MB", "64");
    let bytes = max_bm25_cache_bytes();
    assert_eq!(bytes, 64 * 1024 * 1024);
    crate::test_env::remove_var("LEAN_CTX_BM25_MAX_CACHE_MB");
}

// ---- #933: parallel build determinism ----

/// Write a varied corpus that exercises the multi-chunk symbol path, the
/// fallback (prose) chunker, camelCase splitting and repeated-token `doc_freqs`
/// dedup. Returns the sorted relative paths.
fn write_parallel_corpus(root: &std::path::Path, n: usize) -> Vec<String> {
    std::fs::create_dir_all(root.join("src")).expect("mkdir src");
    std::fs::create_dir_all(root.join("docs")).expect("mkdir docs");
    let mut files = Vec::new();
    for i in 0..n {
        let rel = format!("src/mod_{i:03}.rs");
        let content = format!(
            "pub fn process_item_{i}(item: Item) -> Result<Item> {{\n    \
             let processedValue = transformItem(item);\n    \
             validate(processedValue); validate(processedValue);\n    \
             Ok(processedValue)\n}}\n\n\
             pub struct DataHolder{i} {{\n    field_one: String,\n    field_two: usize,\n}}\n\n\
             // shared keyword repeated repeated repeated across files\n"
        );
        std::fs::write(root.join(&rel), content).expect("write src");
        files.push(rel);
    }
    let notes = "docs/notes.md".to_string();
    std::fs::write(
        root.join(&notes),
        "# Notes\n\nProse with CamelCaseWords and snake_case_words.\n\
         Repeated repeated tokens exercise document-frequency counting.\n",
    )
    .expect("write notes");
    files.push(notes);
    files.sort();
    files.dedup();
    files
}

/// Assert two indexes are logically identical: same chunk order, same inverted
/// postings, same `doc_freqs`, same file set and corpus statistics. This is the
/// determinism contract between the parallel and sequential builds (#933/#498).
fn assert_same_index(a: &BM25Index, b: &BM25Index) {
    assert_eq!(a.doc_count, b.doc_count, "doc_count");
    assert_eq!(a.chunks, b.chunks, "chunk vector (order + content)");
    assert_eq!(a.inverted, b.inverted, "inverted index");
    assert_eq!(a.doc_freqs, b.doc_freqs, "doc_freqs");
    assert_eq!(a.files, b.files, "tracked files");
    assert_eq!(
        a.avg_doc_len.to_bits(),
        b.avg_doc_len.to_bits(),
        "avg_doc_len"
    );
}

#[test]
fn parallel_build_matches_sequential() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    let files = write_parallel_corpus(root, 40);

    let hint = HashMap::new();
    let seq = BM25Index::build_sequential(root, &hint, &files, &admission());
    let par = BM25Index::build_parallel(root, &hint, &files, &admission());

    assert!(par.doc_count > files.len(), "expected multiple chunks/file");
    assert_same_index(&seq, &par);
}

#[test]
fn parallel_build_is_deterministic_across_runs() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    let files = write_parallel_corpus(root, 48);
    let hint = HashMap::new();

    let a = BM25Index::build_parallel(root, &hint, &files, &admission());
    let b = BM25Index::build_parallel(root, &hint, &files, &admission());
    assert_same_index(&a, &b);
}

/// #685: the batched parallel build must merge multiple batches into the same
/// index a single-batch (or sequential) build produces. Batch size 7 over 40
/// files forces 6 batch boundaries through the merge loop.
#[test]
fn parallel_build_batched_merge_matches_sequential() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    let files = write_parallel_corpus(root, 40);
    let hint = HashMap::new();

    let seq = BM25Index::build_sequential(root, &hint, &files, &admission());
    let batched = BM25Index::build_parallel_batched(root, &hint, &files, 7, &admission());
    assert_same_index(&seq, &batched);
}

#[test]
fn build_from_directory_dispatches_parallel_and_matches_sequential() {
    // >= PARALLEL_MIN_FILES files so the public entry point takes the parallel
    // path; its result must equal an explicit sequential build over the same set.
    let td = tempdir().expect("tempdir");
    let root = td.path();
    write_parallel_corpus(root, 40);

    let files = list_code_files(root);
    assert!(
        files.len() >= super::build::PARALLEL_MIN_FILES,
        "corpus must trigger the parallel path"
    );

    let public = BM25Index::build_from_directory(root);
    let seq = BM25Index::build_sequential(root, &HashMap::new(), &files, &admission());
    assert_same_index(&seq, &public);
}

// ---- #581: parallel incremental rebuild determinism ----

/// Mutate a freshly-built corpus to exercise every incremental branch — a
/// changed file (re-extract), a new file, a removed file, and many unchanged
/// files (reuse) — then assert the parallel and sequential incremental rebuilds
/// produce a byte-identical index over the same `prev` + disk state.
#[test]
fn parallel_incremental_matches_sequential() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    write_parallel_corpus(root, 40);

    // Build the baseline index (the corpus is large enough to take the parallel
    // full-build path), then mutate disk so the rebuild hits all branches.
    let prev = BM25Index::build_from_directory(root);
    // `files` keys and `chunk.file_path` keep the OS-native separator (output is
    // normalized to '/' only at render time, #324); build expected keys the same
    // way so these lookups also hit on Windows (`src\mod_001.rs`).
    let key = |rel: &str| rel.replace('/', std::path::MAIN_SEPARATOR_STR);
    assert!(prev.files.contains_key(&key("src/mod_001.rs")));

    // Changed: different body (and size) forces a re-extract.
    std::fs::write(
        root.join("src/mod_000.rs"),
        "pub fn changed_entry() -> usize {\n    let recomputed = 42 + 7;\n    recomputed\n}\n",
    )
    .expect("rewrite mod_000");
    // New file the baseline never saw.
    std::fs::write(
        root.join("src/mod_new.rs"),
        "pub fn brand_new(token: Token) -> Token {\n    token\n}\n",
    )
    .expect("write mod_new");
    // Removed file must drop out of the rebuilt index.
    std::fs::remove_file(root.join("src/mod_001.rs")).expect("remove mod_001");

    let old_by_file = BM25Index::group_prev_chunks_by_file(&prev);
    let files = list_code_files(root);
    assert!(
        files.len() >= super::build::PARALLEL_MIN_FILES,
        "corpus must trigger the parallel rebuild path"
    );

    let seq =
        BM25Index::rebuild_incremental_sequential(root, &prev, &old_by_file, &files, &admission());
    let par =
        BM25Index::rebuild_incremental_parallel(root, &prev, &old_by_file, &files, &admission());

    // The whole contract: identical chunk order, postings, doc_freqs, file set.
    assert_same_index(&seq, &par);

    // And the mutation actually exercised every branch (guards against a vacuous
    // pass where nothing changed).
    assert!(par.files.contains_key(&key("src/mod_000.rs")));
    assert!(par.files.contains_key(&key("src/mod_new.rs")));
    assert!(
        !par.files.contains_key(&key("src/mod_001.rs")),
        "removed file must not survive the rebuild"
    );
    assert!(
        par.chunks
            .iter()
            .any(|c| c.file_path == key("src/mod_000.rs") && c.content.contains("recomputed")),
        "changed file must be re-extracted with new content"
    );
}

/// The public `rebuild_incremental` dispatcher must take the parallel path for a
/// large corpus yet match an explicit sequential rebuild over the same inputs —
/// guards the dispatch wiring the way the full-build test guards `build()`.
#[test]
fn rebuild_incremental_dispatches_parallel_and_matches_sequential() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    write_parallel_corpus(root, 40);

    let prev = BM25Index::build_from_directory(root);
    std::fs::write(
        root.join("src/mod_005.rs"),
        "pub fn touched() -> bool {\n    true\n}\n",
    )
    .expect("rewrite mod_005");

    let old_by_file = BM25Index::group_prev_chunks_by_file(&prev);
    let files = list_code_files(root);
    assert!(files.len() >= super::build::PARALLEL_MIN_FILES);

    let public = BM25Index::rebuild_incremental(root, &prev);
    let seq =
        BM25Index::rebuild_incremental_sequential(root, &prev, &old_by_file, &files, &admission());
    assert_same_index(&seq, &public);
}

/// CI build-time regression gate for the parallel incremental rebuild
/// (#581, locking in #933). Off by default — wall-clock timing is meaningless
/// under the concurrent local / nextest runner — so it no-ops unless the CI job
/// sets `LEAN_CTX_PERF_GATE=1` and runs it on a quiet, single-threaded runner.
/// Asserts the parallel rebuild is not slower than the sequential one
/// (best-of-3, generous noise slack) and stays under a catastrophic-blowup
/// ceiling, without depending on a specific core count.
#[test]
fn parallel_incremental_rebuild_perf_gate() {
    if std::env::var("LEAN_CTX_PERF_GATE").as_deref() != Ok("1") {
        return; // CI-only gate; no-op elsewhere to avoid timing flakes
    }

    let td = tempdir().expect("tempdir");
    let root = td.path();
    write_parallel_corpus(root, 240);

    let prev = BM25Index::build_from_directory(root);
    // Touch a handful so the rebuild does real re-extraction on top of the reuse
    // path; the bulk stays unchanged — the realistic edit-loop shape.
    for i in [0usize, 60, 120, 180] {
        std::fs::write(
            root.join(format!("src/mod_{i:03}.rs")),
            format!("pub fn touched_{i}() -> usize {{ {i} }}\n"),
        )
        .expect("touch file");
    }

    let old_by_file = BM25Index::group_prev_chunks_by_file(&prev);
    let files = list_code_files(root);

    let best = |f: &dyn Fn() -> std::time::Duration| (0..3).map(|_| f()).min().unwrap();
    let seq = best(&|| {
        let t = std::time::Instant::now();
        let idx = BM25Index::rebuild_incremental_sequential(
            root,
            &prev,
            &old_by_file,
            &files,
            &admission(),
        );
        std::hint::black_box(&idx);
        t.elapsed()
    });
    let par = best(&|| {
        let t = std::time::Instant::now();
        let idx = BM25Index::rebuild_incremental_parallel(
            root,
            &prev,
            &old_by_file,
            &files,
            &admission(),
        );
        std::hint::black_box(&idx);
        t.elapsed()
    });

    eprintln!(
        "[perf-gate] incremental rebuild: seq={seq:?} par={par:?} ratio={:.2}",
        par.as_secs_f64() / seq.as_secs_f64().max(f64::MIN_POSITIVE)
    );

    // CI-safe gate (plan: "großzügiges CI-sicheres Budget"). The parallel path
    // must not be *dramatically* slower than sequential: a 2x ceiling flags a path
    // that serialized and piled on overhead (e.g. a deadlock-y merge), while
    // tolerating scheduler noise and low-core CI runners where a small fixture's
    // parallel speedup shrinks. Byte-for-byte equivalence is asserted separately
    // (parallel_incremental_matches_sequential), so this guard only has to catch a
    // catastrophic perf regression — not police a tight ratio that would flake.
    assert!(
        par.as_secs_f64() <= seq.as_secs_f64() * 2.0,
        "parallel incremental rebuild regressed: par={par:?} > seq*2 ({:?})",
        seq.mul_f64(2.0)
    );
    // Absolute blowup ceiling, generous for a slow debug CI runner.
    assert!(
        par < std::time::Duration::from_secs(30),
        "parallel incremental rebuild absurdly slow: {par:?}"
    );
}

#[test]
fn parallel_build_search_parity() {
    // End-to-end: the parallel index must rank a query identically to the
    // sequential one (same scores, same order).
    let td = tempdir().expect("tempdir");
    let root = td.path();
    let files = write_parallel_corpus(root, 40);
    let hint = HashMap::new();

    let seq = BM25Index::build_sequential(root, &hint, &files, &admission());
    let par = BM25Index::build_parallel(root, &hint, &files, &admission());

    let q = "process item transform";
    let rs = seq.search(q, 10);
    let rp = par.search(q, 10);
    assert!(!rp.is_empty(), "query should return hits");
    assert_eq!(rs.len(), rp.len(), "result count");
    for (s, p) in rs.iter().zip(rp.iter()) {
        assert_eq!(s.file_path, p.file_path);
        assert_eq!(s.symbol_name, p.symbol_name);
        assert_eq!(s.start_line, p.start_line);
        assert_eq!(s.score.to_bits(), p.score.to_bits(), "score parity");
    }
}

/// Evicting a chunk shifts the chunks behind it; their postings must follow.
/// With stale postings the query below addressed a position past the end.
#[test]
fn search_after_eviction_finds_the_chunk_that_moved() {
    let chunk = |file: &str, symbol: &str, content: &str| CodeChunk {
        file_path: file.into(),
        symbol_name: symbol.into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 1,
        content: content.into(),
        tokens: Vec::new(),
        token_count: 0,
    };
    let mut index = BM25Index::from_chunks_for_test(vec![
        chunk("health://complexity/a", "evicted", "evictedterm only here"),
        chunk("src/kept.rs", "kept", "survivorterm lives here"),
    ]);

    assert_eq!(index.remove_chunks_with_prefix("health://"), 1);

    let hits = index.search("survivorterm", 5);
    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].file_path, "src/kept.rs");
    assert_eq!(hits[0].chunk_idx, 0);
    assert!(index.search("evictedterm", 5).is_empty());
    assert!(!index.doc_freqs.contains_key("evictedterm"));
}

#[test]
fn remove_chunks_with_prefix_evicts_only_matching() {
    use crate::core::content_chunk::ContentChunk;

    let mut index = BM25Index::from_chunks_for_test(vec![CodeChunk {
        file_path: "src/lib.rs".into(),
        symbol_name: "main".into(),
        kind: ChunkKind::Function,
        start_line: 1,
        end_line: 2,
        content: "fn main() {}".into(),
        tokens: Vec::new(),
        token_count: 0,
    }]);
    index.ingest_content_chunks(vec![
        ContentChunk::from_provider(
            "health",
            "complexity",
            "src/a.rs#big",
            "big",
            ChunkKind::Other,
            "complex function body".into(),
            vec![],
            None,
        ),
        ContentChunk::from_provider(
            "github",
            "issues",
            "42",
            "bug",
            ChunkKind::Issue,
            "issue text".into(),
            vec![],
            None,
        ),
    ]);
    assert_eq!(index.chunks.len(), 3);

    let removed = index.remove_chunks_with_prefix("health://");
    assert_eq!(removed, 1, "only the health chunk is evicted");
    assert_eq!(index.chunks.len(), 2);
    assert!(
        index
            .chunks
            .iter()
            .all(|c| !c.file_path.starts_with("health://")),
        "no health chunks remain"
    );
    // Code chunk and the unrelated provider chunk survive.
    assert!(index.chunks.iter().any(|c| c.file_path == "src/lib.rs"));
    assert!(
        index
            .chunks
            .iter()
            .any(|c| c.file_path.starts_with("github://"))
    );
    // A no-match prefix is a no-op.
    assert_eq!(index.remove_chunks_with_prefix("nope://"), 0);
}

// ── #1724: a path-scoped sibling project kept answering from its first,
// partial tree. The fast staleness check only samples files it already knows,
// so files added after that first build stayed invisible forever.

#[test]
fn fast_stale_check_sees_files_added_after_the_first_build() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("main.go"), "package main\nfunc main() {}\n").expect("write main.go");

    let idx = BM25Index::build_from_directory(root);
    assert!(
        !bm25_index_looks_stale_fast(&idx, root),
        "a freshly built index is current"
    );

    // The reporter's case: a whole subsystem directory appears afterwards.
    std::fs::create_dir_all(root.join("replacement")).expect("mkdir replacement");
    std::fs::write(
        root.join("replacement").join("docker.go"),
        "package replacement\nfunc ReplaceContainer() {}\n",
    )
    .expect("write docker.go");

    assert!(
        bm25_index_looks_stale_fast(&idx, root),
        "files added after the build must invalidate the sampled fast check"
    );
}

#[test]
fn load_or_build_fast_reindexes_after_new_files_land() {
    let _env = crate::core::data_dir::test_env_lock();
    let data_dir = tempdir().expect("data_dir");
    crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("main.go"), "package main\nfunc main() {}\n").expect("write main.go");

    // First path-scoped call: builds and persists the (then complete) index.
    let first = BM25Index::load_or_build_fast(root);
    assert!(first.files.keys().any(|f| f.ends_with("main.go")));
    assert!(
        first.search("ReplaceContainer", 5).is_empty(),
        "the subsystem does not exist yet"
    );

    std::fs::create_dir_all(root.join("replacement")).expect("mkdir replacement");
    std::fs::write(
        root.join("replacement").join("docker.go"),
        "package replacement\nfunc ReplaceContainer() {}\n",
    )
    .expect("write docker.go");

    // Second call must not silently serve the earlier partial tree.
    let second = BM25Index::load_or_build_fast(root);
    assert!(
        second.files.keys().any(|f| f.ends_with("docker.go")),
        "newly added files must be indexed: {:?}",
        second.files.keys().collect::<Vec<_>>()
    );
    assert!(
        !second.search("ReplaceContainer", 5).is_empty(),
        "the new subsystem must be searchable"
    );

    crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
}

#[test]
fn directory_snapshot_covers_root_and_every_ancestor() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::create_dir_all(root.join("moby").join("client")).expect("mkdir");
    std::fs::write(
        root.join("moby").join("client").join("api.go"),
        "package client\nfunc Ping() {}\n",
    )
    .expect("write api.go");

    let idx = BM25Index::build_from_directory(root);
    assert!(idx.dirs.contains_key(""), "root is always recorded");
    assert_eq!(
        idx.dirs.len(),
        3,
        "root + moby + moby/client: {:?}",
        idx.dirs.keys().collect::<Vec<_>>()
    );

    // A new top-level directory is caught through the recorded root even though
    // its own mtime was never seen.
    std::fs::create_dir_all(root.join("replacement")).expect("mkdir replacement");
    assert!(bm25_index_looks_stale_fast(&idx, root));
}

#[test]
fn index_without_directory_snapshot_is_refreshed_once() {
    let td = tempdir().expect("tempdir");
    let root = td.path();
    std::fs::write(root.join("a.rs"), "pub fn a() {}\n").expect("write a.rs");

    // An index persisted before #1724 carries no directory snapshot, so its
    // freshness cannot be proven cheaply: report it stale exactly once.
    let mut legacy = BM25Index::build_from_directory(root);
    legacy.dirs.clear();
    assert!(bm25_index_looks_stale_fast(&legacy, root));

    let refreshed = BM25Index::rebuild_incremental(root, &legacy);
    assert!(
        !refreshed.dirs.is_empty(),
        "the rebuild records the snapshot"
    );
    assert!(
        !bm25_index_looks_stale_fast(&refreshed, root),
        "and the next call takes the cheap path again"
    );
}

#[test]
fn decompression_ceiling_follows_the_file_and_the_host_not_a_disk_budget() {
    // #1739: the ceiling was `max_bm25_cache_bytes() * 20` — on the default
    // 512 MB disk budget that authorised a 10 GB allocation for *any* index.
    let tiny = max_decompressed_bytes(1024);
    let ram = crate::core::memory_guard::rss_limit_bytes();

    assert!(
        tiny <= 64 * 1024 * 1024 || Some(tiny) == ram.map(|r| r.max(64 * 1024 * 1024)),
        "a 1 KB index must not authorise more than the floor, got {tiny}"
    );
    assert!(
        max_decompressed_bytes(10 * 1024 * 1024) >= max_decompressed_bytes(1024),
        "the ceiling must not shrink as the file grows"
    );
    if let Some(limit) = ram {
        assert!(
            max_decompressed_bytes(u64::MAX / 32) <= limit.max(64 * 1024 * 1024),
            "the host's RSS limit must cap the ceiling"
        );
    }

    // The streaming guard still refuses payloads past whatever ceiling applies.
    let payload = vec![b'x'; 4 * 1024 * 1024];
    let compressed = zstd::encode_all(payload.as_slice(), 3).expect("compress");
    assert!(bounded_zstd_decode(&compressed, 1024 * 1024).is_none());
    assert_eq!(
        bounded_zstd_decode(&compressed, 8 * 1024 * 1024).map(|out| out.len()),
        Some(payload.len())
    );
}

#[test]
fn minified_payloads_stay_out_of_the_index() {
    // #1739 end-to-end: a committed vendor bundle next to real source must not
    // reach the chunker, while the source next to it indexes normally.
    let dir = tempdir().expect("tempdir");
    let root = dir.path();
    std::fs::write(
        root.join("app.rs"),
        "pub fn distinctive_helper_name() -> i32 {\n    41 + 1\n}\n",
    )
    .expect("write source");
    std::fs::write(
        root.join("swagger-ui-bundle.js"),
        format!(
            "!function(){{{}}}();",
            "var distinctiveBundleToken=1;".repeat(20_000)
        ),
    )
    .expect("write bundle");

    let index = BM25Index::build_from_directory(root);

    assert!(
        index.files.contains_key("app.rs"),
        "real source must still be indexed, got {:?}",
        index.files.keys().collect::<Vec<_>>()
    );
    assert!(
        !index.files.contains_key("swagger-ui-bundle.js"),
        "the minified bundle must be skipped, got {:?}",
        index.files.keys().collect::<Vec<_>>()
    );
}

#[test]
fn persisted_chunk_count_reads_the_length_prefix_without_loading() {
    let _data = crate::core::data_dir::isolated_data_dir();
    let td = tempdir().expect("tempdir");
    let root = td.path();
    assert_eq!(
        BM25Index::persisted_chunk_count(root),
        None,
        "nothing saved yet"
    );

    BM25Index::default().save(root).expect("save empty index");
    assert_eq!(
        BM25Index::persisted_chunk_count(root),
        Some(0),
        "an empty index must report zero chunks, not look ready"
    );

    let mut body = String::new();
    for i in 0..200 {
        body.push_str(&format!("pub fn f{i}() -> u32 {{ {i} }}\n\n"));
    }
    std::fs::write(root.join("many.rs"), body).expect("write");
    let index = BM25Index::build_from_directory(root);
    assert!(
        index.chunks.len() > 127,
        "fixture must need a multi-byte varint"
    );
    index.save(root).expect("save");
    assert_eq!(
        BM25Index::persisted_chunk_count(root),
        Some(index.chunks.len() as u64)
    );
}