leankg 0.19.21

Lightweight Knowledge Graph for AI-Assisted Development
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
// Phase 1 Benchmark Tests: Real leankg codebase as test data
// Tests all Phase 1 tools against actual indexed leankg source.
// Run: cargo test --release -- phase1_benchmark_test

use leankg::db::models::{CodeElement, Relationship};
use leankg::db::schema::init_db;
use leankg::graph::GraphEngine;
use leankg::indexer::route_extractor::RouteExtractor;

use tempfile::TempDir;

// ── Test harness: index real leankg source patterns ──

fn make_engine() -> (GraphEngine, TempDir) {
    let tmp = TempDir::new().unwrap();
    let db_path = tmp.path().join("test.db");
    let db = init_db(&db_path).unwrap();
    (GraphEngine::new(db), tmp)
}

/// Index patterns from the real leankg codebase
fn index_leankg_self(engine: &GraphEngine) {
    // Real leankg source files (subset representing key modules)
    let elements = vec![
        // Core
        ("src/main.rs", "main", "function", "rust", 1, 50, None, None),
        (
            "src/main.rs",
            "setup_logging",
            "function",
            "rust",
            52,
            65,
            None,
            None,
        ),
        (
            "src/lib.rs",
            "run_benchmark",
            "function",
            "rust",
            1,
            30,
            Some("c1"),
            Some("benchmark"),
        ),
        // DB layer
        (
            "src/db/models.rs",
            "RelationshipType",
            "enum",
            "rust",
            10,
            80,
            None,
            None,
        ),
        (
            "src/db/models.rs",
            "CodeElement",
            "struct",
            "rust",
            215,
            250,
            None,
            None,
        ),
        (
            "src/db/models.rs",
            "Relationship",
            "struct",
            "rust",
            255,
            268,
            None,
            None,
        ),
        (
            "src/db/schema.rs",
            "init_db",
            "function",
            "rust",
            89,
            121,
            None,
            None,
        ),
        (
            "src/db/schema.rs",
            "init_schema",
            "function",
            "rust",
            180,
            400,
            None,
            None,
        ),
        (
            "src/db/schema.rs",
            "run_script",
            "function",
            "rust",
            16,
            26,
            None,
            None,
        ),
        // Graph engine
        (
            "src/graph/query.rs",
            "GraphEngine",
            "struct",
            "rust",
            42,
            50,
            None,
            None,
        ),
        (
            "src/graph/query.rs",
            "get_architecture",
            "function",
            "rust",
            3160,
            3278,
            None,
            None,
        ),
        (
            "src/graph/query.rs",
            "get_graph_schema",
            "function",
            "rust",
            3292,
            3331,
            None,
            None,
        ),
        (
            "src/graph/query.rs",
            "find_dead_code",
            "function",
            "rust",
            3334,
            3370,
            None,
            None,
        ),
        (
            "src/graph/query.rs",
            "count_knowledge",
            "function",
            "rust",
            3280,
            3289,
            None,
            None,
        ),
        (
            "src/graph/query.rs",
            "insert_relationship",
            "function",
            "rust",
            1728,
            1754,
            None,
            None,
        ),
        (
            "src/graph/query.rs",
            "get_callers",
            "function",
            "rust",
            2323,
            2383,
            None,
            None,
        ),
        (
            "src/graph/clustering.rs",
            "cluster_elements",
            "function",
            "rust",
            1,
            200,
            Some("c2"),
            Some("clustering"),
        ),
        (
            "src/graph/cache.rs",
            "QueryCache",
            "struct",
            "rust",
            1,
            30,
            None,
            None,
        ),
        // MCP layer
        (
            "src/mcp/tools.rs",
            "ToolRegistry",
            "struct",
            "rust",
            4,
            6,
            None,
            None,
        ),
        (
            "src/mcp/tools.rs",
            "list_tools",
            "function",
            "rust",
            7,
            930,
            None,
            None,
        ),
        (
            "src/mcp/handler.rs",
            "execute_tool",
            "function",
            "rust",
            206,
            281,
            None,
            None,
        ),
        (
            "src/mcp/handler.rs",
            "get_architecture",
            "function",
            "rust",
            3114,
            3119,
            None,
            None,
        ),
        (
            "src/mcp/handler.rs",
            "find_dead_code",
            "function",
            "rust",
            3128,
            3140,
            None,
            None,
        ),
        (
            "src/mcp/handler.rs",
            "get_graph_schema",
            "function",
            "rust",
            3121,
            3126,
            None,
            None,
        ),
        // Indexer
        (
            "src/indexer/extractor.rs",
            "CodeExtractor",
            "struct",
            "rust",
            1,
            50,
            None,
            None,
        ),
        (
            "src/indexer/extractor.rs",
            "extract",
            "function",
            "rust",
            252,
            290,
            None,
            None,
        ),
        (
            "src/indexer/call_graph.rs",
            "CallGraphBuilder",
            "struct",
            "rust",
            6,
            14,
            None,
            None,
        ),
        (
            "src/indexer/call_graph.rs",
            "extract_calls_with_resolution",
            "function",
            "rust",
            416,
            425,
            None,
            None,
        ),
        (
            "src/indexer/call_graph.rs",
            "resolve_call",
            "function",
            "rust",
            309,
            364,
            None,
            None,
        ),
        (
            "src/indexer/route_extractor.rs",
            "RouteExtractor",
            "struct",
            "rust",
            1,
            20,
            None,
            None,
        ),
        (
            "src/indexer/route_extractor.rs",
            "extract_routes",
            "function",
            "rust",
            21,
            40,
            None,
            None,
        ),
        (
            "src/indexer/route_extractor.rs",
            "routes_to_elements_and_rels",
            "function",
            "rust",
            42,
            100,
            None,
            None,
        ),
        // API/Web
        (
            "src/api/handlers.rs",
            "handle_request",
            "function",
            "rust",
            1,
            30,
            None,
            None,
        ),
        (
            "src/web/handlers.rs",
            "graph",
            "function",
            "rust",
            245,
            1127,
            None,
            None,
        ),
        (
            "src/web/handlers.rs",
            "services_page",
            "function",
            "rust",
            1374,
            1607,
            None,
            None,
        ),
        // Config
        (
            "src/config/mod.rs",
            "Config",
            "struct",
            "rust",
            1,
            30,
            None,
            None,
        ),
        (
            "src/config/project.rs",
            "ProjectConfig",
            "struct",
            "rust",
            1,
            50,
            None,
            None,
        ),
        // Benchmark
        (
            "src/benchmark/runner.rs",
            "BenchmarkRunner",
            "struct",
            "rust",
            1,
            50,
            None,
            None,
        ),
        (
            "src/benchmark/ab_test.rs",
            "run",
            "function",
            "rust",
            129,
            519,
            None,
            None,
        ),
    ];

    for (file, name, etype, lang, ls, le, cid, clabel) in &elements {
        let elem = CodeElement {
            qualified_name: format!("{}::{}", file, name),
            element_type: etype.to_string(),
            name: name.to_string(),
            file_path: file.to_string(),
            line_start: *ls,
            line_end: *le,
            language: lang.to_string(),
            cluster_id: cid.map(|s| s.to_string()),
            cluster_label: clabel.map(|s| s.to_string()),
            ..Default::default()
        };
        engine.insert_element(&elem).unwrap();
    }

    // Call relationships from real leankg source
    let calls = vec![
        (
            "src/main.rs::main",
            "src/main.rs::setup_logging",
            0.95,
            "name",
        ),
        (
            "src/main.rs::main",
            "src/lib.rs::run_benchmark",
            0.90,
            "name",
        ),
        (
            "src/mcp/handler.rs::execute_tool",
            "src/graph/query.rs::get_architecture",
            0.90,
            "name",
        ),
        (
            "src/mcp/handler.rs::execute_tool",
            "src/graph/query.rs::get_graph_schema",
            0.90,
            "name",
        ),
        (
            "src/mcp/handler.rs::execute_tool",
            "src/graph/query.rs::find_dead_code",
            0.90,
            "name",
        ),
        (
            "src/mcp/handler.rs::get_architecture",
            "src/graph/query.rs::get_architecture",
            0.95,
            "name",
        ),
        (
            "src/mcp/handler.rs::get_graph_schema",
            "src/graph/query.rs::get_graph_schema",
            0.95,
            "name",
        ),
        (
            "src/mcp/handler.rs::find_dead_code",
            "src/graph/query.rs::find_dead_code",
            0.95,
            "name",
        ),
        (
            "src/indexer/extractor.rs::extract",
            "src/indexer/route_extractor.rs::extract_routes",
            0.85,
            "name_file_hint",
        ),
        (
            "src/indexer/extractor.rs::extract",
            "src/indexer/call_graph.rs::extract_calls_with_resolution",
            0.85,
            "name_file_hint",
        ),
        (
            "src/indexer/call_graph.rs::extract_calls_with_resolution",
            "src/indexer/call_graph.rs::resolve_call",
            0.90,
            "name",
        ),
        (
            "src/indexer/call_graph.rs::extract_calls_with_resolution",
            "src/indexer/call_graph.rs::CallGraphBuilder",
            0.95,
            "name",
        ),
        (
            "src/db/schema.rs::init_db",
            "src/db/schema.rs::init_schema",
            0.90,
            "name",
        ),
        (
            "src/db/schema.rs::init_schema",
            "src/db/schema.rs::run_script",
            0.85,
            "name",
        ),
        (
            "src/graph/query.rs::get_architecture",
            "src/graph/query.rs::count_knowledge",
            0.90,
            "name",
        ),
        (
            "src/graph/query.rs::find_dead_code",
            "src/db/schema.rs::run_script",
            0.80,
            "name_file_hint",
        ),
    ];

    for (source, target, conf, method) in &calls {
        let rel = Relationship {
            source_qualified: source.to_string(),
            target_qualified: target.to_string(),
            rel_type: "calls".to_string(),
            confidence: *conf,
            metadata: serde_json::json!({
                "resolution_method": method,
                "is_resolved": true,
                "line": 1,
            }),
            ..Default::default()
        };
        engine.insert_relationship(&rel).unwrap();
    }

    // Tested_by relationships
    let tests = vec![
        (
            "tests/phase1_test.rs::test_arch",
            "src/graph/query.rs::get_architecture",
        ),
        (
            "tests/phase1_test.rs::test_schema",
            "src/graph/query.rs::get_graph_schema",
        ),
        (
            "tests/phase1_test.rs::test_dead",
            "src/graph/query.rs::find_dead_code",
        ),
    ];
    for (test_name, tested_fn) in &tests {
        let rel = Relationship {
            source_qualified: test_name.to_string(),
            target_qualified: tested_fn.to_string(),
            rel_type: "tested_by".to_string(),
            confidence: 0.90,
            metadata: serde_json::json!({}),
            ..Default::default()
        };
        engine.insert_relationship(&rel).unwrap();
    }
}

// ── Benchmark tests: get_architecture ──

#[test]
fn bench_architecture_returns_all_keys() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let arch = engine
        .get_architecture(None)
        .expect("get_architecture should succeed");
    let obj = arch.as_object().unwrap();

    let required = [
        "languages",
        "entry_points",
        "routes",
        "clusters",
        "hotspots",
        "relationship_summary",
        "knowledge_count",
        "total_elements",
        "total_files",
        "max_items",
        "truncated_sections",
    ];
    for key in &required {
        assert!(obj.contains_key(*key), "Missing key: {}", key);
    }
}

#[test]
fn bench_architecture_detects_rust_language() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let langs = obj["languages"].as_array().unwrap();
    let rust = langs
        .iter()
        .find(|l| l["language"].as_str().unwrap() == "rust");
    assert!(rust.is_some(), "Should detect Rust");
    assert!(rust.unwrap()["element_count"].as_u64().unwrap() >= 30);
}

#[test]
fn bench_architecture_finds_main_entry_point() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let eps = obj["entry_points"].as_array().unwrap();
    assert!(!eps.is_empty(), "Should find entry points");
    let has_main = eps
        .iter()
        .any(|e| e["qualified_name"].as_str().unwrap().contains("main"));
    assert!(has_main, "Should find main()");
}

#[test]
fn bench_architecture_finds_hotspots() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let hs = obj["hotspots"].as_array().unwrap();
    assert!(!hs.is_empty(), "Should find hotspots");
    // web/handlers.rs has 2 functions, graph/query.rs has 5, mcp/handler.rs has 3
    let query_hot = hs
        .iter()
        .find(|h| h["file_path"].as_str().unwrap().contains("query.rs"));
    assert!(query_hot.is_some(), "graph/query.rs should be a hotspot");
}

#[test]
fn bench_architecture_finds_clusters() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let clusters = obj["clusters"].as_array().unwrap();
    assert_eq!(
        clusters.len(),
        2,
        "Should find benchmark + clustering clusters"
    );
}

#[test]
fn bench_architecture_counts_relationships() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let rels = obj["relationship_summary"].as_array().unwrap();
    let calls = rels
        .iter()
        .find(|r| r["rel_type"].as_str().unwrap() == "calls");
    assert!(calls.is_some(), "Should have calls in summary");
    assert_eq!(
        calls.unwrap()["count"].as_u64().unwrap(),
        16,
        "Should have 16 call edges"
    );
}

// ── Benchmark tests: get_graph_schema ──

#[test]
fn bench_schema_counts_element_types() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let schema = engine.get_graph_schema(None).unwrap();
    let obj = schema.as_object().unwrap();
    let types = obj["element_types"].as_array().unwrap();

    let func = types
        .iter()
        .find(|t| t["element_type"].as_str().unwrap() == "function");
    assert!(func.is_some());
    assert!(func.unwrap()["count"].as_u64().unwrap() >= 20);

    let struct_type = types
        .iter()
        .find(|t| t["element_type"].as_str().unwrap() == "struct");
    assert!(struct_type.is_some());

    let enum_type = types
        .iter()
        .find(|t| t["element_type"].as_str().unwrap() == "enum");
    assert!(enum_type.is_some());
}

#[test]
fn bench_schema_counts_relationship_types() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let schema = engine.get_graph_schema(None).unwrap();
    let obj = schema.as_object().unwrap();
    let rels = obj["relationship_types"].as_array().unwrap();

    let calls = rels
        .iter()
        .find(|r| r["rel_type"].as_str().unwrap() == "calls");
    assert!(calls.is_some());
    assert_eq!(calls.unwrap()["count"].as_u64().unwrap(), 16);

    let tested_by = rels
        .iter()
        .find(|r| r["rel_type"].as_str().unwrap() == "tested_by");
    assert!(tested_by.is_some());
    assert_eq!(tested_by.unwrap()["count"].as_u64().unwrap(), 3);
}

#[test]
fn bench_schema_totals_correct() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let schema = engine.get_graph_schema(None).unwrap();
    let obj = schema.as_object().unwrap();
    assert_eq!(obj["total_elements"].as_u64().unwrap(), 39);
    assert_eq!(obj["total_relationships"].as_u64().unwrap(), 19);
}

// ── Benchmark tests: find_dead_code ──

#[test]
fn bench_dead_code_excludes_called_functions() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let dead = engine.find_dead_code(10).unwrap();
    let names: Vec<&str> = dead.iter().map(|d| d["name"].as_str().unwrap()).collect();

    // These ARE called - should NOT be dead
    assert!(
        !names.contains(&"get_architecture"),
        "get_architecture is called"
    );
    assert!(
        !names.contains(&"get_graph_schema"),
        "get_graph_schema is called"
    );
    assert!(
        !names.contains(&"find_dead_code"),
        "find_dead_code is called"
    );
    assert!(!names.contains(&"resolve_call"), "resolve_call is called");
    assert!(!names.contains(&"init_schema"), "init_schema is called");
}

#[test]
fn bench_dead_code_excludes_entry_points() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let dead = engine.find_dead_code(5).unwrap();
    let names: Vec<&str> = dead.iter().map(|d| d["name"].as_str().unwrap()).collect();
    assert!(!names.contains(&"main"), "main should be excluded");
}

#[test]
fn bench_dead_code_excludes_tested_functions() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let dead = engine.find_dead_code(5).unwrap();
    let names: Vec<&str> = dead.iter().map(|d| d["name"].as_str().unwrap()).collect();
    // get_architecture, get_graph_schema, find_dead_code have tested_by edges
    assert!(!names.contains(&"get_architecture"));
    assert!(!names.contains(&"get_graph_schema"));
    assert!(!names.contains(&"find_dead_code"));
}

#[test]
fn bench_dead_code_finds_truly_dead() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    let dead = engine.find_dead_code(10).unwrap();
    let names: Vec<&str> = dead.iter().map(|d| d["name"].as_str().unwrap()).collect();

    // These have no callers and no tests
    assert!(
        names.contains(&"handle_request"),
        "handle_request should be dead"
    );
    assert!(names.contains(&"graph"), "web graph handler should be dead");
    assert!(
        names.contains(&"services_page"),
        "services_page should be dead"
    );
    assert!(
        names.contains(&"ProjectConfig"),
        "ProjectConfig should be dead"
    );
}

#[test]
fn bench_dead_code_respects_min_lines() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let dead_small = engine.find_dead_code(500).unwrap();
    assert!(
        dead_small.is_empty(),
        "min_lines=500 should exclude everything"
    );

    let dead_large = engine.find_dead_code(10).unwrap();
    assert!(!dead_large.is_empty(), "min_lines=10 should find dead code");
}

// ── Benchmark tests: resolution_method ──

#[test]
fn bench_resolution_method_present_in_metadata() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);
    // The calls we inserted have resolution_method in metadata
    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let rels = obj["relationship_summary"].as_array().unwrap();
    let calls_count = rels
        .iter()
        .find(|r| r["rel_type"].as_str().unwrap() == "calls")
        .unwrap()["count"]
        .as_u64()
        .unwrap();
    assert_eq!(
        calls_count, 16,
        "Should have 16 calls with resolution_method metadata"
    );
}

// ── Benchmark tests: route extraction ──

#[test]
fn bench_route_extraction_go_chi() {
    let source = r#"
package main
import "github.com/go-chi/chi/v5"
func main() {
    r := chi.NewRouter()
    r.Get("/users/{id}", getUser)
    r.Post("/users", createUser)
    r.Delete("/users/{id}", deleteUser)
}
func getUser(w http.ResponseWriter, r *http.Request) {}
func createUser(w http.ResponseWriter, r *http.Request) {}
func deleteUser(w http.ResponseWriter, r *http.Request) {}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_go::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();
    let routes = RouteExtractor::extract_routes(source.as_bytes(), &tree, "test.go", "go");
    assert_eq!(routes.len(), 3, "Should extract 3 chi routes");
    assert!(routes
        .iter()
        .any(|r| r.method == "GET" && r.path == "/users/{id}"));
    assert!(routes
        .iter()
        .any(|r| r.method == "POST" && r.path == "/users"));
    assert!(routes
        .iter()
        .any(|r| r.method == "DELETE" && r.path == "/users/{id}"));
}

#[test]
fn bench_route_extraction_go_gin() {
    let source = r#"
package main
import "github.com/gin-gonic/gin"
func main() {
    g := gin.Default()
    g.GET("/health", healthCheck)
    g.POST("/orders", createOrder)
    g.PUT("/orders/:id", updateOrder)
}
func healthCheck(c *gin.Context) {}
func createOrder(c *gin.Context) {}
func updateOrder(c *gin.Context) {}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_go::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();
    let routes = RouteExtractor::extract_routes(source.as_bytes(), &tree, "test.go", "go");
    assert_eq!(routes.len(), 3, "Should extract 3 gin routes");
    assert!(routes.iter().all(|r| r.framework == "gin"));
}

#[test]
fn bench_route_extraction_ts_express() {
    let source = r#"
const express = require('express');
const app = express();
app.get('/api/users', getUsers);
app.post('/api/users', createUser);
app.put('/api/users/:id', updateUser);
app.delete('/api/users/:id', deleteUser);
function getUsers(req, res) {}
function createUser(req, res) {}
function updateUser(req, res) {}
function deleteUser(req, res) {}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();
    let routes = RouteExtractor::extract_routes(source.as_bytes(), &tree, "app.ts", "typescript");
    assert_eq!(routes.len(), 4, "Should extract 4 express routes");
    assert!(routes.iter().all(|r| r.framework == "express"));
}

#[test]
fn bench_route_extraction_ts_fastify() {
    let source = r#"
import Fastify from 'fastify';
const fastify = Fastify();
fastify.get('/status', getStatus);
fastify.post('/items', createItem);
fastify.patch('/items/:id', updateItem);
function getStatus(req, reply) {}
function createItem(req, reply) {}
function updateItem(req, reply) {}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();
    let routes =
        RouteExtractor::extract_routes(source.as_bytes(), &tree, "server.ts", "typescript");
    assert_eq!(routes.len(), 3, "Should extract 3 fastify routes");
    assert!(routes.iter().all(|r| r.framework == "fastify"));
}

#[test]
fn bench_route_extraction_generates_elements_and_edges() {
    let routes = vec![
        leankg::indexer::route_extractor::RouteInfo {
            method: "GET".to_string(),
            path: "/api/health".to_string(),
            handler: "healthCheck".to_string(),
            framework: "chi".to_string(),
            file_path: "src/handler.go".to_string(),
            line: 10,
        },
        leankg::indexer::route_extractor::RouteInfo {
            method: "POST".to_string(),
            path: "/api/users".to_string(),
            handler: "createUser".to_string(),
            framework: "express".to_string(),
            file_path: "src/app.ts".to_string(),
            line: 20,
        },
    ];
    let (elements, relationships) = RouteExtractor::routes_to_elements_and_rels(&routes);

    assert_eq!(elements.len(), 2, "Should generate 2 route elements");
    assert_eq!(elements[0].element_type, "route");
    assert_eq!(elements[0].metadata["method"], "GET");
    assert_eq!(elements[0].metadata["framework"], "chi");
    assert_eq!(elements[1].metadata["method"], "POST");
    assert_eq!(elements[1].metadata["framework"], "express");

    // 2 routes * 2 edges each (http_calls + defines_route)
    assert_eq!(relationships.len(), 4);
    assert_eq!(relationships[0].rel_type, "http_calls");
    assert_eq!(relationships[1].rel_type, "defines_route");
    assert_eq!(relationships[2].rel_type, "http_calls");
    assert_eq!(relationships[3].rel_type, "defines_route");
}

#[test]
fn bench_route_extraction_ignores_non_http_calls() {
    let source = r#"
const app = express();
app.listen(3000, () => console.log('started'));
app.use(express.json());
const x = computeSomething();
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();
    let routes = RouteExtractor::extract_routes(source.as_bytes(), &tree, "app.ts", "typescript");
    // app.listen and app.use(express.json()) should not be routes
    // app.use with string path would be, but express.json() has no string path
    assert!(
        routes.is_empty()
            || routes
                .iter()
                .all(|r| r.method != "GET" && r.method != "POST"),
        "Should not extract non-route calls as routes"
    );
}

// ── Benchmark tests: route elements in architecture ──

#[test]
fn bench_routes_appear_in_architecture() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    // Insert a route element directly
    let route_elem = CodeElement {
        qualified_name: "src/api/handlers.rs::GET /health".to_string(),
        element_type: "route".to_string(),
        name: "GET /health".to_string(),
        file_path: "src/api/handlers.rs".to_string(),
        line_start: 10,
        line_end: 10,
        language: "rust".to_string(),
        metadata: serde_json::json!({
            "method": "GET",
            "path": "/health",
            "handler": "healthHandler",
            "framework": "axum",
        }),
        ..Default::default()
    };
    engine.insert_element(&route_elem).unwrap();

    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    let routes = obj["routes"].as_array().unwrap();
    assert!(!routes.is_empty(), "Architecture should include routes");
    let health = routes
        .iter()
        .find(|r| r["path"].as_str().unwrap() == "/health");
    assert!(health.is_some(), "Should find /health route");
}

// ── FR-B22: Token budget truncation benchmark tests ──

#[test]
fn bench_arch_max_items_truncates_hotspots() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let full = engine.get_architecture(None).unwrap();
    let full_hs = full["hotspots"].as_array().unwrap().len();

    let arch = engine.get_architecture(Some(2)).unwrap();
    let obj = arch.as_object().unwrap();
    assert_eq!(obj["hotspots"].as_array().unwrap().len(), 2);
    let trunc = obj["truncated_sections"].as_array().unwrap();
    let hs = trunc
        .iter()
        .find(|t| t["section"].as_str() == Some("hotspots"));
    assert!(hs.is_some());
    assert_eq!(hs.unwrap()["original_count"].as_u64(), Some(full_hs as u64));
}

#[test]
fn bench_arch_max_items_truncates_relationships() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let arch = engine.get_architecture(Some(1)).unwrap();
    let obj = arch.as_object().unwrap();
    assert_eq!(obj["relationship_summary"].as_array().unwrap().len(), 1);
    let trunc = obj["truncated_sections"].as_array().unwrap();
    let rs = trunc
        .iter()
        .find(|t| t["section"].as_str() == Some("relationship_summary"));
    assert!(rs.is_some());
    assert_eq!(rs.unwrap()["original_count"].as_u64(), Some(2));
}

#[test]
fn bench_arch_max_items_reports_all_truncated() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let arch = engine.get_architecture(Some(1)).unwrap();
    let obj = arch.as_object().unwrap();
    let trunc = obj["truncated_sections"].as_array().unwrap();
    let names: Vec<&str> = trunc.iter().filter_map(|t| t["section"].as_str()).collect();
    assert!(names.contains(&"hotspots"), "hotspots should be truncated");
    assert!(names.contains(&"clusters"), "clusters should be truncated");
}

#[test]
fn bench_arch_max_items_none_returns_full() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let arch = engine.get_architecture(None).unwrap();
    let obj = arch.as_object().unwrap();
    assert!(obj["truncated_sections"].as_array().unwrap().is_empty());
    assert!(obj["max_items"].is_null());
    assert_eq!(obj["relationship_summary"].as_array().unwrap().len(), 2);
}

#[test]
fn bench_arch_max_items_one_minimal() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let arch = engine.get_architecture(Some(1)).unwrap();
    let obj = arch.as_object().unwrap();
    for key in &[
        "languages",
        "entry_points",
        "hotspots",
        "clusters",
        "relationship_summary",
    ] {
        assert!(
            obj[*key].as_array().unwrap().len() <= 1,
            "Section {} >1 item",
            key
        );
    }
    assert_eq!(obj["max_items"].as_u64(), Some(1));
}

#[test]
fn bench_arch_truncation_reduces_token_size() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let full = engine.get_architecture(None).unwrap();
    let truncated = engine.get_architecture(Some(1)).unwrap();
    assert!(
        truncated.to_string().len() < full.to_string().len(),
        "Truncated should be smaller than full"
    );
}

#[test]
fn bench_schema_max_items_truncates_types() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let full = engine.get_graph_schema(None).unwrap();
    let full_types = full["element_types"].as_array().unwrap().len();

    let schema = engine.get_graph_schema(Some(2)).unwrap();
    let obj = schema.as_object().unwrap();
    assert_eq!(obj["element_types"].as_array().unwrap().len(), 2);
    let trunc = obj["truncated_sections"].as_array().unwrap();
    let et = trunc
        .iter()
        .find(|t| t["section"].as_str() == Some("element_types"));
    assert!(et.is_some());
    assert_eq!(
        et.unwrap()["original_count"].as_u64(),
        Some(full_types as u64)
    );
}

#[test]
fn bench_schema_max_items_truncates_rel_types() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let schema = engine.get_graph_schema(Some(1)).unwrap();
    let obj = schema.as_object().unwrap();
    assert_eq!(obj["relationship_types"].as_array().unwrap().len(), 1);
    let trunc = obj["truncated_sections"].as_array().unwrap();
    let rt = trunc
        .iter()
        .find(|t| t["section"].as_str() == Some("relationship_types"));
    assert!(rt.is_some());
    assert_eq!(rt.unwrap()["original_count"].as_u64(), Some(2));
}

#[test]
fn bench_schema_truncation_preserves_totals() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let schema = engine.get_graph_schema(Some(1)).unwrap();
    let obj = schema.as_object().unwrap();
    assert_eq!(obj["total_elements"].as_u64().unwrap(), 39);
    assert_eq!(obj["total_relationships"].as_u64().unwrap(), 19);
}

#[test]
fn bench_arch_max_items_five_partial() {
    let (engine, _tmp) = make_engine();
    index_leankg_self(&engine);

    let arch = engine.get_architecture(Some(5)).unwrap();
    let obj = arch.as_object().unwrap();
    let trunc = obj["truncated_sections"].as_array().unwrap();

    // languages has only 1 entry, should NOT be truncated with max_items=5
    let lang_trunc = trunc
        .iter()
        .find(|t| t["section"].as_str() == Some("languages"));
    assert!(
        lang_trunc.is_none(),
        "languages (1 item) should not be truncated with max_items=5"
    );
}