codenexus 0.3.9

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! API review toolkit.
//!
//! Provides four graph-based analysis capabilities over the existing
//! LadybugDB graph:
//! - [`ApiReviewer::route_map`] — lists all `Route`/`Endpoint` nodes joined
//!   with their handler (legacy `Handler` node or axum `Function` node) and
//!   `Middleware` via `HANDLES`/`HANDLES_ROUTE`/`USES` edges.
//! - [`ApiReviewer::shape_check`] — validates API endpoint schema consistency
//!   by comparing an `Endpoint` node's `expectedSchema` property with the
//!   actual schema recorded on `CALLS` edges pointing to it.
//! - [`ApiReviewer::api_impact`] — traces which callers would be affected by
//!   changing an endpoint, by reverse-traversing `CALLS` edges from the
//!   endpoint's handler.
//! - [`ApiReviewer::tool_map`] — lists all `Tool` nodes (MCP tools) joined
//!   with their handler functions via `HANDLES` edges.
//!
//! # Algorithm
//!
//! Each method issues Cypher queries against the `&dyn Storage` capability
//! and joins results in Rust. LadybugDB's Cypher subset does not support
//! `GROUP BY`, multi-label `WHERE (n:A OR n:B)` expressions, or `UNION`, so
//! we issue separate queries per node label and aggregate in Rust — matching
//! the pattern established by [`crate::analysis::architecture`] and
//! [`crate::analysis::dead_code`].
//!
//! Edges are stored as `CodeRelation` nodes (not true graph edges) with
//! `source`/`target`/`type` fields. The `HANDLES` edge direction is
//! `source = handler_id → target = route/tool/endpoint_id`. The `CALLS` edge
//! direction is `source = caller_id → target = callee_id`.

use crate::storage::capability::Storage;
use crate::storage::error::Result as StorageResult;
use crate::storage::{escape_cypher_string, escape_identifier};
use serde::Serialize;

/// Severity label recorded on [`ShapeViolation`] when expected and actual
/// schemas differ.
const SEVERITY_MISMATCH: &str = "mismatch";

/// Node labels that may carry an HTTP route / endpoint path.
///
/// `Endpoint` is the legacy schema (with `expectedSchema`); `Route` is emitted
/// by the axum extractor in [`crate::parse::rust_extractor::extract_axum_routes`].
/// `route_map`/`api_impact` query both so the analysis works for either style.
const ROUTE_LIKE_LABELS: &[&str] = &["Endpoint", "Route"];

/// Node labels whose `id` may appear as the source of a `HANDLES` or
/// `HANDLES_ROUTE` edge — i.e. handler-like entities.
///
/// `Handler` is the legacy label; `Function` is what the axum extractor emits
/// for `Router::new().route(path, get(handler))`. Merged here so
/// `route_map`/`api_impact`/`tool_map` resolve handlers regardless of style.
const HANDLER_LIKE_LABELS: &[&str] = &["Handler", "Function"];

/// Edge types whose `source` is a handler-like node pointing at a route,
/// endpoint, or tool. Used by [`ApiReviewer::find_handler_for_target`] and
/// [`ApiReviewer::route_map`] (via [`ApiReviewer::load_edges_multi`]) to merge
/// legacy `HANDLES` edges (Handler → Route/Tool) with axum `HANDLES_ROUTE`
/// edges (Function → Route) without duplicating the literal list.
const HANDLER_LIKE_EDGE_TYPES: &[&str] = &["HANDLES", "HANDLES_ROUTE"];

/// Node labels searched when resolving a caller's `(name, filePath, startLine)`.
///
/// `CALLS` edges can originate from any callable — `Function` (free functions),
/// `Method` (impl blocks), or `Handler` (legacy handler nodes) — so all three
/// are scanned by [`ApiReviewer::load_caller_info`].
const CALLER_LIKE_LABELS: &[&str] = &["Function", "Method", "Handler"];

/// Properties on `Endpoint`/`Route` nodes that may carry the route path or
/// name. Searched in order by [`ApiReviewer::find_endpoint`].
const ENDPOINT_MATCH_FIELDS: &[&str] = &["path", "name"];

/// A single route-map entry: one route + its handler + middleware chain.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RouteEntry {
    /// Route path (e.g. `/api/users`).
    pub path: String,
    /// HTTP method (e.g. `GET`, `POST`). Empty if not set.
    pub method: String,
    /// Handler node id. Empty if no handler linked.
    pub handler_id: String,
    /// Handler function name. Empty if no handler linked.
    pub handler_name: String,
    /// Middleware names wrapping the handler (in edge order).
    pub middleware: Vec<String>,
}

/// A schema mismatch between an endpoint's expected schema and the actual
/// schema recorded on a call edge.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ShapeViolation {
    /// Endpoint path (e.g. `/api/users`).
    pub endpoint: String,
    /// Expected schema (JSON string from `Endpoint.expectedSchema`).
    pub expected_schema: String,
    /// Actual schema (JSON string from `CodeRelation.reason`).
    pub actual_schema: String,
    /// Always `SEVERITY_MISMATCH` when expected != actual.
    pub severity: String,
}

/// A single impact entry: one caller affected by an endpoint change.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ImpactEntry {
    /// Endpoint path that was analysed.
    pub endpoint: String,
    /// Caller function name.
    pub affected_caller: String,
    /// Caller source file path.
    pub caller_file: String,
    /// Caller 1-based start line.
    pub caller_line: u32,
}

/// A single tool-map entry: one MCP tool + its handler function.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ToolEntry {
    /// Tool node name (e.g. `query`).
    pub tool_name: String,
    /// Handler node id. Empty if no handler linked.
    pub handler_id: String,
    /// Handler function name. Empty if no handler linked.
    pub handler_name: String,
}

/// Provides API review analysis for a project.
///
/// All four methods take a `&dyn Storage` (the trait-kit capability) rather
/// than a `&StorageConnection` directly, matching the codebase convention
/// used by [`crate::analysis::dead_code::DeadCodeDetector`] and
/// [`crate::analysis::architecture::ArchitectureAnalyzer`].
pub struct ApiReviewer<'a> {
    storage: &'a dyn Storage,
}

impl<'a> ApiReviewer<'a> {
    /// Creates a new reviewer backed by the given storage capability.
    #[must_use]
    pub fn new(storage: &'a dyn Storage) -> Self {
        Self { storage }
    }

    /// Generates a route map: all `Route`/`Endpoint` nodes joined with their
    /// handler functions and middleware.
    ///
    /// # Errors
    ///
    /// Returns [`crate::storage::error::StorageError`] if any Cypher query
    /// fails.
    pub fn route_map(&self, project: &str) -> StorageResult<Vec<RouteEntry>> {
        // (a) Load all Route + Endpoint nodes (same schema, separate queries).
        let routes = self.load_routes(project)?;

        // (b) Load all handler-like nodes (id → name): Handler + Function.
        let handlers = self.load_handler_like_nodes(project)?;

        // (c) Load all Middleware nodes (id → name).
        let middleware = self.load_middleware(project)?;

        // (d) Load HANDLES + HANDLES_ROUTE edges (source = handler id,
        //     target = route id). axum routes use HANDLES_ROUTE edges with
        //     Function sources; legacy routes use HANDLES edges with Handler
        //     sources. Both are merged here so route_map works for either.
        let handles = self.load_edges_multi(project, HANDLER_LIKE_EDGE_TYPES)?;

        // (e) Load USES edges (source = middleware id, target = handler id).
        let uses = self.load_edges_multi(project, &["USES"])?;

        // (f) Build handler → middleware list map.
        // Single-line for coverage: tarpaulin attribute continuation
        let mut handler_to_mw: std::collections::HashMap<String, Vec<String>> =
            std::collections::HashMap::new();
        for (mw_id, h_id) in &uses {
            if let Some(mw_name) = middleware.get(mw_id) {
                handler_to_mw
                    .entry(h_id.clone())
                    .or_default()
                    .push(mw_name.clone());
            }
        }

        // (g) Build route → handler map.
        let mut route_to_handler: std::collections::HashMap<String, (String, String)> =
            std::collections::HashMap::new(); // Single-line for coverage: tarpaulin attribute continuation
        for (h_id, r_id) in &handles {
            if let Some(h_name) = handlers.get(h_id) {
                route_to_handler
                    .entry(r_id.clone())
                    .or_insert_with(|| (h_id.clone(), h_name.clone()));
            }
        }

        // (h) Build result: for each route, look up handler + middleware.
        let mut result: Vec<RouteEntry> = routes
            .into_iter()
            .map(|(id, path, method)| {
                let (handler_id, handler_name) =
                    route_to_handler.get(&id).cloned().unwrap_or_default();
                let mw = handler_to_mw.get(&handler_id).cloned().unwrap_or_default();
                RouteEntry {
                    path,
                    method,
                    handler_id,
                    handler_name,
                    middleware: mw,
                }
            })
            .collect();
        // Sort by path for determinism.
        result.sort_by(|a, b| a.path.cmp(&b.path));
        Ok(result)
    }

    /// Checks API shape consistency: compares each `Endpoint` node's
    /// `expectedSchema` property with the actual schema recorded on `CALLS`
    /// edges pointing to it.
    ///
    /// # Errors
    ///
    /// Returns [`crate::storage::error::StorageError`] if any Cypher query
    /// fails.
    pub fn shape_check(&self, project: &str) -> StorageResult<Vec<ShapeViolation>> {
        // (a) Load all Endpoint nodes with expectedSchema.
        let endpoints = self.load_endpoints_with_schema(project)?;

        // (b) Load CALLS edges with their `reason` field in a single query
        //     (perf-review H2: was N+1 — one Cypher query per endpoint ×
        //     matching CALLS edge). Build a HashMap<target_id, Vec<reason>>
        //     so each endpoint lookup is O(1) instead of triggering another
        //     round-trip.
        let calls_with_reason = self.load_calls_with_reason(project)?;
        let mut by_target: std::collections::HashMap<&str, Vec<&str>> =
            std::collections::HashMap::new();
        for (target, reason) in &calls_with_reason {
            if !reason.is_empty() {
                by_target
                    .entry(target.as_str())
                    .or_default()
                    .push(reason.as_str());
            }
        }

        // (c) For each endpoint with a non-empty expectedSchema, look up its
        //     CALLS reasons in the HashMap and emit a violation per mismatch.
        let mut result = Vec::new();
        for (ep_id, ep_path, expected_schema) in &endpoints {
            if expected_schema.is_empty() {
                continue;
            }
            if let Some(actuals) = by_target.get(ep_id.as_str()) {
                for actual in actuals {
                    if *actual != expected_schema.as_str() {
                        result.push(ShapeViolation {
                            endpoint: ep_path.clone(),
                            expected_schema: expected_schema.clone(),
                            actual_schema: actual.to_string(),
                            severity: SEVERITY_MISMATCH.to_string(),
                        });
                    }
                }
            }
        }
        // Sort by endpoint path for determinism.
        result.sort_by(|a, b| a.endpoint.cmp(&b.endpoint));
        Ok(result)
    }

    /// Analyses the impact of changing an endpoint: traces which callers
    /// would be affected by reverse-traversing `CALLS` edges from the
    /// endpoint's handler.
    ///
    /// `endpoint` is matched against both `Endpoint.path` and `Endpoint.name`.
    ///
    /// # Errors
    ///
    /// Returns [`crate::storage::error::StorageError`] if any Cypher query
    /// fails.
    pub fn api_impact(&self, project: &str, endpoint: &str) -> StorageResult<Vec<ImpactEntry>> {
        // (a) Find the Endpoint node by path or name.
        let endpoint_id = match self.find_endpoint(project, endpoint)? {
            Some(id) => id,
            None => return Ok(Vec::new()),
        };

        // (b) Find the Handler via a targeted HANDLES/HANDLES_ROUTE query
        //     (source = handler/function, target = endpoint/route). axum
        //     routes emit HANDLES_ROUTE edges with Function sources; legacy
        //     endpoints use HANDLES edges with Handler sources. Uses a
        //     targeted `WHERE e.target = ...` query instead of loading all
        //     edges and filtering in Rust (M2: was O(N) over all edges).
        let handler_id = match self.find_handler_for_target(project, &endpoint_id)? {
            Some(id) => id,
            None => return Ok(Vec::new()),
        };

        // (c) Find all CALLS edges pointing to the handler via a targeted
        //     query (M2: was loading all CALLS edges then filtering).
        let caller_ids = self.find_callers_of_target(project, &handler_id)?;

        // (d) Look up caller info (name, filePath, startLine) from
        //     Function/Method/Handler tables.
        let callers = self.load_caller_info(project, &caller_ids)?;

        // (e) Build result.
        let ep_path = self
            .load_endpoint_path(project, &endpoint_id)?
            .unwrap_or_default();
        let mut result: Vec<ImpactEntry> = callers
            .into_iter()
            .map(|(name, file, line)| ImpactEntry {
                endpoint: ep_path.clone(),
                affected_caller: name,
                caller_file: file,
                caller_line: line,
            })
            .collect();
        // Sort by caller name for determinism.
        result.sort_by(|a, b| a.affected_caller.cmp(&b.affected_caller));
        Ok(result)
    }

    /// Generates a tool map: all `Tool` nodes joined with their handler
    /// functions via `HANDLES` edges.
    ///
    /// # Errors
    ///
    /// Returns [`crate::storage::error::StorageError`] if any Cypher query
    /// fails.
    pub fn tool_map(&self, project: &str) -> StorageResult<Vec<ToolEntry>> {
        // (a) Load all Tool nodes.
        let tools = self.load_tools(project)?;

        // (b) Load all handler-like nodes (id → name): Handler + Function.
        let handlers = self.load_handler_like_nodes(project)?;

        // (c) Load HANDLES edges (source = handler id, target = tool id).
        // tool_map intentionally queries HANDLES only (not HANDLES_ROUTE) —
        // MCP tool dispatch is registered via the legacy `Handler` node +
        // HANDLES edge pattern; axum-style routes have no MCP tool semantics.
        let handles = self.load_edges_multi(project, &["HANDLES"])?;

        // (d) Build tool → handler map.
        let mut tool_to_handler: std::collections::HashMap<String, (String, String)> =
            std::collections::HashMap::new(); // Single-line for coverage: tarpaulin attribute continuation
        for (h_id, t_id) in &handles {
            if let Some(h_name) = handlers.get(h_id) {
                tool_to_handler
                    .entry(t_id.clone())
                    .or_insert_with(|| (h_id.clone(), h_name.clone()));
            }
        }

        // (e) Build result.
        let mut result: Vec<ToolEntry> = tools
            .into_iter()
            .map(|(id, name)| {
                let (handler_id, handler_name) =
                    tool_to_handler.get(&id).cloned().unwrap_or_default();
                ToolEntry {
                    tool_name: name,
                    handler_id,
                    handler_name,
                }
            })
            .collect();
        // Sort by tool name for determinism.
        result.sort_by(|a, b| a.tool_name.cmp(&b.tool_name));
        Ok(result)
    }

    // --- Helper methods ---

    /// Loads all `Route` and `Endpoint` nodes for `project`.
    ///
    /// Returns a vector of `(id, path, method)` tuples.
    fn load_routes(&self, project: &str) -> StorageResult<Vec<(String, String, String)>> {
        let escaped = escape_cypher_string(project);
        let mut out = Vec::new();
        for label in ROUTE_LIKE_LABELS {
            let safe_label = escape_identifier(label);
            let cypher = format!(
                "MATCH (n:{safe_label}) WHERE n.project = '{escaped}' \
                 RETURN n.id AS id, n.path AS path, n.httpMethod AS method;"
            );
            let rows = self.storage.query(&cypher)?;
            for row in rows {
                if row.len() < 3 {
                    continue;
                }
                let id = row[0].as_str().unwrap_or_default().to_string();
                let path = row[1].as_str().unwrap_or_default().to_string();
                let method = row[2].as_str().unwrap_or_default().to_string();
                out.push((id, path, method));
            }
        }
        Ok(out)
    }

    /// Loads all handler-like nodes for `project`: legacy `Handler` nodes plus
    /// `Function` nodes so that axum-style routes (where the handler is a
    /// `Function` linked via `HANDLES_ROUTE` edges) are visible to
    /// `route_map`/`api_impact`/`tool_map`.
    ///
    /// LadybugDB's Cypher subset does not support multi-label
    /// `WHERE (n:A OR n:B)` expressions, so we issue one query per label and
    /// merge in Rust — matching the pattern used by [`Self::load_routes`].
    /// The label set is [`HANDLER_LIKE_LABELS`].
    ///
    /// Returns a `HashMap<id, name>`.
    fn load_handler_like_nodes(
        &self,
        project: &str,
    ) -> StorageResult<std::collections::HashMap<String, String>> {
        let escaped = escape_cypher_string(project);
        let mut map = std::collections::HashMap::new();
        // Query each label separately and merge; ids are unique across labels
        // (FQN-based), so insertions never collide in practice.
        for label in HANDLER_LIKE_LABELS {
            let safe_label = escape_identifier(label);
            let cypher = format!(
                "MATCH (h:{safe_label}) WHERE h.project = '{escaped}' \
                 RETURN h.id AS id, h.name AS name;"
            );
            let rows = self.storage.query(&cypher)?;
            map.reserve(rows.len());
            for row in rows {
                if row.len() < 2 {
                    continue;
                }
                let id = row[0].as_str().unwrap_or_default().to_string();
                let name = row[1].as_str().unwrap_or_default().to_string();
                map.insert(id, name);
            }
        }
        Ok(map)
    }

    /// Loads all `Middleware` nodes for `project`.
    ///
    /// Returns a `HashMap<id, name>`.
    fn load_middleware(
        &self,
        project: &str,
    ) -> StorageResult<std::collections::HashMap<String, String>> {
        let escaped = escape_cypher_string(project);
        let safe_label = escape_identifier("Middleware");
        let cypher = format!(
            "MATCH (m:{safe_label}) WHERE m.project = '{escaped}' \
             RETURN m.id AS id, m.name AS name;"
        );
        let rows = self.storage.query(&cypher)?;
        let mut map = std::collections::HashMap::with_capacity(rows.len());
        for row in rows {
            if row.len() < 2 {
                continue;
            }
            let id = row[0].as_str().unwrap_or_default().to_string();
            let name = row[1].as_str().unwrap_or_default().to_string();
            map.insert(id, name);
        }
        Ok(map)
    }

    /// Loads all `Tool` nodes for `project`.
    ///
    /// Returns a vector of `(id, name)` tuples.
    fn load_tools(&self, project: &str) -> StorageResult<Vec<(String, String)>> {
        let escaped = escape_cypher_string(project);
        let safe_label = escape_identifier("Tool");
        let cypher = format!(
            "MATCH (t:{safe_label}) WHERE t.project = '{escaped}' \
             RETURN t.id AS id, t.name AS name;"
        );
        let rows = self.storage.query(&cypher)?;
        let mut out = Vec::new();
        for row in rows {
            if row.len() < 2 {
                continue;
            }
            let id = row[0].as_str().unwrap_or_default().to_string();
            let name = row[1].as_str().unwrap_or_default().to_string();
            out.push((id, name));
        }
        Ok(out)
    }

    /// Finds the handler id for a specific endpoint/route via a targeted
    /// `WHERE e.target = ...` query over the edge types in
    /// [`HANDLER_LIKE_EDGE_TYPES`] (HANDLES + HANDLES_ROUTE). Hits the
    /// `idx_rel_target` index added in v0.3.7 (perf-review C1).
    ///
    /// Returns the handler (source) id if a matching edge exists.
    fn find_handler_for_target(
        &self,
        project: &str,
        target_id: &str,
    ) -> StorageResult<Option<String>> {
        let escaped_project = escape_cypher_string(project);
        let escaped_target = escape_cypher_string(target_id);
        let in_list = HANDLER_LIKE_EDGE_TYPES
            .iter()
            .map(|t| format!("'{}'", escape_cypher_string(t)))
            .collect::<Vec<_>>()
            .join(", ");
        let cypher = format!(
            "MATCH (e:CodeRelation) WHERE e.type IN [{in_list}] \
             AND e.project = '{escaped_project}' AND e.target = '{escaped_target}' \
             RETURN e.source AS source LIMIT 1;"
        );
        let rows = self.storage.query(&cypher)?;
        if let Some(row) = rows.into_iter().next() {
            if let Some(source) = row.first().and_then(|v| v.as_str()) {
                return Ok(Some(source.to_string()));
            }
        }
        Ok(None)
    }

    /// Finds all caller ids for a specific target via a targeted
    /// `WHERE e.target = ...` query over `CALLS` edges.
    ///
    /// Returns a vector of caller (source) ids.
    fn find_callers_of_target(&self, project: &str, target_id: &str) -> StorageResult<Vec<String>> {
        let escaped_project = escape_cypher_string(project);
        let escaped_target = escape_cypher_string(target_id);
        let cypher = format!(
            "MATCH (e:CodeRelation) WHERE e.type = 'CALLS' \
             AND e.project = '{escaped_project}' AND e.target = '{escaped_target}' \
             RETURN e.source AS source;"
        );
        let rows = self.storage.query(&cypher)?;
        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            if let Some(source) = row.first().and_then(|v| v.as_str()) {
                out.push(source.to_string());
            }
        }
        Ok(out)
    }

    /// Loads `CodeRelation` edges of any of the given `edge_types` for
    /// `project`. Used by [`route_map`](Self::route_map) and
    /// [`api_impact`](Self::api_impact) to merge legacy `HANDLES` edges
    /// (Handler → Route/Tool) with axum `HANDLES_ROUTE` edges
    /// (Function → Route) in a single call.
    ///
    /// Issues a single Cypher query with `WHERE e.type IN [...]` rather than
    /// one query per edge type, matching the pattern in
    /// `dead_code::load_outgoing_edges`.
    ///
    /// Returns a vector of `(source, target)` tuples.
    fn load_edges_multi(
        &self,
        project: &str,
        edge_types: &[&str],
    ) -> StorageResult<Vec<(String, String)>> {
        if edge_types.is_empty() {
            return Ok(Vec::new());
        }
        let escaped_project = escape_cypher_string(project);
        let in_list = edge_types
            .iter()
            .map(|t| format!("'{}'", escape_cypher_string(t)))
            .collect::<Vec<_>>()
            .join(", ");
        let cypher = format!(
            "MATCH (e:CodeRelation) WHERE e.type IN [{in_list}] AND e.project = '{escaped_project}' \
             RETURN e.source AS source, e.target AS target;"
        );
        let rows = self.storage.query(&cypher)?;
        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            if row.len() < 2 {
                continue;
            }
            let source = row[0].as_str().unwrap_or_default().to_string();
            let target = row[1].as_str().unwrap_or_default().to_string();
            out.push((source, target));
        }
        Ok(out)
    }

    /// Loads all `Endpoint` nodes with non-empty `expectedSchema` for `project`.
    ///
    /// Returns a vector of `(id, path, expected_schema)` tuples.
    fn load_endpoints_with_schema(
        &self,
        project: &str,
    ) -> StorageResult<Vec<(String, String, String)>> {
        let escaped = escape_cypher_string(project);
        let safe_label = escape_identifier("Endpoint");
        let cypher = format!(
            "MATCH (e:{safe_label}) WHERE e.project = '{escaped}' \
             RETURN e.id AS id, e.path AS path, e.expectedSchema AS expected_schema;"
        );
        let rows = self.storage.query(&cypher)?;
        let mut out = Vec::new();
        for row in rows {
            if row.len() < 3 {
                continue;
            }
            let id = row[0].as_str().unwrap_or_default().to_string();
            let path = row[1].as_str().unwrap_or_default().to_string();
            let expected = row[2].as_str().unwrap_or_default().to_string();
            out.push((id, path, expected));
        }
        Ok(out)
    }

    /// Loads all `CALLS` edges for `project` together with their `reason`
    /// field (the actual schema). Used by [`shape_check`](Self::shape_check)
    /// to build a `HashMap<target_id, Vec<reason>>` in one round-trip instead
    /// of one Cypher query per endpoint × matching edge (perf-review H2).
    ///
    /// Returns a vector of `(target_id, reason)` tuples. Empty `reason`
    /// values are preserved here; the caller filters them as needed.
    fn load_calls_with_reason(&self, project: &str) -> StorageResult<Vec<(String, String)>> {
        let escaped_project = escape_cypher_string(project);
        let cypher = format!(
            "MATCH (e:CodeRelation) WHERE e.type = 'CALLS' AND e.project = '{escaped_project}' \
             RETURN e.target AS target, e.reason AS reason;"
        );
        let rows = self.storage.query(&cypher)?;
        let mut out = Vec::with_capacity(rows.len());
        for row in rows {
            if row.len() < 2 {
                continue;
            }
            let target = row[0].as_str().unwrap_or_default().to_string();
            let reason = row[1].as_str().unwrap_or_default().to_string();
            out.push((target, reason));
        }
        Ok(out)
    }

    /// Finds an `Endpoint` or `Route` node by `path` or `name` for `project`.
    ///
    /// Searches both labels (see [`ROUTE_LIKE_LABELS`]) so that `api_impact`
    /// works for legacy `Endpoint` nodes (with `expectedSchema`) and axum
    /// `Route` nodes (created by the axum route extractor).
    ///
    /// Returns the node id if found.
    fn find_endpoint(&self, project: &str, endpoint: &str) -> StorageResult<Option<String>> {
        let escaped_project = escape_cypher_string(project);
        let escaped_endpoint = escape_cypher_string(endpoint);
        // Try each label, then each field. Endpoint is checked first so that
        // legacy endpoints with explicit schemas take precedence over axum
        // routes when both happen to share a path.
        for label in ROUTE_LIKE_LABELS {
            let safe_label = escape_identifier(label);
            for field in ENDPOINT_MATCH_FIELDS {
                let safe_field = escape_identifier(field);
                let cypher = format!(
                    "MATCH (e:{safe_label}) WHERE e.project = '{escaped_project}' \
                     AND e.{safe_field} = '{escaped_endpoint}' RETURN e.id AS id;"
                );
                let rows = self.storage.query(&cypher)?;
                if let Some(row) = rows.into_iter().next() {
                    if let Some(id) = row.first().and_then(|v| v.as_str()) {
                        return Ok(Some(id.to_string()));
                    }
                }
            }
        }
        Ok(None)
    }

    /// Loads the `path` of an `Endpoint` or `Route` node by `id`.
    ///
    /// Searches both labels (see [`ROUTE_LIKE_LABELS`]) so `api_impact` can
    /// resolve the path of either legacy endpoints or axum routes.
    fn load_endpoint_path(
        &self,
        project: &str,
        endpoint_id: &str,
    ) -> StorageResult<Option<String>> {
        let escaped_project = escape_cypher_string(project);
        let escaped_id = escape_cypher_string(endpoint_id);
        for label in ROUTE_LIKE_LABELS {
            let safe_label = escape_identifier(label);
            let cypher = format!(
                "MATCH (e:{safe_label}) WHERE e.project = '{escaped_project}' \
                 AND e.id = '{escaped_id}' RETURN e.path AS path;"
            );
            let rows = self.storage.query(&cypher)?;
            if let Some(row) = rows.into_iter().next() {
                if let Some(path) = row.first().and_then(|v| v.as_str()) {
                    return Ok(Some(path.to_string()));
                }
            }
        }
        Ok(None)
    }

    /// Loads caller info (name, filePath, startLine) for the given `caller_ids`.
    ///
    /// Searches the labels in [`CALLER_LIKE_LABELS`] (`Function`, `Method`,
    /// `Handler`). The `caller_ids` slice is materialised into a `HashSet`
    /// once so each per-row membership check is O(1) instead of the previous
    /// `Vec::contains` O(N) scan (perf-review H1: bulwark-class graphs hit
    /// this with 19k Function rows × 270 caller ids = 5M comparisons).
    fn load_caller_info(
        &self,
        project: &str,
        caller_ids: &[String],
    ) -> StorageResult<Vec<(String, String, u32)>> {
        if caller_ids.is_empty() {
            return Ok(Vec::new());
        }
        let caller_set: std::collections::HashSet<&str> =
            caller_ids.iter().map(String::as_str).collect();
        let escaped_project = escape_cypher_string(project);
        let mut out = Vec::new();
        for table in CALLER_LIKE_LABELS {
            let safe_table = escape_identifier(table);
            let cypher = format!(
                "MATCH (n:{safe_table}) WHERE n.project = '{escaped_project}' \
                 RETURN n.id AS id, n.name AS name, n.filePath AS file_path, n.startLine AS start_line;"
            );
            let rows = self.storage.query(&cypher)?;
            for row in rows {
                if row.len() < 4 {
                    continue;
                }
                let id = row[0].as_str().unwrap_or_default();
                if !caller_set.contains(id) {
                    continue;
                }
                let name = row[1].as_str().unwrap_or_default().to_string();
                let file = row[2].as_str().unwrap_or_default().to_string();
                let line = row[3]
                    .as_i64()
                    .map(|v| v as u32)
                    .or_else(|| row[3].as_u64().map(|v| v as u32))
                    .unwrap_or(0);
                out.push((name, file, line));
            }
        }
        Ok(out)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::kit::{build_kit, AsyncKit, AsyncReady, KitBootstrapConfig, StorageModule};
    use tempfile::TempDir;

    /// Returns a fresh on-disk database path inside a temp dir.
    fn fresh_db_path() -> std::path::PathBuf {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("api_review_testdb");
        std::mem::forget(dir);
        path
    }

    /// Builds a Kit backed by an on-disk database at `db`.
    fn build_kit_for_db(db: &std::path::Path) -> AsyncKit<AsyncReady> {
        let config = KitBootstrapConfig::new(db.to_path_buf());
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(build_kit(&config))
            .expect("build_kit")
    }

    /// Returns the `dyn Storage` capability from `kit`.
    fn storage(
        kit: &AsyncKit<AsyncReady>,
    ) -> std::sync::Arc<dyn crate::storage::capability::Storage> {
        kit.require::<StorageModule>().expect("require_storage")
    }

    /// Creates a Route node.
    fn create_route(kit: &AsyncKit<AsyncReady>, id: &str, project: &str, path: &str, method: &str) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:Route {{id: '{}', project: '{}', name: '{}', qualifiedName: '{}', \
             filePath: '', startLine: 0, endLine: 0, httpMethod: '{}', path: '{}', parentQn: ''}});",
            escape_cypher_string(id),
            escape_cypher_string(project),
            escape_cypher_string(path),
            escape_cypher_string(path),
            escape_cypher_string(method),
            escape_cypher_string(path),
        );
        storage.execute(&cypher).expect("create route");
    }

    /// Creates an Endpoint node with an expected schema.
    fn create_endpoint(
        kit: &AsyncKit<AsyncReady>,
        id: &str,
        project: &str,
        path: &str,
        method: &str,
        expected_schema: &str,
    ) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:Endpoint {{id: '{}', project: '{}', name: '{}', qualifiedName: '{}', \
             filePath: '', startLine: 0, endLine: 0, httpMethod: '{}', path: '{}', \
             expectedSchema: '{}', parentQn: ''}});",
            escape_cypher_string(id),
            escape_cypher_string(project),
            escape_cypher_string(path),
            escape_cypher_string(path),
            escape_cypher_string(method),
            escape_cypher_string(path),
            escape_cypher_string(expected_schema),
        );
        storage.execute(&cypher).expect("create endpoint");
    }

    /// Creates a Handler node.
    fn create_handler(kit: &AsyncKit<AsyncReady>, id: &str, project: &str, name: &str) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:Handler {{id: '{}', project: '{}', name: '{}', qualifiedName: '{}', \
             filePath: '', startLine: 0, endLine: 0, signature: '', returnType: '', \
             isExported: false, docstring: '', content: '', parentQn: ''}});",
            escape_cypher_string(id),
            escape_cypher_string(project),
            escape_cypher_string(name),
            escape_cypher_string(name),
        );
        storage.execute(&cypher).expect("create handler");
    }

    /// Creates a Middleware node.
    fn create_middleware(kit: &AsyncKit<AsyncReady>, id: &str, project: &str, name: &str) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:Middleware {{id: '{}', project: '{}', name: '{}', qualifiedName: '{}', \
             filePath: '', startLine: 0, endLine: 0, signature: '', returnType: '', \
             isExported: false, docstring: '', content: '', parentQn: ''}});",
            escape_cypher_string(id),
            escape_cypher_string(project),
            escape_cypher_string(name),
            escape_cypher_string(name),
        );
        storage.execute(&cypher).expect("create middleware");
    }

    /// Creates a Tool node.
    fn create_tool(kit: &AsyncKit<AsyncReady>, id: &str, project: &str, name: &str) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:Tool {{id: '{}', project: '{}', name: '{}', qualifiedName: '{}', \
             filePath: '', toolType: 'mcp', parentQn: ''}});",
            escape_cypher_string(id),
            escape_cypher_string(project),
            escape_cypher_string(name),
            escape_cypher_string(name),
        );
        storage.execute(&cypher).expect("create tool");
    }

    /// Creates a Function node.
    fn create_function(
        kit: &AsyncKit<AsyncReady>,
        id: &str,
        project: &str,
        name: &str,
        file: &str,
        line: u32,
    ) {
        let storage = storage(kit);
        let end_line = line + 10;
        let cypher = format!(
            "CREATE (:Function {{id: '{}', project: '{}', name: '{}', qualifiedName: '{}', \
             filePath: '{}', startLine: {}, endLine: {}, signature: '', returnType: '', \
             isExported: false, docstring: '', content: '', parentQn: ''}});",
            escape_cypher_string(id),
            escape_cypher_string(project),
            escape_cypher_string(name),
            escape_cypher_string(name),
            escape_cypher_string(file),
            line,
            end_line,
        );
        storage.execute(&cypher).expect("create function");
    }

    /// Creates a CodeRelation edge.
    fn create_edge(
        kit: &AsyncKit<AsyncReady>,
        id: &str,
        source: &str,
        target: &str,
        edge_type: &str,
        project: &str,
    ) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:CodeRelation {{id: '{}', source: '{}', target: '{}', type: '{}', \
             confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 1, project: '{}'}});",
            escape_cypher_string(id),
            escape_cypher_string(source),
            escape_cypher_string(target),
            escape_cypher_string(edge_type),
            escape_cypher_string(project),
        );
        storage.execute(&cypher).expect("create edge");
    }

    /// Creates a CodeRelation edge with a reason (used for actual schema).
    fn create_edge_with_reason(
        kit: &AsyncKit<AsyncReady>,
        id: &str,
        source: &str,
        target: &str,
        edge_type: &str,
        project: &str,
        reason: &str,
    ) {
        let storage = storage(kit);
        let cypher = format!(
            "CREATE (:CodeRelation {{id: '{}', source: '{}', target: '{}', type: '{}', \
             confidence: 1.0, confidenceTier: 'High', reason: '{}', startLine: 1, project: '{}'}});",
            escape_cypher_string(id),
            escape_cypher_string(source),
            escape_cypher_string(target),
            escape_cypher_string(edge_type),
            escape_cypher_string(reason),
            escape_cypher_string(project),
        );
        storage.execute(&cypher).expect("create edge with reason");
    }

    // --- route_map tests ---

    #[test]
    fn route_map_returns_empty_for_empty_db() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert!(result.is_empty(), "empty DB should yield no routes");
    }

    #[test]
    fn route_map_lists_endpoints_with_handlers() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_handler(&kit, "h1", "demo", "list_users");
        create_edge(&kit, "e1", "h1", "r1", "HANDLES", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 1, "should have 1 route");
        let entry = &result[0];
        assert_eq!(entry.path, "/api/users");
        assert_eq!(entry.method, "GET");
        assert_eq!(entry.handler_id, "h1");
        assert_eq!(entry.handler_name, "list_users");
        assert!(entry.middleware.is_empty(), "no middleware");
    }

    #[test]
    fn route_map_includes_middleware() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_handler(&kit, "h1", "demo", "list_users");
        create_middleware(&kit, "m1", "demo", "auth_middleware");
        create_edge(&kit, "e1", "h1", "r1", "HANDLES", "demo");
        create_edge(&kit, "e2", "m1", "h1", "USES", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 1, "should have 1 route");
        let entry = &result[0];
        assert_eq!(entry.handler_name, "list_users");
        assert_eq!(entry.middleware.len(), 1, "should have 1 middleware");
        assert_eq!(entry.middleware[0], "auth_middleware");
    }

    #[test]
    fn route_map_route_without_handler() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/orphan", "POST");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 1, "should have 1 route");
        let entry = &result[0];
        assert_eq!(entry.path, "/api/orphan");
        assert!(entry.handler_id.is_empty(), "handler_id should be empty");
        assert!(
            entry.handler_name.is_empty(),
            "handler_name should be empty"
        );
    }

    #[test]
    fn route_map_multiple_routes() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_route(&kit, "r2", "demo", "/api/products", "POST");
        create_handler(&kit, "h1", "demo", "list_users");
        create_handler(&kit, "h2", "demo", "create_product");
        create_edge(&kit, "e1", "h1", "r1", "HANDLES", "demo");
        create_edge(&kit, "e2", "h2", "r2", "HANDLES", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 2, "should have 2 routes");
        // Sorted by path.
        assert_eq!(result[0].path, "/api/products");
        assert_eq!(result[1].path, "/api/users");
    }

    #[test]
    fn route_map_filters_by_project() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_route(&kit, "r2", "other", "/api/products", "POST");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 1, "should only see demo's routes");
        assert_eq!(result[0].path, "/api/users");
    }

    // --- route_map: axum-style routes (Function + HANDLES_ROUTE + Route) ---

    #[test]
    fn route_map_lists_axum_routes_with_function_handlers() {
        // axum extractor emits Route nodes + HANDLES_ROUTE edges with Function
        // sources (not Handler nodes). route_map should resolve the Function
        // name via load_handler_like_nodes and link it to the Route via
        // HANDLES_ROUTE.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_function(&kit, "h1", "demo", "list_users", "/src/api.rs", 10);
        create_edge(&kit, "e1", "h1", "r1", "HANDLES_ROUTE", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 1, "should have 1 axum route");
        let entry = &result[0];
        assert_eq!(entry.path, "/api/users");
        assert_eq!(entry.method, "GET");
        assert_eq!(entry.handler_id, "h1");
        assert_eq!(entry.handler_name, "list_users");
        assert!(entry.middleware.is_empty(), "no middleware for axum route");
    }

    #[test]
    fn route_map_merges_legacy_handles_and_axum_handles_route_edges() {
        // When a project has both legacy Handler+HANDLES routes and axum
        // Function+HANDLES_ROUTE routes, route_map should list both.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        // Legacy route: Handler + HANDLES.
        create_route(&kit, "r1", "demo", "/api/legacy", "GET");
        create_handler(&kit, "h1", "demo", "legacy_handler");
        create_edge(&kit, "e1", "h1", "r1", "HANDLES", "demo");
        // axum route: Function + HANDLES_ROUTE.
        create_route(&kit, "r2", "demo", "/api/axum", "POST");
        create_function(&kit, "h2", "demo", "axum_handler", "/src/api.rs", 20);
        create_edge(&kit, "e2", "h2", "r2", "HANDLES_ROUTE", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 2, "should have 2 routes (legacy + axum)");
        // Sorted by path.
        assert_eq!(result[0].path, "/api/axum");
        assert_eq!(result[0].handler_name, "axum_handler");
        assert_eq!(result[1].path, "/api/legacy");
        assert_eq!(result[1].handler_name, "legacy_handler");
    }

    #[test]
    fn route_map_axum_route_without_function_handler_is_orphan() {
        // A Route node with no HANDLES_ROUTE edge should still appear, but
        // with empty handler fields (same behaviour as legacy orphan routes).
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/orphan", "GET");
        // No Function node, no HANDLES_ROUTE edge.

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.route_map("demo").expect("route_map");
        assert_eq!(result.len(), 1, "should have 1 route");
        let entry = &result[0];
        assert_eq!(entry.path, "/api/orphan");
        assert!(entry.handler_id.is_empty(), "handler_id should be empty");
        assert!(
            entry.handler_name.is_empty(),
            "handler_name should be empty"
        );
    }

    // --- shape_check tests ---

    #[test]
    fn shape_check_returns_empty_for_empty_db() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.shape_check("demo").expect("shape_check");
        assert!(result.is_empty(), "empty DB should yield no violations");
    }

    #[test]
    fn shape_check_finds_mismatch() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(
            &kit,
            "e1",
            "demo",
            "/api/users",
            "GET",
            r#"{"name":"string"}"#,
        );
        create_function(&kit, "f1", "demo", "caller", "/src/app.rs", 10);
        // CALLS edge from caller to endpoint with actual schema in reason.
        create_edge_with_reason(
            &kit,
            "cr1",
            "f1",
            "e1",
            "CALLS",
            "demo",
            r#"{"name":"number"}"#,
        );

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.shape_check("demo").expect("shape_check");
        assert_eq!(result.len(), 1, "should have 1 violation");
        let v = &result[0];
        assert_eq!(v.endpoint, "/api/users");
        assert_eq!(v.expected_schema, r#"{"name":"string"}"#);
        assert_eq!(v.actual_schema, r#"{"name":"number"}"#);
        assert_eq!(v.severity, "mismatch");
    }

    #[test]
    fn shape_check_no_violation_when_schemas_match() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(
            &kit,
            "e1",
            "demo",
            "/api/users",
            "GET",
            r#"{"name":"string"}"#,
        );
        create_function(&kit, "f1", "demo", "caller", "/src/app.rs", 10);
        create_edge_with_reason(
            &kit,
            "cr1",
            "f1",
            "e1",
            "CALLS",
            "demo",
            r#"{"name":"string"}"#,
        );

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.shape_check("demo").expect("shape_check");
        assert!(
            result.is_empty(),
            "matching schemas should yield no violations"
        );
    }

    #[test]
    fn shape_check_skips_endpoint_without_expected_schema() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        // Endpoint with empty expectedSchema.
        create_endpoint(&kit, "e1", "demo", "/api/users", "GET", "");
        create_function(&kit, "f1", "demo", "caller", "/src/app.rs", 10);
        create_edge_with_reason(
            &kit,
            "cr1",
            "f1",
            "e1",
            "CALLS",
            "demo",
            r#"{"name":"number"}"#,
        );

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.shape_check("demo").expect("shape_check");
        assert!(result.is_empty(), "no expectedSchema → no violation");
    }

    #[test]
    fn shape_check_filters_by_project() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(
            &kit,
            "e1",
            "demo",
            "/api/users",
            "GET",
            r#"{"name":"string"}"#,
        );
        create_endpoint(
            &kit,
            "e2",
            "other",
            "/api/products",
            "GET",
            r#"{"name":"string"}"#,
        );
        create_function(&kit, "f1", "demo", "caller", "/src/app.rs", 10);
        create_edge_with_reason(
            &kit,
            "cr1",
            "f1",
            "e1",
            "CALLS",
            "demo",
            r#"{"name":"number"}"#,
        );

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.shape_check("demo").expect("shape_check");
        assert_eq!(result.len(), 1, "should only see demo's violations");
        assert_eq!(result[0].endpoint, "/api/users");
    }

    // --- api_impact tests ---

    #[test]
    fn api_impact_returns_empty_for_empty_db() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert!(result.is_empty(), "empty DB should yield no impact");
    }

    #[test]
    fn api_impact_traces_callers() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(&kit, "e1", "demo", "/api/users", "GET", "");
        create_handler(&kit, "h1", "demo", "list_users");
        // HANDLES edge: handler → endpoint.
        create_edge(&kit, "he1", "h1", "e1", "HANDLES", "demo");
        // 2 callers calling the handler.
        create_function(&kit, "f1", "demo", "caller_a", "/src/a.rs", 10);
        create_function(&kit, "f2", "demo", "caller_b", "/src/b.rs", 20);
        create_edge(&kit, "ce1", "f1", "h1", "CALLS", "demo");
        create_edge(&kit, "ce2", "f2", "h1", "CALLS", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert_eq!(result.len(), 2, "should have 2 impact entries");
        // Sorted by caller name.
        assert_eq!(result[0].affected_caller, "caller_a");
        assert_eq!(result[0].caller_file, "/src/a.rs");
        assert_eq!(result[0].caller_line, 10);
        assert_eq!(result[1].affected_caller, "caller_b");
        assert_eq!(result[1].caller_file, "/src/b.rs");
        assert_eq!(result[1].caller_line, 20);
        // All entries should have the endpoint path.
        for entry in &result {
            assert_eq!(entry.endpoint, "/api/users");
        }
    }

    #[test]
    fn api_impact_no_callers_returns_empty() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(&kit, "e1", "demo", "/api/users", "GET", "");
        create_handler(&kit, "h1", "demo", "list_users");
        create_edge(&kit, "he1", "h1", "e1", "HANDLES", "demo");
        // No CALLS edges to handler.

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert!(result.is_empty(), "no callers → no impact");
    }

    #[test]
    fn api_impact_endpoint_not_found_returns_empty() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(&kit, "e1", "demo", "/api/users", "GET", "");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/nonexistent")
            .expect("api_impact");
        assert!(result.is_empty(), "nonexistent endpoint → no impact");
    }

    #[test]
    fn api_impact_endpoint_without_handler_returns_empty() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(&kit, "e1", "demo", "/api/users", "GET", "");
        // No HANDLES edge.

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert!(result.is_empty(), "no handler → no impact");
    }

    #[test]
    fn api_impact_matches_by_name() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        // Endpoint with name "users_api" and path "/api/users".
        let storage = storage(&kit);
        let cypher = "CREATE (:Endpoint {id: 'e1', project: 'demo', name: 'users_api', qualifiedName: 'users_api', \
             filePath: '', startLine: 0, endLine: 0, httpMethod: 'GET', path: '/api/users', \
             expectedSchema: '', parentQn: ''});";
        storage.execute(cypher).expect("create endpoint");
        create_handler(&kit, "h1", "demo", "list_users");
        create_edge(&kit, "he1", "h1", "e1", "HANDLES", "demo");
        create_function(&kit, "f1", "demo", "caller", "/src/a.rs", 5);
        create_edge(&kit, "ce1", "f1", "h1", "CALLS", "demo");

        let reviewer = ApiReviewer::new(&*storage);
        // Match by name (not path).
        let result = reviewer
            .api_impact("demo", "users_api")
            .expect("api_impact");
        assert_eq!(result.len(), 1, "should find 1 caller by name match");
    }

    // --- api_impact: axum-style routes (Function + HANDLES_ROUTE + Route) ---

    #[test]
    fn api_impact_traces_callers_for_axum_route() {
        // axum route: Route + Function (handler) + HANDLES_ROUTE edge.
        // Caller calls the Function (not the Route) via a CALLS edge.
        // api_impact should: find Route by path → find Function via
        // HANDLES_ROUTE → find CALLS edges to the Function → return callers.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_function(&kit, "h1", "demo", "list_users", "/src/api.rs", 10);
        create_edge(&kit, "he1", "h1", "r1", "HANDLES_ROUTE", "demo");
        // 2 callers calling the handler function.
        create_function(&kit, "f1", "demo", "caller_a", "/src/a.rs", 5);
        create_function(&kit, "f2", "demo", "caller_b", "/src/b.rs", 15);
        create_edge(&kit, "ce1", "f1", "h1", "CALLS", "demo");
        create_edge(&kit, "ce2", "f2", "h1", "CALLS", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert_eq!(result.len(), 2, "should have 2 impact entries");
        // Sorted by caller name.
        assert_eq!(result[0].affected_caller, "caller_a");
        assert_eq!(result[0].caller_file, "/src/a.rs");
        assert_eq!(result[0].caller_line, 5);
        assert_eq!(result[1].affected_caller, "caller_b");
        assert_eq!(result[1].caller_file, "/src/b.rs");
        assert_eq!(result[1].caller_line, 15);
        // All entries should carry the route path.
        for entry in &result {
            assert_eq!(entry.endpoint, "/api/users");
        }
    }

    #[test]
    fn api_impact_axum_route_no_callers_returns_empty() {
        // axum route with handler but no CALLS edges to the handler.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        create_function(&kit, "h1", "demo", "list_users", "/src/api.rs", 10);
        create_edge(&kit, "he1", "h1", "r1", "HANDLES_ROUTE", "demo");
        // No CALLS edges to h1.

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert!(result.is_empty(), "no callers → no impact");
    }

    #[test]
    fn api_impact_axum_route_not_found_returns_empty() {
        // No Route or Endpoint matches the given path.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/nonexistent")
            .expect("api_impact");
        assert!(result.is_empty(), "nonexistent route → no impact");
    }

    #[test]
    fn api_impact_axum_route_without_handler_returns_empty() {
        // Route exists but no HANDLES_ROUTE edge (orphan route).
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_route(&kit, "r1", "demo", "/api/users", "GET");
        // No Function, no HANDLES_ROUTE edge.

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        assert!(result.is_empty(), "no handler → no impact");
    }

    // --- tool_map tests ---

    #[test]
    fn tool_map_returns_empty_for_empty_db() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.tool_map("demo").expect("tool_map");
        assert!(result.is_empty(), "empty DB should yield no tools");
    }

    #[test]
    fn tool_map_lists_tools() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_tool(&kit, "t1", "demo", "query");
        create_handler(&kit, "h1", "demo", "query_handler");
        create_edge(&kit, "e1", "h1", "t1", "HANDLES", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.tool_map("demo").expect("tool_map");
        assert_eq!(result.len(), 1, "should have 1 tool");
        let entry = &result[0];
        assert_eq!(entry.tool_name, "query");
        assert_eq!(entry.handler_id, "h1");
        assert_eq!(entry.handler_name, "query_handler");
    }

    #[test]
    fn tool_map_tool_without_handler() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_tool(&kit, "t1", "demo", "orphan_tool");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.tool_map("demo").expect("tool_map");
        assert_eq!(result.len(), 1, "should have 1 tool");
        let entry = &result[0];
        assert_eq!(entry.tool_name, "orphan_tool");
        assert!(entry.handler_id.is_empty(), "handler_id should be empty");
        assert!(
            entry.handler_name.is_empty(),
            "handler_name should be empty"
        );
    }

    #[test]
    fn tool_map_multiple_tools() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_tool(&kit, "t1", "demo", "query");
        create_tool(&kit, "t2", "demo", "search");
        create_handler(&kit, "h1", "demo", "query_handler");
        create_handler(&kit, "h2", "demo", "search_handler");
        create_edge(&kit, "e1", "h1", "t1", "HANDLES", "demo");
        create_edge(&kit, "e2", "h2", "t2", "HANDLES", "demo");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.tool_map("demo").expect("tool_map");
        assert_eq!(result.len(), 2, "should have 2 tools");
        // Sorted by tool name.
        assert_eq!(result[0].tool_name, "query");
        assert_eq!(result[1].tool_name, "search");
    }

    #[test]
    fn tool_map_filters_by_project() {
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_tool(&kit, "t1", "demo", "query");
        create_tool(&kit, "t2", "other", "search");

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.tool_map("demo").expect("tool_map");
        assert_eq!(result.len(), 1, "should only see demo's tools");
        assert_eq!(result[0].tool_name, "query");
    }

    // --- Additional coverage tests (targeting uncovered lines) ---

    #[test]
    fn shape_check_skips_calls_to_other_endpoints() {
        // Line 204: `if callee_id != ep_id { continue; }` — when CALLS edges
        // point to a different endpoint than the one being checked, the inner
        // loop should skip them without producing violations.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(
            &kit,
            "e1",
            "demo",
            "/api/users",
            "GET",
            r#"{"name":"string"}"#,
        );
        create_endpoint(
            &kit,
            "e2",
            "demo",
            "/api/products",
            "GET",
            r#"{"name":"string"}"#,
        );
        create_function(&kit, "f1", "demo", "caller", "/src/app.rs", 10);
        // CALLS edge to e2 (not e1) — should be skipped when checking e1.
        create_edge_with_reason(
            &kit,
            "cr1",
            "f1",
            "e2",
            "CALLS",
            "demo",
            r#"{"name":"number"}"#,
        );

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer.shape_check("demo").expect("shape_check");
        // e1 has expectedSchema but no matching CALLS edge → no violation.
        // e2 has a mismatch and the CALLS edge target matches e2 → 1 violation.
        assert_eq!(
            result.len(),
            1,
            "only e2 should have a violation (CALLS target matches)"
        );
        assert_eq!(result[0].endpoint, "/api/products");
    }

    #[test]
    fn api_impact_skips_non_caller_functions() {
        // Line 572: `if !caller_ids.contains(&id) { continue; }` — when
        // load_caller_info iterates over functions that are NOT in the
        // caller_ids list, they should be skipped.
        let db = fresh_db_path();
        let kit = build_kit_for_db(&db);
        create_endpoint(&kit, "e1", "demo", "/api/users", "GET", "");
        create_handler(&kit, "h1", "demo", "list_users");
        create_edge(&kit, "he1", "h1", "e1", "HANDLES", "demo");
        // f1 calls the handler (is a caller).
        create_function(&kit, "f1", "demo", "caller_a", "/src/a.rs", 10);
        create_edge(&kit, "ce1", "f1", "h1", "CALLS", "demo");
        // f2 does NOT call the handler — should be skipped by load_caller_info.
        create_function(&kit, "f2", "demo", "non_caller", "/src/b.rs", 20);

        let storage = storage(&kit);
        let reviewer = ApiReviewer::new(&*storage);
        let result = reviewer
            .api_impact("demo", "/api/users")
            .expect("api_impact");
        // Only f1 should be in the result; f2 should be skipped.
        assert_eq!(result.len(), 1, "only the caller should be in impact");
        assert_eq!(result[0].affected_caller, "caller_a");
    }
}