gitcortex-mcp 0.5.0

MCP server library for GitCortex — exposes the knowledge graph via the Model Context Protocol
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
/// End-to-end pipeline tests: git repo → indexer → store → query.
/// Each test creates a real temp git repo, commits a fixture file,
/// runs the incremental indexer, applies the diff to a KuzuDB store,
/// and asserts that nodes and known symbols are present.
///
/// Tests are serialized via KUZU_LOCK because KuzuDB cannot safely open
/// multiple database instances concurrently within the same process.
use std::path::Path;
use std::process::Command;
use std::sync::Mutex;

static KUZU_LOCK: Mutex<()> = Mutex::new(());

/// Commit multiple fixture files in a single git commit.
fn commit_files(dir: &Path, fixtures: &[&str]) {
    for name in fixtures {
        let src = Path::new(FIXTURES).join(name);
        std::fs::copy(&src, dir.join(name)).expect("copy fixture");
    }
    let names: Vec<&str> = fixtures.to_vec();
    let mut add_args = vec!["add"];
    add_args.extend_from_slice(&names);
    let status = Command::new("git")
        .args(&add_args)
        .current_dir(dir)
        .status()
        .expect("git add failed");
    assert!(status.success(), "git add failed");
    let status = Command::new("git")
        .args(["commit", "-m", "add fixtures"])
        .current_dir(dir)
        .status()
        .expect("git commit failed");
    assert!(status.success(), "git commit failed");
}

/// Run the full pipeline against multiple fixture files committed together.
fn run_pipeline_multi(
    fixtures: &[&str],
) -> (
    Vec<gitcortex_core::graph::Node>,
    Vec<gitcortex_core::graph::Edge>,
    KuzuGraphStore,
) {
    let _lock = KUZU_LOCK.lock().expect("lock");
    let tmp = tempfile::tempdir().expect("tempdir");
    init_repo(tmp.path());
    commit_files(tmp.path(), fixtures);

    let indexer = IncrementalIndexer::new(tmp.path()).expect("indexer");
    let (diff, head_sha) = indexer.run(None).expect("indexer.run");

    let mut store = KuzuGraphStore::open(tmp.path()).expect("store");
    store.apply_diff("main", &diff).expect("apply_diff");
    store
        .set_last_indexed_sha("main", &head_sha)
        .expect("set sha");

    let nodes = store.list_all_nodes("main").expect("list_all_nodes");
    let edges = store.list_all_edges("main").expect("list_all_edges");
    (nodes, edges, store)
}

use gitcortex_core::store::GraphStore;
use gitcortex_indexer::IncrementalIndexer;
use gitcortex_store::kuzu::KuzuGraphStore;

const FIXTURES: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../../tests/integration/fixtures"
);

fn init_repo(dir: &Path) {
    for args in [
        vec!["init"],
        vec!["config", "user.email", "test@test.com"],
        vec!["config", "user.name", "Test"],
    ] {
        let status = Command::new("git")
            .args(&args)
            .current_dir(dir)
            .status()
            .expect("git failed");
        assert!(status.success(), "git {args:?} failed");
    }
}

fn commit_file(dir: &Path, src: &Path, dest_name: &str) {
    let dest = dir.join(dest_name);
    std::fs::copy(src, &dest).expect("copy fixture");
    for args in [vec!["add", dest_name], vec!["commit", "-m", "add fixture"]] {
        let status = Command::new("git")
            .args(&args)
            .current_dir(dir)
            .status()
            .expect("git failed");
        assert!(status.success(), "git {args:?} failed");
    }
}

fn run_pipeline(
    fixture: &str,
) -> (
    Vec<gitcortex_core::graph::Node>,
    Vec<gitcortex_core::graph::Edge>,
) {
    let _lock = KUZU_LOCK.lock().expect("lock");
    let tmp = tempfile::tempdir().expect("tempdir");
    init_repo(tmp.path());
    commit_file(
        tmp.path(),
        Path::new(FIXTURES).join(fixture).as_path(),
        fixture,
    );

    let indexer = IncrementalIndexer::new(tmp.path()).expect("indexer");
    let (diff, head_sha) = indexer.run(None).expect("indexer.run");

    let mut store = KuzuGraphStore::open(tmp.path()).expect("store");
    store.apply_diff("main", &diff).expect("apply_diff");
    store
        .set_last_indexed_sha("main", &head_sha)
        .expect("set sha");

    let nodes = store.list_all_nodes("main").expect("list_all_nodes");
    let edges = store.list_all_edges("main").expect("list_all_edges");
    (nodes, edges)
}

#[test]
fn rust_fixture_indexes_nodes_and_edges() {
    let (nodes, edges) = run_pipeline("sample.rs");
    assert!(!nodes.is_empty(), "expected nodes for sample.rs");
    assert!(!edges.is_empty(), "expected edges for sample.rs");
    let names: Vec<_> = nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(names.contains(&"Hello"), "expected struct Hello");
    assert!(names.contains(&"Greeter"), "expected trait Greeter");
    assert!(
        names.contains(&"make_greeting"),
        "expected fn make_greeting"
    );
}

#[test]
fn python_fixture_indexes_nodes_and_edges() {
    let (nodes, edges) = run_pipeline("sample.py");
    assert!(!nodes.is_empty(), "expected nodes for sample.py");
    assert!(!edges.is_empty(), "expected edges for sample.py");
    let names: Vec<_> = nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(names.contains(&"Greeter"), "expected class Greeter");
    assert!(
        names.contains(&"make_greeting"),
        "expected fn make_greeting"
    );
}

#[test]
fn typescript_fixture_indexes_nodes_and_edges() {
    let (nodes, edges) = run_pipeline("sample.ts");
    assert!(!nodes.is_empty(), "expected nodes for sample.ts");
    assert!(!edges.is_empty(), "expected edges for sample.ts");
    let names: Vec<_> = nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(names.contains(&"Greeter"), "expected interface Greeter");
    assert!(names.contains(&"Hello"), "expected class Hello");
    assert!(names.contains(&"makeGreeting"), "expected fn makeGreeting");
}

#[test]
fn go_fixture_indexes_nodes_and_edges() {
    let (nodes, edges) = run_pipeline("sample.go");
    assert!(!nodes.is_empty(), "expected nodes for sample.go");
    assert!(!edges.is_empty(), "expected edges for sample.go");
    let names: Vec<_> = nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(names.contains(&"Greeter"), "expected interface Greeter");
    assert!(names.contains(&"Hello"), "expected struct Hello");
    assert!(names.contains(&"MakeGreeting"), "expected fn MakeGreeting");
}

#[test]
fn java_fixture_indexes_nodes_and_edges() {
    let (nodes, edges) = run_pipeline("sample.java");
    assert!(!nodes.is_empty(), "expected nodes for sample.java");
    assert!(!edges.is_empty(), "expected edges for sample.java");
    let names: Vec<_> = nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(names.contains(&"Greeter"), "expected interface Greeter");
    assert!(names.contains(&"Hello"), "expected class Hello");
    assert!(names.contains(&"makeGreeting"), "expected fn makeGreeting");
}

// ── Python comprehensive regression tests ────────────────────────────────────

use gitcortex_core::schema::{EdgeKind, NodeKind};

fn run_python_comprehensive() -> (
    Vec<gitcortex_core::graph::Node>,
    Vec<gitcortex_core::graph::Edge>,
) {
    run_pipeline("python_comprehensive.py")
}

#[test]
fn python_comprehensive_constants_are_indexed() {
    let (nodes, _) = run_python_comprehensive();
    let constants: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Constant)
        .collect();
    let names: Vec<&str> = constants.iter().map(|n| n.name.as_str()).collect();
    assert!(
        names.contains(&"MAX_RETRIES"),
        "expected Constant MAX_RETRIES, got: {names:?}"
    );
    assert!(
        names.contains(&"DEFAULT_TIMEOUT"),
        "expected Constant DEFAULT_TIMEOUT, got: {names:?}"
    );
    assert!(
        names.contains(&"API_VERSION"),
        "expected Constant API_VERSION, got: {names:?}"
    );
}

#[test]
fn python_comprehensive_protocols_become_interfaces() {
    let (nodes, _) = run_python_comprehensive();
    let interfaces: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Interface)
        .collect();
    let names: Vec<&str> = interfaces.iter().map(|n| n.name.as_str()).collect();
    assert!(
        names.contains(&"Serializable"),
        "expected Interface Serializable, got: {names:?}"
    );
    assert!(
        names.contains(&"Repository"),
        "expected Interface Repository, got: {names:?}"
    );
    for iface in &interfaces {
        assert!(
            iface.metadata.is_abstract,
            "Protocol node '{}' should have is_abstract=true",
            iface.name
        );
    }
}

#[test]
fn python_comprehensive_plain_classes_are_structs() {
    let (nodes, _) = run_python_comprehensive();
    let structs: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Struct)
        .collect();
    let names: Vec<&str> = structs.iter().map(|n| n.name.as_str()).collect();
    for expected in &["BaseModel", "User", "AsyncService", "EventSystem"] {
        assert!(
            names.contains(expected),
            "expected Struct {expected}, got: {names:?}"
        );
    }
}

#[test]
fn python_comprehensive_property_decorator() {
    let (nodes, _) = run_python_comprehensive();
    let props: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Property)
        .collect();
    assert!(
        props.iter().any(|n| n.name == "display_name"),
        "expected Property 'display_name', got: {:?}",
        props.iter().map(|n| &n.name).collect::<Vec<_>>()
    );
    let display_name = props.iter().find(|n| n.name == "display_name").unwrap();
    assert!(
        display_name.metadata.is_property,
        "display_name should have is_property=true"
    );
}

#[test]
fn python_comprehensive_staticmethod_and_classmethod() {
    let (nodes, _) = run_python_comprehensive();
    let methods: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Method)
        .collect();
    let from_dict = methods.iter().find(|n| n.name == "from_dict");
    let anonymous = methods.iter().find(|n| n.name == "anonymous");
    assert!(from_dict.is_some(), "expected method 'from_dict'");
    assert!(anonymous.is_some(), "expected method 'anonymous'");
    assert!(
        from_dict.unwrap().metadata.is_static,
        "from_dict (@staticmethod) should have is_static=true"
    );
    assert!(
        anonymous.unwrap().metadata.is_static,
        "anonymous (@classmethod) should have is_static=true"
    );
}

#[test]
fn python_comprehensive_async_methods_flagged() {
    let (nodes, _) = run_python_comprehensive();
    let methods: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Method)
        .collect();
    let fetch = methods.iter().find(|n| n.name == "fetch_user");
    let save = methods.iter().find(|n| n.name == "save_user");
    assert!(fetch.is_some(), "expected method 'fetch_user'");
    assert!(save.is_some(), "expected method 'save_user'");
    assert!(
        fetch.unwrap().metadata.is_async,
        "fetch_user should have is_async=true"
    );
    assert!(
        save.unwrap().metadata.is_async,
        "save_user should have is_async=true"
    );
}

#[test]
fn python_comprehensive_generator_function_flagged() {
    let (nodes, _) = run_python_comprehensive();
    let fns: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Function)
        .collect();
    let user_stream = fns.iter().find(|n| n.name == "user_stream");
    assert!(user_stream.is_some(), "expected function 'user_stream'");
    assert!(
        user_stream.unwrap().metadata.is_generator,
        "user_stream should have is_generator=true"
    );
}

#[test]
fn python_comprehensive_async_generator_flagged() {
    let (nodes, _) = run_python_comprehensive();
    let fns: Vec<_> = nodes
        .iter()
        .filter(|n| n.kind == NodeKind::Function)
        .collect();
    let async_stream = fns.iter().find(|n| n.name == "async_user_stream");
    assert!(
        async_stream.is_some(),
        "expected function 'async_user_stream'"
    );
    let f = async_stream.unwrap();
    assert!(
        f.metadata.is_async,
        "async_user_stream should have is_async=true"
    );
    assert!(
        f.metadata.is_generator,
        "async_user_stream should have is_generator=true"
    );
}

#[test]
fn python_comprehensive_nested_classes_indexed() {
    let (nodes, edges) = run_python_comprehensive();
    let names: Vec<&str> = nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(names.contains(&"Event"), "expected nested class 'Event'");
    assert!(
        names.contains(&"Handler"),
        "expected nested class 'Handler'"
    );
    // EventSystem must contain Event and Handler via Contains edges
    let event_sys = nodes.iter().find(|n| n.name == "EventSystem").unwrap();
    let event_cls = nodes.iter().find(|n| n.name == "Event").unwrap();
    let handler_cls = nodes.iter().find(|n| n.name == "Handler").unwrap();
    let contains: Vec<_> = edges
        .iter()
        .filter(|e| e.kind == EdgeKind::Contains)
        .collect();
    assert!(
        contains
            .iter()
            .any(|e| e.src == event_sys.id && e.dst == event_cls.id),
        "expected Contains edge EventSystem → Event"
    );
    assert!(
        contains
            .iter()
            .any(|e| e.src == event_sys.id && e.dst == handler_cls.id),
        "expected Contains edge EventSystem → Handler"
    );
}

#[test]
fn python_comprehensive_call_edges_recorded() {
    let (nodes, edges) = run_python_comprehensive();
    let process = nodes.iter().find(|n| n.name == "process_pipeline").unwrap();
    let user_stream = nodes.iter().find(|n| n.name == "user_stream").unwrap();
    let create_user = nodes.iter().find(|n| n.name == "create_user").unwrap();
    let calls: Vec<_> = edges.iter().filter(|e| e.kind == EdgeKind::Calls).collect();
    assert!(
        calls
            .iter()
            .any(|e| e.src == process.id && e.dst == user_stream.id),
        "expected Calls edge process_pipeline → user_stream"
    );
    assert!(
        calls
            .iter()
            .any(|e| e.src == process.id && e.dst == create_user.id),
        "expected Calls edge process_pipeline → create_user"
    );
}

#[test]
fn python_comprehensive_inheritance_edges_present() {
    let (_, edges) = run_python_comprehensive();
    let implements: Vec<_> = edges
        .iter()
        .filter(|e| e.kind == EdgeKind::Implements)
        .collect();
    assert!(
        !implements.is_empty(),
        "expected at least one Implements edge (User extends BaseModel)"
    );
}

#[test]
fn python_comprehensive_private_method_visibility() {
    use gitcortex_core::schema::Visibility;
    let (nodes, _) = run_python_comprehensive();
    let internal = nodes.iter().find(|n| n.name == "_internal_check");
    assert!(internal.is_some(), "expected method '_internal_check'");
    assert_eq!(
        internal.unwrap().metadata.visibility,
        Visibility::Private,
        "_internal_check should be Private"
    );
}

#[test]
fn python_comprehensive_dataclass_is_struct() {
    let (nodes, _) = run_python_comprehensive();
    let user = nodes.iter().find(|n| n.name == "User");
    assert!(user.is_some(), "expected class 'User'");
    assert_eq!(
        user.unwrap().kind,
        NodeKind::Struct,
        "@dataclass User should be Struct kind"
    );
}

// ── Cross-file deferred edge tests ────────────────────────────────────────────
// These tests verify that deferred edge resolution works across file boundaries:
// callers in one file resolve to callees defined in a separate file.

#[test]
fn cross_file_calls_edge_resolved() {
    let (nodes, _edges, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);

    // Both files' nodes should be indexed.
    assert!(
        nodes.iter().any(|n| n.name == "compute_value"),
        "expected 'compute_value' node from xfile_callee.rs"
    );
    assert!(
        nodes.iter().any(|n| n.name == "run"),
        "expected 'run' node from xfile_caller.rs"
    );

    // Deferred call from `run` in xfile_caller.rs → `compute_value` in xfile_callee.rs
    // should have been resolved as a Calls edge.
    let callers = store
        .find_callers("main", "compute_value")
        .expect("find_callers");
    assert!(
        callers.iter().any(|n| n.name == "run"),
        "expected 'run' as a caller of 'compute_value' across files; got: {:?}",
        callers.iter().map(|n| &n.name).collect::<Vec<_>>()
    );
}

#[test]
fn cross_file_calls_edge_multiple_callers() {
    let (_nodes, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);

    // Both `run` and `run_with_branch` call `compute_value`.
    let callers = store
        .find_callers("main", "compute_value")
        .expect("find_callers");
    let caller_names: Vec<&str> = callers.iter().map(|n| n.name.as_str()).collect();
    assert!(
        caller_names.contains(&"run"),
        "expected 'run' in callers; got {caller_names:?}"
    );
    assert!(
        caller_names.contains(&"run_with_branch"),
        "expected 'run_with_branch' in callers; got {caller_names:?}"
    );
}

#[test]
fn cross_file_implements_edge_resolved() {
    let (nodes, edges, _store) = run_pipeline_multi(&["xfile_trait.rs", "xfile_impl.rs"]);

    assert!(
        nodes.iter().any(|n| n.name == "Processor"),
        "expected 'Processor' trait from xfile_trait.rs"
    );
    assert!(
        nodes.iter().any(|n| n.name == "Worker"),
        "expected 'Worker' struct from xfile_impl.rs"
    );

    // Worker implements Processor — deferred Implements edge should be present.
    let impl_edges: Vec<_> = edges
        .iter()
        .filter(|e| e.kind == EdgeKind::Implements)
        .collect();
    assert!(
        !impl_edges.is_empty(),
        "expected at least one Implements edge (Worker → Processor)"
    );
}

#[test]
fn module_dependencies_resolves_cross_file() {
    // xfile_caller imports compute_value (defined in xfile_callee.rs) →
    // module xfile_caller depends on module xfile_callee.
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let deps = store
        .module_dependencies("main", "xfile_caller")
        .expect("module_dependencies");
    let names: Vec<&str> = deps.iter().map(|n| n.name.as_str()).collect();
    assert!(
        names.contains(&"xfile_callee"),
        "xfile_caller should depend on xfile_callee, got: {names:?}"
    );
    // A module never lists itself as a dependency.
    assert!(!names.contains(&"xfile_caller"), "self-dependency leaked");
}

#[test]
fn module_dependencies_unknown_module_is_empty() {
    let (_, _, store) = run_pipeline_multi(&["sample.rs"]);
    let deps = store
        .module_dependencies("main", "no_such_module")
        .expect("module_dependencies");
    assert!(deps.is_empty());
}

#[test]
fn find_type_usages_finds_signature_references() {
    // python_comprehensive: create_user(...) -> User; find_users(repository: Repository) -> List[User]
    // User is used as a return type by multiple functions → Uses edges point to it.
    let (_, _, store) = run_pipeline_multi(&["python_comprehensive.py"]);
    let users = store
        .find_type_usages("main", "User")
        .expect("find_type_usages");
    let names: Vec<&str> = users.iter().map(|n| n.name.as_str()).collect();
    assert!(
        !users.is_empty(),
        "User is referenced in several signatures; expected non-empty usages"
    );
    assert!(
        names.contains(&"create_user") || names.contains(&"find_users"),
        "expected create_user or find_users among User's users, got: {names:?}"
    );
}

#[test]
fn find_type_usages_unknown_type_is_empty() {
    let (_, _, store) = run_pipeline_multi(&["sample.rs"]);
    let users = store
        .find_type_usages("main", "NoSuchTypeXyz")
        .expect("find_type_usages");
    assert!(users.is_empty());
}

#[test]
fn tour_no_seed_produces_component_summary() {
    // A no-seed tour must emit a component-grouped architecture summary, and
    // the markdown must lead with the Architecture/Components section.
    let (_, _, store) = run_pipeline_multi(&[
        "xfile_callee.rs",
        "xfile_caller.rs",
        "xfile_trait.rs",
        "xfile_impl.rs",
    ]);
    let tour = gitcortex_mcp::mcp::tour::generate(&store, "main", None, Some(12)).expect("tour");
    assert!(
        !tour.components.is_empty(),
        "no-seed tour should produce components"
    );
    let md = gitcortex_mcp::mcp::tour::render_markdown(&tour);
    assert!(
        md.contains("# Architecture") && md.contains("## Components"),
        "markdown should lead with architecture summary:\n{md}"
    );
}

#[test]
fn tour_seeded_has_no_components() {
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let tour =
        gitcortex_mcp::mcp::tour::generate(&store, "main", Some("run"), Some(12)).expect("tour");
    assert!(
        tour.components.is_empty(),
        "seeded tour should not compute components"
    );
}

#[test]
fn edge_confidence_inferred_cross_file_extracted_structural() {
    use gitcortex_core::schema::EdgeConfidence;
    // Cross-file run()/run_with_branch() -> compute_value() resolve by name
    // across files => Inferred. Structural Contains edges are always direct
    // => Extracted.
    let (_, edges, _store) =
        run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs", "sample.rs"]);
    let calls: Vec<_> = edges.iter().filter(|e| e.kind == EdgeKind::Calls).collect();
    assert!(
        calls
            .iter()
            .any(|e| e.confidence == EdgeConfidence::Inferred),
        "expected at least one Inferred (cross-file) calls edge"
    );
    let contains: Vec<_> = edges
        .iter()
        .filter(|e| e.kind == EdgeKind::Contains)
        .collect();
    assert!(!contains.is_empty(), "expected Contains edges");
    assert!(
        contains
            .iter()
            .all(|e| e.confidence == EdgeConfidence::Extracted),
        "structural Contains edges must all be Extracted"
    );
}

#[test]
fn get_call_sites_records_caller_and_line() {
    // xfile_caller.rs: run() and run_with_branch() both call compute_value().
    // Each call site must report the caller and a concrete line number.
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let sites = store
        .find_call_sites("main", "compute_value")
        .expect("find_call_sites");
    let callers: Vec<&str> = sites.iter().map(|s| s.caller.name.as_str()).collect();
    assert!(
        callers.contains(&"run") && callers.contains(&"run_with_branch"),
        "expected run and run_with_branch as callers, got: {callers:?}"
    );
    // Every call site must carry a concrete line number.
    for s in &sites {
        assert!(
            s.line.is_some(),
            "call site from {} missing a line number",
            s.caller.name
        );
    }
}

#[test]
fn get_call_sites_unknown_function_is_empty() {
    let (_, _, store) = run_pipeline_multi(&["sample.rs"]);
    let sites = store
        .find_call_sites("main", "no_such_fn")
        .expect("find_call_sites");
    assert!(sites.is_empty());
}

#[test]
fn find_importers_resolves_cross_file_rust_import() {
    // xfile_caller.rs: `use crate::xfile_callee::compute_value;`
    // The importer's file-level module node must be found for compute_value.
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let importers = store
        .find_importers("main", "compute_value")
        .expect("find_importers");
    assert!(
        !importers.is_empty(),
        "compute_value should have at least one importer (xfile_caller module)"
    );
    // Importer is the caller file's module node.
    assert!(
        importers
            .iter()
            .any(|n| n.file.to_string_lossy().contains("xfile_caller")),
        "expected an importer in xfile_caller.rs, got: {:?}",
        importers
            .iter()
            .map(|n| n.file.display().to_string())
            .collect::<Vec<_>>()
    );
}

#[test]
fn find_importers_unknown_symbol_is_empty() {
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let importers = store
        .find_importers("main", "NoSuchSymbolXyz")
        .expect("find_importers");
    assert!(importers.is_empty());
}

#[test]
fn rust_file_gets_module_node() {
    // The file-level module node (added for import attachment) must exist.
    let (nodes, _) = run_pipeline("sample.rs");
    assert!(
        nodes
            .iter()
            .any(|n| n.kind == NodeKind::Module && n.name == "sample"),
        "expected a file-level module node named 'sample'"
    );
}

#[test]
fn type_hierarchy_subtypes_from_trait() {
    // xfile_trait.rs: trait Processor; xfile_impl.rs: impl Processor for Worker.
    // Querying the trait should list Worker as a subtype.
    let (_, _, store) = run_pipeline_multi(&["xfile_trait.rs", "xfile_impl.rs"]);
    let h = store
        .type_hierarchy("main", "Processor")
        .expect("type_hierarchy");
    let sub_names: Vec<&str> = h.subtypes.iter().map(|n| n.name.as_str()).collect();
    assert!(
        sub_names.contains(&"Worker"),
        "Processor subtypes should include Worker, got: {sub_names:?}"
    );
}

#[test]
fn type_hierarchy_supertypes_from_impl() {
    // From the concrete type's side: Worker implements Processor (supertype).
    let (_, _, store) = run_pipeline_multi(&["xfile_trait.rs", "xfile_impl.rs"]);
    let h = store
        .type_hierarchy("main", "Worker")
        .expect("type_hierarchy");
    let super_names: Vec<&str> = h.supertypes.iter().map(|n| n.name.as_str()).collect();
    assert!(
        super_names.contains(&"Processor"),
        "Worker supertypes should include Processor, got: {super_names:?}"
    );
}

#[test]
fn type_hierarchy_unknown_type_is_empty() {
    let (_, _, store) = run_pipeline_multi(&["sample.rs"]);
    let h = store
        .type_hierarchy("main", "NoSuchTypeXyz")
        .expect("type_hierarchy");
    assert!(h.supertypes.is_empty() && h.subtypes.is_empty());
}

#[test]
fn annotations_captured_as_metadata_for_external_decorators() {
    // @dataclass is external (stdlib) — its Annotated edge is dropped, but the
    // name must still be captured on the decorated node's metadata.
    let (nodes, _) = run_pipeline("python_comprehensive.py");
    let user = nodes
        .iter()
        .find(|n| n.name == "User")
        .expect("User class node");
    assert!(
        user.metadata.annotations.iter().any(|a| a == "dataclass"),
        "User should carry the dataclass annotation, got: {:?}",
        user.metadata.annotations
    );
}

#[test]
fn ast_search_by_annotation_finds_decorated() {
    use gitcortex_core::store::AttributeFilter;
    let (_, _, store) = run_pipeline_multi(&["python_comprehensive.py"]);
    let hits = store
        .search_by_attributes(
            "main",
            &AttributeFilter {
                annotation: Some("staticmethod".into()),
                ..Default::default()
            },
            50,
        )
        .expect("search_by_attributes");
    let names: Vec<&str> = hits.iter().map(|n| n.name.as_str()).collect();
    assert!(
        names.contains(&"from_dict"),
        "@staticmethod search should find from_dict, got: {names:?}"
    );
    // Every hit must actually carry the annotation.
    for n in &hits {
        assert!(
            n.metadata
                .annotations
                .iter()
                .any(|a| a.contains("staticmethod")),
            "{} lacks staticmethod annotation",
            n.name
        );
    }
}

#[test]
fn ast_search_async_methods_only() {
    use gitcortex_core::store::AttributeFilter;
    let (_, _, store) = run_pipeline_multi(&["python_comprehensive.py"]);
    let filter = AttributeFilter {
        kind: Some(NodeKind::Method),
        is_async: Some(true),
        ..Default::default()
    };
    let hits = store
        .search_by_attributes("main", &filter, 50)
        .expect("search_by_attributes");
    let names: Vec<&str> = hits.iter().map(|n| n.name.as_str()).collect();
    // AsyncService.fetch_user / save_user are async methods.
    assert!(
        names.contains(&"fetch_user"),
        "expected async method fetch_user, got: {names:?}"
    );
    // Every result must actually be an async method.
    for n in &hits {
        assert_eq!(n.kind, NodeKind::Method);
        assert!(n.metadata.is_async, "{} not async", n.name);
    }
}

#[test]
fn ast_search_kind_filter_excludes_others() {
    use gitcortex_core::store::AttributeFilter;
    let (_, _, store) = run_pipeline_multi(&["sample.rs"]);
    let filter = AttributeFilter {
        kind: Some(NodeKind::Trait),
        ..Default::default()
    };
    let hits = store
        .search_by_attributes("main", &filter, 50)
        .expect("search_by_attributes");
    assert!(!hits.is_empty(), "expected at least the Greeter trait");
    for n in &hits {
        assert_eq!(n.kind, NodeKind::Trait, "{} is not a trait", n.name);
    }
}

#[test]
fn ast_search_complexity_lower_bound() {
    use gitcortex_core::store::AttributeFilter;
    // run_with_branch has complexity 2; a min of 2 must include it, min of 3 must not.
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);

    let at_least_2 = store
        .search_by_attributes(
            "main",
            &AttributeFilter {
                min_complexity: Some(2),
                ..Default::default()
            },
            50,
        )
        .expect("search");
    assert!(
        at_least_2.iter().any(|n| n.name == "run_with_branch"),
        "complexity≥2 should include run_with_branch"
    );

    let at_least_3 = store
        .search_by_attributes(
            "main",
            &AttributeFilter {
                min_complexity: Some(3),
                ..Default::default()
            },
            50,
        )
        .expect("search");
    assert!(
        !at_least_3.iter().any(|n| n.name == "run_with_branch"),
        "complexity≥3 should exclude run_with_branch (complexity 2)"
    );
}

#[test]
fn graph_stats_totals_match_kind_sums() {
    let (nodes, edges, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let stats = store.graph_stats("main").expect("graph_stats");

    // Totals must equal the raw node/edge counts.
    assert_eq!(stats.total_nodes as usize, nodes.len());
    assert_eq!(stats.total_edges as usize, edges.len());

    // Per-kind tallies must sum to the totals.
    let node_sum: u64 = stats.nodes_by_kind.iter().map(|(_, c)| c).sum();
    let edge_sum: u64 = stats.edges_by_kind.iter().map(|(_, c)| c).sum();
    assert_eq!(node_sum, stats.total_nodes);
    assert_eq!(edge_sum, stats.total_edges);

    // Known fixtures: function nodes and at least one calls edge exist.
    assert!(
        stats
            .nodes_by_kind
            .iter()
            .any(|(k, c)| k == "function" && *c >= 2),
        "expected ≥2 function nodes, got: {:?}",
        stats.nodes_by_kind
    );
    assert!(
        stats
            .edges_by_kind
            .iter()
            .any(|(k, c)| k == "calls" && *c >= 1),
        "expected ≥1 calls edge, got: {:?}",
        stats.edges_by_kind
    );
}

#[test]
fn graph_stats_kind_counts_sorted_descending() {
    let (_, _, store) = run_pipeline_multi(&["sample.py", "python_comprehensive.py"]);
    let stats = store.graph_stats("main").expect("graph_stats");
    // Output must be sorted by count descending for deterministic display.
    for w in stats.nodes_by_kind.windows(2) {
        assert!(
            w[0].1 >= w[1].1,
            "nodes_by_kind not sorted desc: {:?}",
            stats.nodes_by_kind
        );
    }
}

#[test]
fn find_unused_symbols_returns_uncalled_nodes() {
    // compute_value is CALLED by run() and run_with_branch(), so it should NOT
    // appear as unused. DataStore is defined but never called or used as a type.
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let unused = store
        .find_unused_symbols("main", None)
        .expect("find_unused_symbols");
    let unused_names: Vec<&str> = unused.iter().map(|n| n.name.as_str()).collect();

    assert!(
        !unused_names.contains(&"compute_value"),
        "compute_value is called by run() — must not appear in unused: {unused_names:?}"
    );
    assert!(
        unused_names.contains(&"DataStore"),
        "DataStore has no callers or uses — must appear in unused: {unused_names:?}"
    );
}

#[test]
fn find_unused_symbols_kind_filter() {
    // With kind=function, only functions/methods should be returned.
    let (_, _, store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    let unused = store
        .find_unused_symbols("main", Some(NodeKind::Function))
        .expect("find_unused_symbols kind=function");
    for node in &unused {
        assert!(
            matches!(node.kind, NodeKind::Function | NodeKind::Method),
            "kind filter returned non-function: {node:?}"
        );
    }
}

#[test]
fn cyclomatic_complexity_simple_function() {
    let (nodes, _) = run_pipeline("sample.rs");
    // make_greeting calls h.greet() — linear function, complexity should be 1.
    let f = nodes.iter().find(|n| n.name == "make_greeting");
    assert!(f.is_some(), "expected 'make_greeting'");
    let complexity = f.unwrap().metadata.lld.complexity;
    assert_eq!(
        complexity,
        Some(1),
        "linear function should have complexity 1, got {complexity:?}"
    );
}

#[test]
fn cyclomatic_complexity_branching_function() {
    let (nodes, _, _store) = run_pipeline_multi(&["xfile_callee.rs", "xfile_caller.rs"]);
    // run_with_branch has one `if` → complexity 2.
    let f = nodes.iter().find(|n| n.name == "run_with_branch");
    assert!(f.is_some(), "expected 'run_with_branch'");
    let complexity = f.unwrap().metadata.lld.complexity;
    assert_eq!(
        complexity,
        Some(2),
        "function with one `if` should have complexity 2, got {complexity:?}"
    );
}