tokensave 4.3.13

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
use std::collections::{HashMap, HashSet};
use std::fs;
use tempfile::TempDir;
use tokensave::db::Database;
use tokensave::graph::git::file_churn;
use tokensave::graph::queries::GraphQueryManager;
use tokensave::graph::traversal::GraphTraverser;
use tokensave::tokensave::TokenSave;
use tokensave::types::*;

/// Helper: create a temp database and return (Database, TempDir).
async fn setup_db() -> (Database, TempDir) {
    let dir = TempDir::new().expect("failed to create temp dir");
    let db_path = dir.path().join("test.db");
    let (db, _) = Database::initialize(&db_path)
        .await
        .expect("failed to initialize database");
    (db, dir)
}

/// Helper: create a function node with sensible defaults.
fn make_node(id: &str, name: &str, file_path: &str, visibility: Visibility) -> Node {
    Node {
        id: id.to_string(),
        kind: NodeKind::Function,
        name: name.to_string(),
        qualified_name: format!("crate::{name}"),
        file_path: file_path.to_string(),
        start_line: 1,
        attrs_start_line: 1,
        end_line: 10,
        start_column: 0,
        end_column: 1,
        signature: Some(format!("fn {name}()")),
        docstring: None,
        visibility,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        updated_at: 1000,
    }
}

/// Sets up a call chain: main -> process -> validate -> check.
/// Returns the database and temp dir.
async fn setup_call_chain() -> (Database, TempDir) {
    let (db, dir) = setup_db().await;

    let main_node = make_node("n-main", "main", "src/main.rs", Visibility::Pub);
    let process_node = make_node("n-process", "process", "src/main.rs", Visibility::Pub);
    let validate_node = make_node("n-validate", "validate", "src/lib.rs", Visibility::Pub);
    let check_node = make_node("n-check", "check", "src/lib.rs", Visibility::Pub);

    db.insert_nodes(&[main_node, process_node, validate_node, check_node])
        .await
        .expect("failed to insert nodes");

    let edges = vec![
        Edge {
            source: "n-main".to_string(),
            target: "n-process".to_string(),
            kind: EdgeKind::Calls,
            line: Some(5),
        },
        Edge {
            source: "n-process".to_string(),
            target: "n-validate".to_string(),
            kind: EdgeKind::Calls,
            line: Some(10),
        },
        Edge {
            source: "n-validate".to_string(),
            target: "n-check".to_string(),
            kind: EdgeKind::Calls,
            line: Some(15),
        },
    ];
    db.insert_edges(&edges)
        .await
        .expect("failed to insert edges");

    (db, dir)
}

// ---------------------------------------------------------------------------
// Traversal tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_get_callers() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let callers = traverser
        .get_callers("n-process", 5)
        .await
        .expect("get_callers failed");

    // Direct caller of "process" is "main".
    assert!(
        !callers.is_empty(),
        "process should have at least one caller"
    );
    let caller_names: Vec<&str> = callers.iter().map(|(n, _)| n.name.as_str()).collect();
    assert!(
        caller_names.contains(&"main"),
        "callers of process should include main, got: {caller_names:?}"
    );
}

#[tokio::test]
async fn test_get_callees() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let callees = traverser
        .get_callees("n-process", 5)
        .await
        .expect("get_callees failed");

    let callee_names: Vec<&str> = callees.iter().map(|(n, _)| n.name.as_str()).collect();
    assert!(
        callee_names.contains(&"validate"),
        "callees of process should include validate, got: {callee_names:?}"
    );
}

#[tokio::test]
async fn test_get_callees_transitive() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let callees = traverser
        .get_callees("n-process", 5)
        .await
        .expect("get_callees failed");

    let callee_names: Vec<&str> = callees.iter().map(|(n, _)| n.name.as_str()).collect();
    assert!(
        callee_names.contains(&"validate"),
        "callees should include validate"
    );
    assert!(
        callee_names.contains(&"check"),
        "callees should transitively include check"
    );
}

#[tokio::test]
async fn test_impact_radius() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let subgraph = traverser
        .get_impact_radius("n-check", 10)
        .await
        .expect("get_impact_radius failed");

    let node_names: Vec<&str> = subgraph.nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(
        node_names.contains(&"validate"),
        "impact of check should include validate, got: {node_names:?}"
    );
    assert!(
        node_names.contains(&"process"),
        "impact of check should include process, got: {node_names:?}"
    );
    assert!(
        node_names.contains(&"main"),
        "impact of check should include main, got: {node_names:?}"
    );
}

#[tokio::test]
async fn test_call_graph_bidirectional() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let subgraph = traverser
        .get_call_graph("n-process", 5)
        .await
        .expect("get_call_graph failed");

    let node_names: Vec<&str> = subgraph.nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(
        node_names.contains(&"main"),
        "call graph of process should include caller 'main', got: {node_names:?}"
    );
    assert!(
        node_names.contains(&"validate"),
        "call graph of process should include callee 'validate', got: {node_names:?}"
    );
    assert!(
        node_names.contains(&"process"),
        "call graph should include the center node 'process', got: {node_names:?}"
    );
}

#[tokio::test]
async fn test_bfs_traversal_with_depth_limit() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let opts = TraversalOptions {
        max_depth: 1,
        edge_kinds: Some(vec![EdgeKind::Calls]),
        node_kinds: None,
        direction: TraversalDirection::Outgoing,
        limit: 100,
        include_start: true,
    };

    let subgraph = traverser
        .traverse_bfs("n-main", &opts)
        .await
        .expect("traverse_bfs failed");

    let node_names: Vec<&str> = subgraph.nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(
        node_names.contains(&"main"),
        "depth-1 from main should include main itself"
    );
    assert!(
        node_names.contains(&"process"),
        "depth-1 from main should include process"
    );
    assert!(
        !node_names.contains(&"validate"),
        "depth-1 from main should NOT include validate (that is depth 2)"
    );
    assert!(
        !node_names.contains(&"check"),
        "depth-1 from main should NOT include check (that is depth 3)"
    );
}

#[tokio::test]
async fn test_bfs_traversal_full_depth() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let opts = TraversalOptions {
        max_depth: 10,
        edge_kinds: Some(vec![EdgeKind::Calls]),
        node_kinds: None,
        direction: TraversalDirection::Outgoing,
        limit: 100,
        include_start: true,
    };

    let subgraph = traverser
        .traverse_bfs("n-main", &opts)
        .await
        .expect("traverse_bfs failed");

    assert_eq!(
        subgraph.nodes.len(),
        4,
        "full-depth BFS from main should include all 4 nodes"
    );
}

#[tokio::test]
async fn test_dfs_traversal() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let opts = TraversalOptions {
        max_depth: 10,
        edge_kinds: Some(vec![EdgeKind::Calls]),
        node_kinds: None,
        direction: TraversalDirection::Outgoing,
        limit: 100,
        include_start: true,
    };

    let subgraph = traverser
        .traverse_dfs("n-main", &opts)
        .await
        .expect("traverse_dfs failed");

    assert_eq!(
        subgraph.nodes.len(),
        4,
        "full-depth DFS from main should include all 4 nodes"
    );
}

#[tokio::test]
async fn test_find_path() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let path = traverser
        .find_path("n-main", "n-check", &[EdgeKind::Calls])
        .await
        .expect("find_path failed")
        .expect("path should exist from main to check");

    assert!(
        path.len() >= 2,
        "path from main to check should have at least 2 entries"
    );
    assert_eq!(path[0].0.name, "main", "path should start with main");
    assert_eq!(
        path.last().unwrap().0.name,
        "check",
        "path should end with check"
    );
}

#[tokio::test]
async fn test_find_path_no_route() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    // check -> main has no path via outgoing Calls edges (only reverse direction).
    // But find_path searches bidirectionally. Let's test with a disconnected node.
    let orphan = make_node("n-orphan", "orphan", "src/orphan.rs", Visibility::Private);
    db.insert_node(&orphan).await.expect("insert orphan failed");

    let path = traverser
        .find_path("n-main", "n-orphan", &[EdgeKind::Calls])
        .await
        .expect("find_path failed");

    assert!(
        path.is_none(),
        "there should be no path from main to an orphan node"
    );
}

#[tokio::test]
async fn test_find_path_same_node() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let path = traverser
        .find_path("n-main", "n-main", &[])
        .await
        .expect("find_path failed")
        .expect("path from a node to itself should exist");

    assert_eq!(path.len(), 1, "path from main to main should have 1 entry");
    assert_eq!(path[0].0.name, "main");
}

// ---------------------------------------------------------------------------
// Query tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_find_dead_code() {
    let (db, _dir) = setup_call_chain().await;

    // Add an orphan private function with no incoming edges.
    let orphan = make_node(
        "n-orphan",
        "unused_helper",
        "src/util.rs",
        Visibility::Private,
    );
    db.insert_node(&orphan).await.expect("insert orphan failed");

    let qm = GraphQueryManager::new(&db);
    let dead = qm.find_dead_code(&[]).await.expect("find_dead_code failed");

    let dead_names: Vec<&str> = dead.iter().map(|n| n.name.as_str()).collect();
    assert!(
        dead_names.contains(&"unused_helper"),
        "orphan private function should be detected as dead code, got: {dead_names:?}"
    );
    // "main" should NOT be in the dead code list.
    assert!(
        !dead_names.contains(&"main"),
        "main should not be reported as dead code"
    );
}

#[tokio::test]
async fn test_find_dead_code_excludes_pub() {
    let (db, _dir) = setup_db().await;

    // A public function with no incoming edges should not be flagged.
    let pub_node = make_node("n-pub", "public_api", "src/api.rs", Visibility::Pub);
    db.insert_node(&pub_node)
        .await
        .expect("insert pub_node failed");

    let qm = GraphQueryManager::new(&db);
    let dead = qm.find_dead_code(&[]).await.expect("find_dead_code failed");

    let dead_names: Vec<&str> = dead.iter().map(|n| n.name.as_str()).collect();
    assert!(
        !dead_names.contains(&"public_api"),
        "pub functions should not be reported as dead code"
    );
}

#[tokio::test]
async fn test_find_dead_code_with_kind_filter() {
    let (db, _dir) = setup_db().await;

    let func_node = make_node("n-func", "private_func", "src/lib.rs", Visibility::Private);
    let mut struct_node = make_node("n-struct", "MyStruct", "src/lib.rs", Visibility::Private);
    struct_node.kind = NodeKind::Struct;

    db.insert_nodes(&[func_node, struct_node])
        .await
        .expect("insert nodes failed");

    let qm = GraphQueryManager::new(&db);

    // Filter to only Function kind.
    let dead = qm
        .find_dead_code(&[NodeKind::Function])
        .await
        .expect("find_dead_code failed");

    let dead_names: Vec<&str> = dead.iter().map(|n| n.name.as_str()).collect();
    assert!(
        dead_names.contains(&"private_func"),
        "private_func should be dead code"
    );
    assert!(
        !dead_names.contains(&"MyStruct"),
        "MyStruct should not appear when filtering by Function kind"
    );
}

#[tokio::test]
async fn test_get_node_metrics() {
    let (db, _dir) = setup_call_chain().await;
    let qm = GraphQueryManager::new(&db);

    let metrics = qm
        .get_node_metrics("n-process")
        .await
        .expect("get_node_metrics failed");

    // process has 1 incoming Calls (from main) and 1 outgoing Calls (to validate).
    assert_eq!(metrics.caller_count, 1, "process should have 1 caller");
    assert_eq!(metrics.call_count, 1, "process should have 1 callee");
    assert_eq!(
        metrics.incoming_edge_count, 1,
        "process should have 1 incoming edge total"
    );
    assert_eq!(
        metrics.outgoing_edge_count, 1,
        "process should have 1 outgoing edge total"
    );
}

#[tokio::test]
async fn test_get_file_dependencies() {
    let (db, _dir) = setup_call_chain().await;
    let qm = GraphQueryManager::new(&db);

    // src/main.rs has process -> validate (in src/lib.rs), so it depends on src/lib.rs.
    let deps = qm
        .get_file_dependencies("src/main.rs")
        .await
        .expect("get_file_dependencies failed");

    assert!(
        deps.contains(&"src/lib.rs".to_string()),
        "src/main.rs should depend on src/lib.rs, got: {deps:?}"
    );
}

#[tokio::test]
async fn test_get_file_dependents() {
    let (db, _dir) = setup_call_chain().await;
    let qm = GraphQueryManager::new(&db);

    // src/lib.rs is called from src/main.rs (process -> validate).
    let dependents = qm
        .get_file_dependents("src/lib.rs")
        .await
        .expect("get_file_dependents failed");

    assert!(
        dependents.contains(&"src/main.rs".to_string()),
        "src/lib.rs should be depended on by src/main.rs, got: {dependents:?}"
    );
}

#[tokio::test]
async fn test_find_circular_dependencies() {
    let (db, _dir) = setup_db().await;

    // Set up a circular dependency: file_a -> file_b -> file_a.
    let node_a = make_node("n-a", "func_a", "src/a.rs", Visibility::Pub);
    let node_b = make_node("n-b", "func_b", "src/b.rs", Visibility::Pub);

    db.insert_nodes(&[node_a, node_b])
        .await
        .expect("insert nodes failed");

    // a calls b, b calls a -> circular.
    let edges = vec![
        Edge {
            source: "n-a".to_string(),
            target: "n-b".to_string(),
            kind: EdgeKind::Calls,
            line: Some(1),
        },
        Edge {
            source: "n-b".to_string(),
            target: "n-a".to_string(),
            kind: EdgeKind::Calls,
            line: Some(1),
        },
    ];
    db.insert_edges(&edges).await.expect("insert edges failed");

    // Register files so they show up in get_all_files.
    let file_a = tokensave::types::FileRecord {
        path: "src/a.rs".to_string(),
        content_hash: "hash_a".to_string(),
        size: 100,
        modified_at: 1000,
        indexed_at: 2000,
        node_count: 1,
    };
    let file_b = tokensave::types::FileRecord {
        path: "src/b.rs".to_string(),
        content_hash: "hash_b".to_string(),
        size: 100,
        modified_at: 1000,
        indexed_at: 2000,
        node_count: 1,
    };
    db.upsert_file(&file_a).await.expect("upsert file_a failed");
    db.upsert_file(&file_b).await.expect("upsert file_b failed");

    let qm = GraphQueryManager::new(&db);
    let cycles = qm
        .find_circular_dependencies()
        .await
        .expect("find_circular_dependencies failed");

    assert!(
        !cycles.is_empty(),
        "should detect at least one circular dependency"
    );

    // Verify the cycle contains both files.
    let cycle_files: Vec<&str> = cycles[0].iter().map(|s| s.as_str()).collect();
    assert!(
        cycle_files.contains(&"src/a.rs") && cycle_files.contains(&"src/b.rs"),
        "cycle should contain both src/a.rs and src/b.rs, got: {cycle_files:?}"
    );
}

#[tokio::test]
async fn test_type_hierarchy() {
    let (db, _dir) = setup_db().await;

    let mut trait_node = make_node("n-trait", "MyTrait", "src/lib.rs", Visibility::Pub);
    trait_node.kind = NodeKind::Trait;
    let mut struct_node = make_node("n-struct", "MyStruct", "src/lib.rs", Visibility::Pub);
    struct_node.kind = NodeKind::Struct;
    let mut impl_node = make_node("n-impl", "impl_block", "src/lib.rs", Visibility::Private);
    impl_node.kind = NodeKind::Impl;

    db.insert_nodes(&[trait_node, struct_node, impl_node])
        .await
        .expect("insert nodes failed");

    let edge = Edge {
        source: "n-impl".to_string(),
        target: "n-trait".to_string(),
        kind: EdgeKind::Implements,
        line: None,
    };
    db.insert_edge(&edge).await.expect("insert edge failed");

    let traverser = GraphTraverser::new(&db);
    let subgraph = traverser
        .get_type_hierarchy("n-trait")
        .await
        .expect("get_type_hierarchy failed");

    let node_names: Vec<&str> = subgraph.nodes.iter().map(|n| n.name.as_str()).collect();
    assert!(
        node_names.contains(&"MyTrait"),
        "hierarchy should contain the trait"
    );
    assert!(
        node_names.contains(&"impl_block"),
        "hierarchy should contain the impl that implements the trait"
    );
}

#[tokio::test]
async fn test_traversal_with_limit() {
    let (db, _dir) = setup_call_chain().await;
    let traverser = GraphTraverser::new(&db);

    let opts = TraversalOptions {
        max_depth: 10,
        edge_kinds: Some(vec![EdgeKind::Calls]),
        node_kinds: None,
        direction: TraversalDirection::Outgoing,
        limit: 2,
        include_start: true,
    };

    let subgraph = traverser
        .traverse_bfs("n-main", &opts)
        .await
        .expect("traverse_bfs with limit failed");

    assert!(
        subgraph.nodes.len() <= 2,
        "limit=2 should cap the result to at most 2 nodes, got: {}",
        subgraph.nodes.len()
    );
}

#[tokio::test]
async fn test_traversal_nonexistent_start() {
    let (db, _dir) = setup_db().await;
    let traverser = GraphTraverser::new(&db);

    let opts = TraversalOptions::default();
    let subgraph = traverser
        .traverse_bfs("nonexistent", &opts)
        .await
        .expect("traverse_bfs should not error on missing start");

    assert!(
        subgraph.nodes.is_empty(),
        "traversal from nonexistent node should return empty subgraph"
    );
}

#[tokio::test]
async fn test_node_metrics_depth() {
    let (db, _dir) = setup_db().await;

    // Build a containment hierarchy: file -> module -> function.
    let mut file_node = make_node("n-file", "main.rs", "src/main.rs", Visibility::Pub);
    file_node.kind = NodeKind::File;

    let mut module_node = make_node("n-module", "utils", "src/main.rs", Visibility::Pub);
    module_node.kind = NodeKind::Module;

    let func_node = make_node("n-func", "helper", "src/main.rs", Visibility::Private);

    db.insert_nodes(&[file_node, module_node, func_node])
        .await
        .expect("insert nodes failed");

    let edges = vec![
        Edge {
            source: "n-file".to_string(),
            target: "n-module".to_string(),
            kind: EdgeKind::Contains,
            line: None,
        },
        Edge {
            source: "n-module".to_string(),
            target: "n-func".to_string(),
            kind: EdgeKind::Contains,
            line: None,
        },
    ];
    db.insert_edges(&edges).await.expect("insert edges failed");

    let qm = GraphQueryManager::new(&db);

    let file_metrics = qm.get_node_metrics("n-file").await.expect("metrics failed");
    assert_eq!(file_metrics.depth, 0, "file should be at depth 0");
    assert_eq!(
        file_metrics.child_count, 1,
        "file should have 1 child (module)"
    );

    let module_metrics = qm
        .get_node_metrics("n-module")
        .await
        .expect("metrics failed");
    assert_eq!(module_metrics.depth, 1, "module should be at depth 1");

    let func_metrics = qm.get_node_metrics("n-func").await.expect("metrics failed");
    assert_eq!(func_metrics.depth, 2, "function should be at depth 2");
}

// ---------------------------------------------------------------------------
// File-level DAG tests
// ---------------------------------------------------------------------------

/// Creates a temporary Rust project with cross-file calls and indexes it.
async fn setup_project() -> (TokenSave, TempDir) {
    let dir = TempDir::new().expect("failed to create temp dir");
    let project = dir.path();
    fs::create_dir_all(project.join("src")).expect("failed to create src dir");

    fs::write(
        project.join("src/main.rs"),
        r#"
use crate::utils::helper;
mod utils;

fn main() {
    let result = helper();
    println!("{}", result);
}
"#,
    )
    .expect("failed to write main.rs");

    fs::write(
        project.join("src/utils.rs"),
        r#"
/// Returns a greeting string.
pub fn helper() -> String {
    format!("Hello, world!")
}
"#,
    )
    .expect("failed to write utils.rs");

    let cg = TokenSave::init(project)
        .await
        .expect("failed to init TokenSave");
    cg.index_all().await.expect("failed to index project");
    (cg, dir)
}

#[tokio::test]
async fn test_build_file_adjacency() {
    let (cg, _dir) = setup_project().await;
    let qm = GraphQueryManager::new(cg.db());
    let adj = qm.build_file_adjacency(None).await.unwrap();

    // src/main.rs depends on src/utils.rs (calls helper)
    assert!(
        adj.get("src/main.rs")
            .is_some_and(|deps| deps.contains("src/utils.rs")),
        "main.rs should depend on utils.rs"
    );

    // Self-edges should be excluded
    for (file, deps) in &adj {
        assert!(
            !deps.contains(file),
            "file {file} should not have a self-edge"
        );
    }
}

// ---------------------------------------------------------------------------
// Health algorithm tests
// ---------------------------------------------------------------------------

use tokensave::graph::health::{
    acyclicity_score, compute_composite_health, dependency_depth, gini_coefficient, gini_label,
    modularity_score, HealthDimensions,
};

// --- Gini coefficient ---

#[test]
fn test_gini_perfect_equality() {
    let values = vec![5.0, 5.0, 5.0, 5.0];
    let g = gini_coefficient(&values);
    assert!(
        g.abs() < 1e-9,
        "all-equal values should give Gini ~0.0, got {g}"
    );
}

#[test]
fn test_gini_perfect_inequality() {
    let values = vec![0.0, 0.0, 0.0, 1000.0];
    let g = gini_coefficient(&values);
    assert!(
        g > 0.7,
        "extreme inequality should give Gini > 0.7, got {g}"
    );
}

#[test]
fn test_gini_moderate() {
    let values = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    let g = gini_coefficient(&values);
    assert!(
        (0.1..0.5).contains(&g),
        "moderate distribution should give Gini between 0.1 and 0.5, got {g}"
    );
}

#[test]
fn test_gini_empty() {
    let g = gini_coefficient(&[]);
    assert_eq!(g, 0.0, "empty slice should give Gini 0.0");
}

#[test]
fn test_gini_single() {
    let g = gini_coefficient(&[42.0]);
    assert_eq!(g, 0.0, "single-element slice should give Gini 0.0");
}

#[test]
fn test_gini_label_thresholds() {
    assert_eq!(gini_label(0.10), "low inequality (healthy)");
    assert_eq!(gini_label(0.30), "moderate inequality");
    assert_eq!(gini_label(0.50), "high inequality");
    assert_eq!(gini_label(0.70), "extreme inequality (god files likely)");
}

// --- Acyclicity score ---

fn make_adj(edges: &[(&str, &str)]) -> HashMap<String, HashSet<String>> {
    let mut adj: HashMap<String, HashSet<String>> = HashMap::new();
    for &(src, tgt) in edges {
        adj.entry(src.to_string())
            .or_default()
            .insert(tgt.to_string());
        // ensure target node key exists
        adj.entry(tgt.to_string()).or_default();
    }
    adj
}

#[test]
fn test_acyclicity_no_cycles() {
    let adj = make_adj(&[("a", "b"), ("b", "c")]);
    let (score, cycles) = acyclicity_score(&adj);
    assert_eq!(score, 1.0, "DAG should have acyclicity score 1.0");
    assert_eq!(cycles, 0, "DAG should have 0 cycle edges");
}

#[test]
fn test_acyclicity_with_cycle() {
    let adj = make_adj(&[("a", "b"), ("b", "a")]);
    let (score, cycles) = acyclicity_score(&adj);
    assert!(
        score < 1.0,
        "graph with cycle should have score < 1.0, got {score}"
    );
    assert!(
        cycles > 0,
        "graph with cycle should have > 0 cycle edges, got {cycles}"
    );
}

#[test]
fn test_acyclicity_empty() {
    let adj: HashMap<String, HashSet<String>> = HashMap::new();
    let (score, cycles) = acyclicity_score(&adj);
    assert_eq!(score, 1.0, "empty graph should have acyclicity score 1.0");
    assert_eq!(cycles, 0);
}

// --- Dependency depth ---

#[test]
fn test_depth_linear_chain() {
    let adj = make_adj(&[("a", "b"), ("b", "c"), ("c", "d")]);
    let result = dependency_depth(&adj, 10);
    assert_eq!(
        result.max_depth, 3,
        "linear chain a→b→c→d should have max_depth=3"
    );
    // The deepest chain should contain 4 nodes (a,b,c,d)
    let deepest = result.chains.iter().find(|ch| ch.depth == 3);
    assert!(deepest.is_some(), "should find a chain with depth 3");
    assert_eq!(
        deepest.unwrap().chain.len(),
        4,
        "chain for depth-3 path should have 4 nodes"
    );
}

#[test]
fn test_depth_empty() {
    let adj: HashMap<String, HashSet<String>> = HashMap::new();
    let result = dependency_depth(&adj, 10);
    assert_eq!(result.max_depth, 0, "empty graph should have max_depth=0");
}

#[test]
fn test_depth_with_cycle_breaks() {
    // a→b→a forms a cycle; b→c is an outgoing edge from the SCC
    let adj = make_adj(&[("a", "b"), ("b", "a"), ("b", "c")]);
    let result = dependency_depth(&adj, 10);
    assert!(
        result.max_depth >= 1,
        "should find depth >= 1 even when cycle is present, got {}",
        result.max_depth
    );
}

// --- Modularity score ---

#[test]
fn test_modularity_independent_clusters() {
    // Two disconnected clusters: {a,b} and {c,d}
    let mut adj: HashMap<String, HashSet<String>> = HashMap::new();
    adj.entry("a".to_string())
        .or_default()
        .insert("b".to_string());
    adj.entry("b".to_string()).or_default();
    adj.entry("c".to_string())
        .or_default()
        .insert("d".to_string());
    adj.entry("d".to_string()).or_default();

    let (score, components) = modularity_score(&adj);
    assert!(
        components >= 2,
        "two disconnected clusters should give >= 2 components, got {components}"
    );
    assert!(
        score > 0.0,
        "two-cluster graph should have modularity > 0, got {score}"
    );
}

#[test]
fn test_modularity_single_blob() {
    // Tight cycle: a→b→c→a
    let adj = make_adj(&[("a", "b"), ("b", "c"), ("c", "a")]);
    let (score, components) = modularity_score(&adj);
    assert_eq!(
        components, 1,
        "fully connected cycle should have 1 component"
    );
    assert!(
        score < 0.5,
        "single blob should have low modularity score, got {score}"
    );
}

#[test]
fn test_modularity_empty() {
    let adj: HashMap<String, HashSet<String>> = HashMap::new();
    let (score, _components) = modularity_score(&adj);
    assert_eq!(score, 1.0, "empty graph should have modularity score 1.0");
}

// --- Composite health score ---

#[test]
fn test_composite_health_all_perfect() {
    let dims = HealthDimensions {
        acyclicity: 1.0,
        depth: 1.0,
        equality: 1.0,
        redundancy: 1.0,
        modularity: 1.0,
    };
    assert_eq!(compute_composite_health(&dims), 10000);
}

#[test]
fn test_composite_health_one_zero() {
    let dims = HealthDimensions {
        acyclicity: 0.0,
        depth: 1.0,
        equality: 1.0,
        redundancy: 1.0,
        modularity: 1.0,
    };
    assert_eq!(compute_composite_health(&dims), 0);
}

#[test]
fn test_composite_health_mixed() {
    let dims = HealthDimensions {
        acyclicity: 0.8,
        depth: 0.7,
        equality: 0.9,
        redundancy: 0.6,
        modularity: 0.5,
    };
    let score = compute_composite_health(&dims);
    assert!(
        score > 0 && score < 10000,
        "mixed health should give score between 0 and 10000, got {score}"
    );
}

// ---------------------------------------------------------------------------
// Git churn tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_file_churn() {
    let dir = TempDir::new().expect("failed to create temp dir");
    let project = dir.path();

    // Init a real git repo and make two commits touching the same file
    std::process::Command::new("git")
        .args(["init"])
        .current_dir(project)
        .output()
        .expect("git init failed");
    std::process::Command::new("git")
        .args(["config", "user.email", "test@test.com"])
        .current_dir(project)
        .output()
        .expect("git config email failed");
    std::process::Command::new("git")
        .args(["config", "user.name", "Test"])
        .current_dir(project)
        .output()
        .expect("git config name failed");

    fs::write(project.join("file.rs"), "fn foo() {}").expect("write failed");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(project)
        .output()
        .expect("git add failed");
    std::process::Command::new("git")
        .args(["commit", "-m", "first"])
        .current_dir(project)
        .output()
        .expect("git commit 1 failed");

    fs::write(project.join("file.rs"), "fn foo() {} fn bar() {}").expect("write failed");
    std::process::Command::new("git")
        .args(["add", "."])
        .current_dir(project)
        .output()
        .expect("git add 2 failed");
    std::process::Command::new("git")
        .args(["commit", "-m", "second"])
        .current_dir(project)
        .output()
        .expect("git commit 2 failed");

    let churn = file_churn(project, 90).await.expect("file_churn failed");
    let count = churn.get("file.rs").copied().unwrap_or(0);
    assert!(count >= 2, "file.rs should have churn >= 2, got {count}");
}

#[tokio::test]
async fn test_file_churn_nonexistent_dir() {
    let churn = file_churn(
        std::path::Path::new("/nonexistent/path/that/does/not/exist"),
        90,
    )
    .await
    .expect("file_churn should not error for nonexistent dir");
    assert!(
        churn.is_empty(),
        "should return empty map for nonexistent dir"
    );
}