ripvec-core 4.1.14

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
use ripvec_core::repo_map::{self, Definition};
use streaming_iterator::StreamingIterator as _;

/// Parse `source` as the language identified by `ext` and extract call sites,
/// returning the list of [`Definition`]s (each with populated `.calls`).
fn parse_and_extract_lang(source: &str, ext: &str) -> Vec<Definition> {
    let lang_config = ripvec_core::languages::config_for_extension(ext).expect("lang config");
    let call_config = ripvec_core::languages::call_query_for_extension(ext).expect("call config");
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&lang_config.language)
        .expect("set lang");
    let tree = parser.parse(source, None).expect("parse source");
    let mut defs = Vec::new();
    let mut cursor = tree_sitter::QueryCursor::new();
    let mut matches = cursor.matches(&lang_config.query, tree.root_node(), source.as_bytes());
    while let Some(m) = matches.next() {
        let mut name = String::new();
        let mut def_node = None;
        for cap in m.captures {
            let cap_name = &lang_config.query.capture_names()[cap.index as usize];
            if *cap_name == "name" {
                name = source[cap.node.start_byte()..cap.node.end_byte()].to_string();
            } else if *cap_name == "def" {
                def_node = Some(cap.node);
            }
        }
        if let Some(node) = def_node {
            defs.push(Definition {
                name,
                kind: node.kind().to_string(),
                start_line: node.start_position().row as u32 + 1,
                end_line: node.end_position().row as u32 + 1,
                scope: String::new(),
                signature: None,
                start_byte: node.start_byte() as u32,
                end_byte: node.end_byte() as u32,
                calls: vec![],
                decorator: None,
                lsp_kind_hint: None,
            });
        }
    }
    repo_map::extract_calls_pub(source, &call_config, &mut defs);
    defs
}

fn parse_and_extract(source: &str) -> Vec<Definition> {
    let lang_config = ripvec_core::languages::config_for_extension("rs").expect("rs lang config");
    let call_config =
        ripvec_core::languages::call_query_for_extension("rs").expect("rs call config");
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&lang_config.language)
        .expect("set rs lang");
    let tree = parser.parse(source, None).expect("parse source");
    let mut defs = Vec::new();
    let mut cursor = tree_sitter::QueryCursor::new();
    let mut matches = cursor.matches(&lang_config.query, tree.root_node(), source.as_bytes());
    while let Some(m) = matches.next() {
        let mut name = String::new();
        let mut def_node = None;
        for cap in m.captures {
            let cap_name = &lang_config.query.capture_names()[cap.index as usize];
            if *cap_name == "name" {
                name = source[cap.node.start_byte()..cap.node.end_byte()].to_string();
            } else if *cap_name == "def" {
                def_node = Some(cap.node);
            }
        }
        if let Some(node) = def_node {
            defs.push(Definition {
                name,
                kind: node.kind().to_string(),
                start_line: node.start_position().row as u32 + 1,
                end_line: node.end_position().row as u32 + 1,
                scope: String::new(),
                signature: None,
                start_byte: node.start_byte() as u32,
                end_byte: node.end_byte() as u32,
                calls: vec![],
                decorator: None,
                lsp_kind_hint: None,
            });
        }
    }
    repo_map::extract_calls_pub(source, &call_config, &mut defs);
    defs
}

fn dump(defs: &[Definition], label: &str) {
    eprintln!("--- {} ---", label);
    for d in defs {
        eprintln!(
            "  DEF name={:?} kind={} bytes={}..{} calls={:?}",
            d.name,
            d.kind,
            d.start_byte,
            d.end_byte,
            d.calls
                .iter()
                .map(|c| (&c.name, c.byte_offset))
                .collect::<Vec<_>>()
        );
    }
}

#[test]
fn probe_a_simple_closure() {
    let source = r#"
fn outer() {
    let items = vec![1u32, 2, 3];
    items.iter().for_each(|x| {
        target(*x);
    });
}

fn target(x: u32) {}
"#;
    let defs = parse_and_extract(source);
    dump(&defs, "simple closure");
    let outer = defs.iter().find(|d| d.name == "outer").unwrap();
    assert!(outer.calls.iter().any(|c| c.name == "target"), "PROBE A");
}

#[test]
fn probe_b_chained_destructured_closure_mimicking_build_graph() {
    let source = r#"
pub fn build_graph(root: &str) -> Vec<u32> {
    let files: Vec<u32> = vec![1, 2, 3];
    let sources: Vec<u32> = vec![10, 20, 30];
    files
        .iter()
        .zip(sources.iter())
        .for_each(|(file, source)| {
            if let Some(config) = Some(*file) {
                if is_go_language(config) {
                    enrich_go_method_def_scopes(*source);
                }
            }
        });
    vec![]
}

fn is_go_language(c: u32) -> bool { c > 0 }
fn enrich_go_method_def_scopes(x: u32) {}
"#;
    let defs = parse_and_extract(source);
    dump(&defs, "chained destructured closure (build_graph shape)");
    let bg = defs.iter().find(|d| d.name == "build_graph").unwrap();
    let names: Vec<&str> = bg.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("build_graph.calls names: {:?}", names);
    assert!(
        bg.calls
            .iter()
            .any(|c| c.name == "enrich_go_method_def_scopes"),
        "PROBE B FAIL: build_graph should record call to enrich_go_method_def_scopes; got {:?}",
        names
    );
}

#[test]
fn probe_c_par_iter_mut_zip_for_each_exact() {
    // Mirrors crates/ripvec-core/src/repo_map.rs:2940-2966 shape verbatim
    // (modulo type generics) — par_iter_mut + zip + for_each + nested if-lets +
    // conditional call.
    let source = r#"
pub fn build_graph() {
    let mut files: Vec<u32> = vec![1, 2, 3];
    let raw_sources: Vec<u32> = vec![10, 20, 30];
    files
        .iter_mut()
        .zip(raw_sources.iter())
        .for_each(|(file, source)| {
            if let Some(config) = Some(file) {
                if true {
                    *config = *source;
                    extract_definitions(*source);
                    if true {
                        enrich_go_method_def_scopes(*source);
                    }
                }
            }
        });
}

fn extract_definitions(s: u32) {}
fn enrich_go_method_def_scopes(s: u32) {}
"#;
    let defs = parse_and_extract(source);
    dump(
        &defs,
        "par_iter_mut + zip + for_each + nested if-let (mirror)",
    );
    let bg = defs.iter().find(|d| d.name == "build_graph").unwrap();
    let names: Vec<&str> = bg.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("build_graph.calls names: {:?}", names);
    assert!(
        bg.calls.iter().any(|c| c.name == "extract_definitions"),
        "PROBE C: should have extract_definitions; got {:?}",
        names
    );
    assert!(
        bg.calls
            .iter()
            .any(|c| c.name == "enrich_go_method_def_scopes"),
        "PROBE C: should have enrich_go_method_def_scopes; got {:?}",
        names
    );
}

#[test]
fn probe_d_cross_file_qualified_call_via_build_graph() {
    use std::fs;
    use tempfile::tempdir;

    let dir = tempdir().unwrap();
    let src_dir = dir.path().join("src");
    let tests_dir = dir.path().join("tests");
    fs::create_dir_all(&src_dir).unwrap();
    fs::create_dir_all(&tests_dir).unwrap();

    // src/lib.rs declares pub mod repo_map
    fs::write(src_dir.join("lib.rs"), "pub mod repo_map;\n").unwrap();

    // src/repo_map.rs has pub fn build_graph (the "real" target)
    fs::write(
        src_dir.join("repo_map.rs"),
        r#"
pub fn build_graph(root: &str) -> u32 {
    enrich_helper(root);
    0
}

fn enrich_helper(_: &str) {}
"#,
    )
    .unwrap();

    // tests/integration.rs calls qualified — the cross-file case
    fs::write(
        tests_dir.join("integration.rs"),
        r#"
#[test]
fn calls_build_graph() {
    let _ = my_crate::repo_map::build_graph("x");
}
"#,
    )
    .unwrap();

    fs::write(
        dir.path().join("Cargo.toml"),
        "[package]\nname = \"my_crate\"\nversion=\"0.0.1\"\nedition=\"2021\"\n[lib]\npath=\"src/lib.rs\"\n",
    )
    .unwrap();

    let graph = repo_map::build_graph(dir.path()).expect("build_graph");

    // Find the build_graph def in src/repo_map.rs
    let bg_did = graph
        .files
        .iter()
        .enumerate()
        .find_map(|(fi, f)| {
            f.defs
                .iter()
                .enumerate()
                .find(|(_, d)| d.name == "build_graph")
                .map(|(di, _)| (fi as u32, di as u32))
        })
        .expect("build_graph def must exist");

    // Find calls_build_graph def in tests/integration.rs
    let test_did = graph
        .files
        .iter()
        .enumerate()
        .find_map(|(fi, f)| {
            f.defs
                .iter()
                .enumerate()
                .find(|(_, d)| d.name == "calls_build_graph")
                .map(|(di, _)| (fi as u32, di as u32))
        })
        .expect("calls_build_graph def must exist");

    eprintln!("build_graph def_id: file={} def={}", bg_did.0, bg_did.1);
    eprintln!(
        "calls_build_graph def_id: file={} def={}",
        test_did.0, test_did.1
    );

    // Check the def_callees edge
    let test_flat = graph.def_offsets[test_did.0 as usize] + test_did.1 as usize;
    let bg_flat = graph.def_offsets[bg_did.0 as usize] + bg_did.1 as usize;

    let callees = &graph.def_callees[test_flat];
    eprintln!("calls_build_graph.def_callees: {:?}", callees);
    eprintln!(
        "Looking for bg_flat={} (file={}, def={})",
        bg_flat, bg_did.0, bg_did.1
    );

    let has_edge = callees.iter().any(|did| {
        let cf = graph.def_offsets[did.0 as usize] + did.1 as usize;
        cf == bg_flat
    });

    assert!(
        has_edge,
        "PROBE D: cross-file qualified call calls_build_graph → build_graph not in def_callees. \
         The def edge that lsp_incoming_calls would walk is missing from the BFS graph. \
         This is the actual I#57 cause: cross-file qualified-path call resolution gap."
    );
}

/// I#57 diagnostic — runs `build_graph` on the real ripvec workspace root
/// (this is the actual self-corpus that exhibits the bug) and dumps:
///
/// 1. `build_graph` def_id + its `def_callees` list (count + names)
/// 2. Whether `enrich_go_method_def_scopes` is among those callees
/// 3. `enrich_go_method_def_scopes` def_id + its `def_callers`
/// 4. Which Test entry-points the RustEntryDetector finds in
///    `crates/ripvec-core/tests/repo_map_extractor.rs`
/// 5. For one of those tests, whether its def_callees contains a path
///    that eventually reaches `enrich_go_method_def_scopes`.
///
/// The output enumerates which of the 3 remaining I#57 candidates
/// (entry-seeding gap, cross-crate qualified path, file-index path
/// normalization) is actually causing the false positive.
#[test]
#[ignore = "diagnostic — runs on real ripvec workspace; useful for I#57 root-cause"]
fn i57_diagnostic_real_corpus() {
    use ripvec_core::entry_points::{EntryPointDetector, EntryPointKind, RustEntryDetector};
    use std::path::Path;

    // Workspace root: CARGO_MANIFEST_DIR = crates/ripvec-core; up two = ws root.
    let ws_root = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .parent()
        .unwrap();
    eprintln!("[diag] workspace root: {}", ws_root.display());

    let graph = repo_map::build_graph(ws_root).expect("build_graph workspace");
    eprintln!("[diag] graph.files.len() = {}", graph.files.len());

    // Locate build_graph + enrich_go_method_def_scopes in the graph.
    let mut bg: Option<(usize, usize)> = None;
    let mut enrich: Option<(usize, usize)> = None;
    for (fi, f) in graph.files.iter().enumerate() {
        if f.path.ends_with("crates/ripvec-core/src/repo_map.rs")
            || f.path.ends_with("ripvec-core/src/repo_map.rs")
        {
            for (di, d) in f.defs.iter().enumerate() {
                if d.name == "build_graph" && bg.is_none() {
                    bg = Some((fi, di));
                }
                if d.name == "enrich_go_method_def_scopes" && enrich.is_none() {
                    enrich = Some((fi, di));
                }
            }
        }
    }
    let (bg_fi, bg_di) = bg.expect("build_graph must be present in repo_map.rs");
    let (en_fi, en_di) = enrich.expect("enrich_go_method_def_scopes must be present");
    eprintln!(
        "[diag] build_graph file_idx={} def_idx={} path={}",
        bg_fi, bg_di, graph.files[bg_fi].path
    );
    eprintln!(
        "[diag] enrich_go_method_def_scopes file_idx={} def_idx={} path={}",
        en_fi, en_di, graph.files[en_fi].path
    );

    let bg_flat = graph.def_offsets[bg_fi] + bg_di;
    let en_flat = graph.def_offsets[en_fi] + en_di;

    let bg_callees = &graph.def_callees[bg_flat];
    eprintln!(
        "[diag] build_graph.def_callees.len() = {}",
        bg_callees.len()
    );
    let names_called: Vec<&str> = bg_callees
        .iter()
        .filter_map(|did| {
            let f = graph.files.get(did.0 as usize)?;
            let d = f.defs.get(did.1 as usize)?;
            Some(d.name.as_str())
        })
        .collect();
    eprintln!("[diag] build_graph called names = {:?}", names_called);
    let bg_calls_enrich = bg_callees.iter().any(|did| {
        let cflat = graph.def_offsets[did.0 as usize] + did.1 as usize;
        cflat == en_flat
    });
    eprintln!(
        "[diag] build_graph -> enrich_go_method_def_scopes edge: {}",
        bg_calls_enrich
    );

    let en_callers = &graph.def_callers[en_flat];
    eprintln!(
        "[diag] enrich_go_method_def_scopes.def_callers.len() = {}",
        en_callers.len()
    );
    for did in en_callers {
        let f = &graph.files[did.0 as usize];
        let d = &f.defs[did.1 as usize];
        eprintln!(
            "[diag]   caller: {}::{} (file_idx={} def_idx={})",
            f.path, d.name, did.0, did.1
        );
    }

    // Run RustEntryDetector on repo_map_extractor.rs as the integration test
    // path; see if Test entry points are detected at all.
    let det = RustEntryDetector;
    let test_rel = "crates/ripvec-core/tests/repo_map_extractor.rs";
    let abs = ws_root.join(test_rel);
    let src = std::fs::read_to_string(&abs).expect("read repo_map_extractor.rs");
    let eps = det.detect(&src, &abs);
    let test_eps: Vec<_> = eps
        .iter()
        .filter(|e| matches!(e.kind, EntryPointKind::Test))
        .collect();
    eprintln!(
        "[diag] repo_map_extractor.rs: total entries={} Test entries={}",
        eps.len(),
        test_eps.len()
    );
    for ep in test_eps.iter().take(5) {
        eprintln!("[diag]   Test entry: {} @ line {}", ep.name, ep.line);
    }

    // Locate the file in the graph by path (this checks for path-normalization
    // mismatch between RustEntryDetector input and graph.files[i].path).
    let test_fi = graph
        .files
        .iter()
        .position(|f| f.path.ends_with("tests/repo_map_extractor.rs"));
    eprintln!(
        "[diag] graph file index for repo_map_extractor.rs: {:?}",
        test_fi
    );
    if let Some(test_fi) = test_fi {
        let path_in_graph = &graph.files[test_fi].path;
        eprintln!("[diag] graph path: {:?}", path_in_graph);
        // Now check: for each Test entry, can we find the corresponding def?
        let file = &graph.files[test_fi];
        let mut matched = 0;
        for ep in &test_eps {
            for d in &file.defs {
                if d.start_line == ep.line || d.name == ep.name {
                    matched += 1;
                    break;
                }
            }
        }
        eprintln!(
            "[diag] matched {} of {} Test entries to defs",
            matched,
            test_eps.len()
        );

        // For a test that we know calls repo_map::build_graph
        // (test_build_graph_links_impl_method_to_trait_method around line 683)
        // locate it and dump its callees.
        for d in &file.defs {
            if d.name == "test_build_graph_links_impl_method_to_trait_method" {
                let flat = graph.def_offsets[test_fi]
                    + file.defs.iter().position(|x| std::ptr::eq(x, d)).unwrap();
                let callees = &graph.def_callees[flat];
                eprintln!(
                    "[diag] test_build_graph_links_impl_method_to_trait_method def_callees.len={}",
                    callees.len()
                );
                let names: Vec<&str> = callees
                    .iter()
                    .filter_map(|did| {
                        let f = graph.files.get(did.0 as usize)?;
                        let de = f.defs.get(did.1 as usize)?;
                        Some(de.name.as_str())
                    })
                    .collect();
                eprintln!(
                    "[diag] test_build_graph_links_impl_method_to_trait_method callee names: {:?}",
                    names
                );
                let calls_bg = callees.iter().any(|did| {
                    let f = graph.def_offsets[did.0 as usize] + did.1 as usize;
                    f == bg_flat
                });
                eprintln!(
                    "[diag] test_build_graph...links->build_graph edge present: {}",
                    calls_bg
                );
                break;
            }
        }
    }

    // Also print MCP cross-crate consumer side: tools.rs's call site to build_graph.
    let tools_fi = graph
        .files
        .iter()
        .position(|f| f.path.ends_with("ripvec-mcp/src/tools.rs"));
    eprintln!("[diag] graph file index for tools.rs: {:?}", tools_fi);
    if let Some(tools_fi) = tools_fi {
        let tf = &graph.files[tools_fi];
        // Any def whose callees include bg_flat?
        let mut any_caller_in_tools = false;
        for (di, _d) in tf.defs.iter().enumerate() {
            let flat = graph.def_offsets[tools_fi] + di;
            let callees = &graph.def_callees[flat];
            if callees.iter().any(|did| {
                let f = graph.def_offsets[did.0 as usize] + did.1 as usize;
                f == bg_flat
            }) {
                any_caller_in_tools = true;
                eprintln!(
                    "[diag]   tools.rs caller of build_graph: {}",
                    tf.defs[di].name
                );
            }
        }
        eprintln!(
            "[diag] any tools.rs def has edge to build_graph: {}",
            any_caller_in_tools
        );
    }
}

/// I#55 end-to-end: build_graph on a synthetic C crate with a
/// redis-style command-table and assert that the resolved def_edges
/// connect the table to each command implementation.
///
/// This is the integration-level cousin of the unit-level tests in
/// `c_struct_literal_dispatch.rs`: those drive `extract_calls_pub`
/// directly to verify the per-file CallRef list; this one walks the full
/// `build_graph` pipeline (extract → resolve → flatten → CSR) and
/// confirms the graph-level adjacency includes the synthetic edges.
///
/// Without I#55, `def_callees[cmds]` is empty on this corpus and every
/// command implementation appears in the dead set; with the fix, the
/// callees list contains the def_ids of `getCommand`, `setCommand`,
/// `delCommand`.
#[test]
fn i55_c_struct_literal_edges_propagate_to_def_edges() {
    use std::fs;
    use tempfile::tempdir;

    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("commands.c"),
        r#"
typedef int redisCommandProc(int *c);

struct redisCommand {
    const char *name;
    redisCommandProc *proc;
    int arity;
};

int getCommand(int *c) { return 0; }
int setCommand(int *c) { return 0; }
int delCommand(int *c) { return 0; }

struct redisCommand redisCommandTable[] = {
    {"get", getCommand, 2},
    {"set", setCommand, -3},
    {"del", delCommand, -2},
};
"#,
    )
    .unwrap();

    let graph = repo_map::build_graph(dir.path()).expect("build_graph");

    // Locate the synthetic def for redisCommandTable + each command impl.
    let mut tbl: Option<(u32, u32)> = None;
    let mut targets: std::collections::HashMap<&str, (u32, u32)> = std::collections::HashMap::new();
    for (fi, f) in graph.files.iter().enumerate() {
        for (di, d) in f.defs.iter().enumerate() {
            let did = (fi as u32, di as u32);
            if d.name == "redisCommandTable" {
                tbl = Some(did);
            }
            for name in ["getCommand", "setCommand", "delCommand"] {
                if d.name == name && d.kind == "function_definition" {
                    targets.insert(name, did);
                }
            }
        }
    }
    let (tbl_fi, tbl_di) = tbl.expect("redisCommandTable def must be present (I#55)");
    let tbl_flat = graph.def_offsets[tbl_fi as usize] + tbl_di as usize;

    for name in ["getCommand", "setCommand", "delCommand"] {
        let (t_fi, t_di) = *targets
            .get(name)
            .unwrap_or_else(|| panic!("{name} function_definition def must be present"));
        let target_flat = graph.def_offsets[t_fi as usize] + t_di as usize;

        let callees = &graph.def_callees[tbl_flat];
        let has_edge = callees
            .iter()
            .any(|did| graph.def_offsets[did.0 as usize] + did.1 as usize == target_flat);
        assert!(
            has_edge,
            "I#55: redisCommandTable.def_callees must include {name} (table → command \
             implementation edge). Without this edge the BFS in find_dead_code treats {name} \
             as unreachable, producing the redis command-collapse pathology."
        );
    }
}

// ─── B-0005: JS closure call-edge attribution tests ──────────────────────────
//
// Each test uses `parse_and_extract_lang` with ext="js". The TDD rule:
// every test below must fail (RED) before the JS-closure post-pass is
// implemented, and pass (GREEN) after.

/// B-0005 test 1 — `useCallback(() => { dispatch(); }, [])` inside a
/// React component: the inner `dispatch` call must be attributed to
/// `Component`, not to the anonymous arrow function (which has no def
/// of its own in the def list).
#[test]
fn js_use_callback_closure_call_attributed_to_enclosing() {
    let source = r#"
function Component() {
  const handler = useCallback(() => {
    dispatch({type: 'X'});
  }, []);
  return handler;
}
"#;
    let defs = parse_and_extract_lang(source, "js");
    dump(
        &defs,
        "js_use_callback_closure_call_attributed_to_enclosing",
    );
    let comp = defs
        .iter()
        .find(|d| d.name == "Component")
        .expect("Component def");
    let names: Vec<&str> = comp.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("Component.calls: {:?}", names);
    assert!(
        comp.calls.iter().any(|c| c.name == "useCallback"),
        "Component must record call to useCallback; got {:?}",
        names
    );
    assert!(
        comp.calls.iter().any(|c| c.name == "dispatch"),
        "Component must record call to dispatch (closure attribution); got {:?}",
        names
    );
}

/// B-0005 test 2 — `setTimeout(() => { startup(); }, 0)` inside an init
/// function: `startup` must be attributed to `init`.
#[test]
fn js_set_timeout_closure_call_attributed() {
    let source = r#"
function init() {
  setTimeout(() => {
    startup();
  }, 0);
}
"#;
    let defs = parse_and_extract_lang(source, "js");
    dump(&defs, "js_set_timeout_closure_call_attributed");
    let init = defs.iter().find(|d| d.name == "init").expect("init def");
    let names: Vec<&str> = init.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("init.calls: {:?}", names);
    assert!(
        init.calls.iter().any(|c| c.name == "setTimeout"),
        "init must record call to setTimeout; got {:?}",
        names
    );
    assert!(
        init.calls.iter().any(|c| c.name == "startup"),
        "init must record call to startup (closure attribution); got {:?}",
        names
    );
}

/// B-0005 test 3 — `xs.map(x => transform(x))` inside `process`:
/// `transform` must be attributed to `process`.
#[test]
fn js_array_map_closure_call_attributed() {
    let source = r#"
function process(xs) {
  return xs.map(x => transform(x));
}
"#;
    let defs = parse_and_extract_lang(source, "js");
    dump(&defs, "js_array_map_closure_call_attributed");
    let proc = defs
        .iter()
        .find(|d| d.name == "process")
        .expect("process def");
    let names: Vec<&str> = proc.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("process.calls: {:?}", names);
    assert!(
        proc.calls.iter().any(|c| c.name == "map"),
        "process must record call to map; got {:?}",
        names
    );
    assert!(
        proc.calls.iter().any(|c| c.name == "transform"),
        "process must record call to transform (closure attribution); got {:?}",
        names
    );
}

/// B-0005 test 4 — Express-style `app.use((req, res, next) => { authenticate(req); next(); })`:
/// `authenticate` and `next` must be attributed to `setupApp`.
#[test]
fn js_express_app_use_closure_attributed() {
    let source = r#"
function setupApp() {
  app.use((req, res, next) => {
    authenticate(req);
    next();
  });
}
"#;
    let defs = parse_and_extract_lang(source, "js");
    dump(&defs, "js_express_app_use_closure_attributed");
    let setup = defs
        .iter()
        .find(|d| d.name == "setupApp")
        .expect("setupApp def");
    let names: Vec<&str> = setup.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("setupApp.calls: {:?}", names);
    assert!(
        setup.calls.iter().any(|c| c.name == "authenticate"),
        "setupApp must record call to authenticate (closure attribution); got {:?}",
        names
    );
    assert!(
        setup.calls.iter().any(|c| c.name == "next"),
        "setupApp must record call to next (closure attribution); got {:?}",
        names
    );
}

/// B-0005 test 5 (regression guard) — a top-level named arrow function
/// `const handler = () => doThing()` must remain its own def and attribute
/// `doThing` to `handler`, not to file scope.
#[test]
fn js_top_level_const_arrow_fn_kept_separate() {
    let source = r#"
const handler = () => doThing();
"#;
    let defs = parse_and_extract_lang(source, "js");
    dump(&defs, "js_top_level_const_arrow_fn_kept_separate");
    let h = defs
        .iter()
        .find(|d| d.name == "handler")
        .expect("handler def");
    let names: Vec<&str> = h.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("handler.calls: {:?}", names);
    assert!(
        h.calls.iter().any(|c| c.name == "doThing"),
        "handler must record call to doThing (named const arrow fn owns its calls); got {:?}",
        names
    );
}

/// B-0005 test 6 — deeply-nested closures: both level-2 and level-3 closures
/// attribute their calls to the outermost named function `outer`.
#[test]
fn js_nested_closure_attributes_to_named_ancestor() {
    let source = r#"
function outer() {
  items.forEach(item => {
    items.filter(x => predicate(x));
  });
}
"#;
    let defs = parse_and_extract_lang(source, "js");
    dump(&defs, "js_nested_closure_attributes_to_named_ancestor");
    let outer = defs.iter().find(|d| d.name == "outer").expect("outer def");
    let names: Vec<&str> = outer.calls.iter().map(|c| c.name.as_str()).collect();
    eprintln!("outer.calls: {:?}", names);
    assert!(
        outer.calls.iter().any(|c| c.name == "predicate"),
        "outer must record call to predicate (deep closure attribution); got {:?}",
        names
    );
}

// ─── End B-0005 tests ────────────────────────────────────────────────────────

/// I#55 end-to-end (Linux fops shape): same pipeline test but for the
/// designated-initializer dispatch idiom universal in Linux drivers.
#[test]
fn i55_c_designated_init_edges_propagate_to_def_edges() {
    use std::fs;
    use tempfile::tempdir;

    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("driver.c"),
        r#"
struct file_operations {
    int (*open)(int);
    int (*release)(int);
    long (*read)(int);
};

static int my_open(int x) { return 0; }
static int my_release(int x) { return 0; }
static long my_read(int x) { return 0; }

static const struct file_operations my_fops = {
    .open    = my_open,
    .release = my_release,
    .read    = my_read,
};
"#,
    )
    .unwrap();

    let graph = repo_map::build_graph(dir.path()).expect("build_graph");

    let mut fops: Option<(u32, u32)> = None;
    let mut targets: std::collections::HashMap<&str, (u32, u32)> = std::collections::HashMap::new();
    for (fi, f) in graph.files.iter().enumerate() {
        for (di, d) in f.defs.iter().enumerate() {
            let did = (fi as u32, di as u32);
            if d.name == "my_fops" {
                fops = Some(did);
            }
            for name in ["my_open", "my_release", "my_read"] {
                if d.name == name && d.kind == "function_definition" {
                    targets.insert(name, did);
                }
            }
        }
    }
    let (fops_fi, fops_di) = fops.expect("my_fops def must be present");
    let fops_flat = graph.def_offsets[fops_fi as usize] + fops_di as usize;

    for name in ["my_open", "my_release", "my_read"] {
        let (t_fi, t_di) = *targets.get(name).expect(name);
        let target_flat = graph.def_offsets[t_fi as usize] + t_di as usize;
        let callees = &graph.def_callees[fops_flat];
        let has_edge = callees
            .iter()
            .any(|did| graph.def_offsets[did.0 as usize] + did.1 as usize == target_flat);
        assert!(
            has_edge,
            "I#55: my_fops.def_callees must include {name} (designated-init edge)"
        );
    }
}

// ─── Cycle 10 W1 Front A: end-to-end BFS via build_graph ──────────────
//
// After dropping spurious nested assignment / variable_declarator defs,
// BFS from `main` reaches the same-file and cross-file helper functions
// that the previous baseline missed (because every `x = lib.helper()`
// call inside `main` was siphoned into a nested local-binding def).

/// Walk the flat def_callees adjacency to determine the set of defs
/// reachable from `seed_flat` via BFS.
fn bfs_reachable(
    graph: &repo_map::RepoGraph,
    seed_flat: usize,
) -> std::collections::HashSet<usize> {
    let mut visited = std::collections::HashSet::new();
    let mut stack = vec![seed_flat];
    visited.insert(seed_flat);
    while let Some(cur) = stack.pop() {
        for &(fi, di) in &graph.def_callees[cur] {
            let f = graph.def_offsets[fi as usize] + di as usize;
            if visited.insert(f) {
                stack.push(f);
            }
        }
    }
    visited
}

fn find_def_flat(graph: &repo_map::RepoGraph, name: &str) -> Option<usize> {
    for (fi, f) in graph.files.iter().enumerate() {
        for (di, d) in f.defs.iter().enumerate() {
            if d.name == name {
                return Some(graph.def_offsets[fi] + di);
            }
        }
    }
    None
}

#[test]
fn bfs_python_main_reaches_called_functions_via_build_graph() {
    use std::fs;
    use tempfile::tempdir;

    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("lib.py"),
        r#"
def helper():
    return 1

def process(x):
    y = helper()
    return x + y
"#,
    )
    .unwrap();
    fs::write(
        dir.path().join("cli.py"),
        r#"
from lib import process

def main():
    args = parse_args()
    result = process(args)
    write(result)

def parse_args():
    return 42

def write(r):
    return r
"#,
    )
    .unwrap();

    let graph = repo_map::build_graph(dir.path()).expect("build_graph");

    let main_flat = find_def_flat(&graph, "main").expect("main def must exist");
    let process_flat = find_def_flat(&graph, "process").expect("process def must exist");
    let helper_flat = find_def_flat(&graph, "helper").expect("helper def must exist");
    let parse_args_flat = find_def_flat(&graph, "parse_args").expect("parse_args def must exist");
    let write_flat = find_def_flat(&graph, "write").expect("write def must exist");

    let reachable = bfs_reachable(&graph, main_flat);

    assert!(
        reachable.contains(&parse_args_flat),
        "C10 W1: BFS from `main` must reach `parse_args` (same-file `args = parse_args()`); \
         reachable size = {}",
        reachable.len()
    );
    assert!(
        reachable.contains(&process_flat),
        "C10 W1: BFS from `main` must reach `process` (cross-file `result = process(args)`); \
         reachable size = {}",
        reachable.len()
    );
    assert!(
        reachable.contains(&write_flat),
        "C10 W1: BFS from `main` must reach `write` (bare statement `write(result)`)"
    );
    assert!(
        reachable.contains(&helper_flat),
        "C10 W1: BFS from `main` must transitively reach `helper` via `process`; \
         this is the 2-hop reachability that the pre-fix baseline could not achieve \
         because `process`'s body-internal `y = helper()` was siphoned into a \
         nested assignment def named `y`"
    );
}

#[test]
fn bfs_js_main_reaches_called_functions_via_build_graph() {
    use std::fs;
    use tempfile::tempdir;

    let dir = tempdir().unwrap();
    fs::write(
        dir.path().join("lib.js"),
        r#"
function helper() { return 1; }

function process(x) {
  const y = helper();
  return x + y;
}

module.exports = { process: process };
"#,
    )
    .unwrap();
    fs::write(
        dir.path().join("cli.js"),
        r#"
const lib = require('./lib');

function parseArgs() { return 42; }
function write(r) { return r; }

function main() {
  const args = parseArgs();
  const result = lib.process(args);
  write(result);
}
"#,
    )
    .unwrap();

    let graph = repo_map::build_graph(dir.path()).expect("build_graph");

    let main_flat = find_def_flat(&graph, "main").expect("main def must exist");
    let parse_args_flat = find_def_flat(&graph, "parseArgs").expect("parseArgs def must exist");
    let write_flat = find_def_flat(&graph, "write").expect("write def must exist");

    let reachable = bfs_reachable(&graph, main_flat);

    assert!(
        reachable.contains(&parse_args_flat),
        "C10 W1: BFS from `main` must reach `parseArgs` (same-file `const args = parseArgs()`); \
         reachable size = {}",
        reachable.len()
    );
    assert!(
        reachable.contains(&write_flat),
        "C10 W1: BFS from `main` must reach `write` (bare statement `write(result)`)"
    );
}