rustqual 1.2.4

Comprehensive Rust code quality analyzer — seven dimensions: IOSP, Complexity, DRY, SRP, Coupling, Test Quality, Architecture
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
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
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
//! Tests for Check B (parity-coverage).
//!
//! Each test sets up a small multi-file workspace and asserts the
//! `missing_adapters` set produced by `check_missing_adapter` for each
//! target-layer pub-fn. Suppression is covered end-to-end in Task 5.

use super::support::{
    build_workspace, cli_mcp_config, empty_cfg_test, four_layer, globset, ports_app_cli_mcp,
    run_check_b, three_layer,
};
use crate::adapters::analyzers::architecture::compiled::CompiledCallParity;
use crate::adapters::analyzers::architecture::{MatchLocation, ViolationKind};
use std::collections::HashSet;

fn make_config(
    call_depth: usize,
    adapters: &[&str],
    exclude_targets: &[&str],
) -> CompiledCallParity {
    CompiledCallParity {
        adapters: adapters.iter().map(|s| s.to_string()).collect(),
        target: "application".to_string(),
        call_depth,
        exclude_targets: globset(exclude_targets),
        transparent_wrappers: HashSet::new(),
        transparent_macros: HashSet::new(),
        promoted_attributes: HashSet::new(),
        single_touchpoint: crate::config::architecture::SingleTouchpointMode::default(),
    }
}

/// `missing_adapters` list for a specific `target_fn` — `None` when
/// no CallParityMissingAdapter finding exists for that target.
fn missing_adapters_for(findings: &[MatchLocation], target_fn: &str) -> Option<Vec<String>> {
    findings.iter().find_map(|f| match &f.kind {
        ViolationKind::CallParityMissingAdapter {
            target_fn: tf,
            missing_adapters,
            ..
        } if tf == target_fn => Some(missing_adapters.clone()),
        _ => None,
    })
}

/// Hint text for the missing-adapter finding on `target_fn`, if any.
/// Returns `None` if there's no finding or the finding has hint=None.
fn hint_for(findings: &[MatchLocation], target_fn: &str) -> Option<String> {
    findings.iter().find_map(|f| match &f.kind {
        ViolationKind::CallParityMissingAdapter {
            target_fn: tf,
            hint,
            ..
        } if tf == target_fn => hint.clone(),
        _ => None,
    })
}

/// Three-layer `cli + mcp + application` config with `application` as
/// target and an empty exclude_targets — the shared shape for the
/// hint/cascade/promoted-attribute tests further down.
fn cli_mcp_config_full() -> CompiledCallParity {
    let mut cp = cli_mcp_config(3);
    cp.exclude_targets = globset(&[]);
    cp
}

/// Extract the `(target_fn, missing_adapters)` pair from a
/// CallParityMissingAdapter finding, as `String` for easy assertions.
fn missing_pairs(findings: &[MatchLocation]) -> Vec<(String, Vec<String>)> {
    findings
        .iter()
        .filter_map(|f| match &f.kind {
            ViolationKind::CallParityMissingAdapter {
                target_fn,
                missing_adapters,
                ..
            } => Some((target_fn.clone(), missing_adapters.clone())),
            _ => None,
        })
        .collect()
}

// ── Direct / transitive coverage ──────────────────────────────

#[test]
fn test_target_fn_called_from_all_adapters_passes() {
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn handle_stats() { get_stats(); }
            "#,
        ),
        (
            "src/rest/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn post_stats() { get_stats(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(
        missing_pairs(&findings).is_empty(),
        "covered-by-all should pass, got {findings:?}"
    );
}

#[test]
fn test_target_fn_missing_one_adapter_fails() {
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn handle_stats() { get_stats(); }
            "#,
        ),
        // rest is missing
    ]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1);
    assert!(pairs[0].0.ends_with("get_stats"));
    assert_eq!(pairs[0].1, vec!["rest".to_string()]);
}

#[test]
fn test_target_fn_missing_two_adapters_fails() {
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1);
    let mut missing = pairs[0].1.clone();
    missing.sort();
    assert_eq!(missing, vec!["mcp".to_string(), "rest".to_string()]);
}

#[test]
fn test_target_fn_not_called_from_any_adapter_lists_all_missing() {
    let ws = build_workspace(&[("src/application/stats.rs", "pub fn get_stats() {}")]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1);
    let mut missing = pairs[0].1.clone();
    missing.sort();
    assert_eq!(
        missing,
        vec!["cli".to_string(), "mcp".to_string(), "rest".to_string()]
    );
}

#[test]
fn test_target_fn_reached_transitively_passes() {
    // rest reaches via a service wrapper (depth 2).
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn handle_stats() { get_stats(); }
            "#,
        ),
        (
            "src/rest/service.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn wrap() { get_stats(); }
            "#,
        ),
        (
            "src/rest/handlers.rs",
            r#"
            use crate::rest::service::wrap;
            pub fn post_stats() { wrap(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(
        missing_pairs(&findings).is_empty(),
        "transitive coverage should pass, got {findings:?}"
    );
}

#[test]
fn test_target_fn_transitive_depth_exceeds_fails() {
    // REST only reaches the target through a layer-less intermediate
    // (`src/shared/` is not a mapped layer), so a shallow call_depth
    // misses it while cli + mcp hit the target directly at depth 1.
    //
    // Backward walk from get_stats:
    //   depth 1: cli::cmd_stats, mcp::handle_stats, shared::deep_call
    //   depth 2: rest::post_stats (through deep_call)
    // With call_depth = 1 the BFS stops at depth 1 → rest missing.
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn handle_stats() { get_stats(); }
            "#,
        ),
        (
            "src/shared/helpers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn deep_call() { get_stats(); }
            "#,
        ),
        (
            "src/rest/handlers.rs",
            r#"
            use crate::shared::helpers::deep_call;
            pub fn post_stats() { deep_call(); }
            "#,
        ),
    ]);
    let cp = make_config(1, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1, "got {findings:?}");
    assert_eq!(pairs[0].1, vec!["rest".to_string()]);
}

#[test]
fn test_target_fn_only_called_from_tests_fails() {
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::stats::get_stats;
            pub fn handle_stats() { get_stats(); }
            "#,
        ),
        (
            "src/rest/tests.rs",
            r#"
            use crate::application::stats::get_stats;
            #[cfg(test)]
            mod tests {
                use super::*;
                #[test]
                fn test_stats() { get_stats(); }
            }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let mut cfg_test = HashSet::new();
    cfg_test.insert("src/rest/tests.rs".to_string());
    let findings = run_check_b(&ws, &four_layer(), &cp, &cfg_test);
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1, "got {findings:?}");
    assert_eq!(pairs[0].1, vec!["rest".to_string()]);
}

#[test]
fn test_non_pub_target_fn_ignored() {
    // Private target fn is not part of the parity surface → no finding
    // even when no adapter calls it.
    let ws = build_workspace(&[("src/application/stats.rs", "fn get_stats() {}")]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(missing_pairs(&findings).is_empty());
}

#[test]
fn test_method_caller_with_receiver_binding_counts() {
    // `let s = Session::open(); s.search()` → receiver tracking resolves
    // the method call to application::session::Session::search, so the
    // mcp adapter counts as reaching `search`.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session {
                pub fn open() -> Self { Session }
                pub fn search(&self) {}
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() {
                let s = Session::open();
                s.search();
            }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn handle_search() {
                let s = Session::open();
                s.search();
            }
            "#,
        ),
    ]);
    // Only test cli + mcp coverage so rest doesn't appear as missing.
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    // `search` is reached from both adapters; `open` is reached from both.
    assert!(
        missing_pairs(&findings).is_empty(),
        "method-call via binding should count, got {findings:?}"
    );
}

#[test]
fn test_method_caller_without_binding_ignored() {
    // Caller invokes `x.get_stats()` on an unknown-type receiver →
    // `<method>:get_stats`, layer-unknown, so the call doesn't count
    // as reaching `crate::application::stats::get_stats`.
    let ws = build_workspace(&[
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            pub fn cmd_stats(x: UnknownType) { x.get_stats(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1);
    assert_eq!(pairs[0].1, vec!["cli".to_string()]);
}

// ── exclude_targets glob ──────────────────────────────────────

#[test]
fn test_target_in_exclude_targets_glob_ignored() {
    let ws = build_workspace(&[
        ("src/application/setup.rs", "pub fn run() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::setup::run;
            pub fn cmd_setup() { run(); }
            "#,
        ),
        // mcp + rest missing, but `setup::run` is excluded.
    ]);
    let cp = make_config(3, &["cli", "mcp", "rest"], &["application::setup::*"]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(
        missing_pairs(&findings).is_empty(),
        "glob-excluded target should not produce a finding, got {findings:?}"
    );
}

#[test]
fn test_target_not_matching_exclude_glob_still_checked() {
    let ws = build_workspace(&[
        (
            "src/application/setup.rs",
            r#"
            pub fn run() {}
            "#,
        ),
        ("src/application/stats.rs", "pub fn get_stats() {}"),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::setup::run;
            use crate::application::stats::get_stats;
            pub fn cmd_setup() { run(); }
            pub fn cmd_stats() { get_stats(); }
            "#,
        ),
    ]);
    // Exclude only setup::*; stats::get_stats remains in scope.
    let cp = make_config(3, &["cli", "mcp"], &["application::setup::*"]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1, "got {findings:?}");
    assert!(pairs[0].0.ends_with("get_stats"));
    assert_eq!(pairs[0].1, vec!["mcp".to_string()]);
}

#[test]
fn test_exclude_targets_uses_canonical_without_crate_prefix() {
    // Glob patterns in config don't carry the `crate::` prefix — the
    // matcher needs to strip it before comparing.
    let ws = build_workspace(&[("src/application/setup.rs", "pub fn run() {}")]);
    let cp = make_config(3, &["cli", "mcp"], &["application::setup::run"]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(missing_pairs(&findings).is_empty());
}

// ── Orphan target-layer islands (v1.2.1) ───────────────────────

#[test]
fn test_orphan_target_with_only_dead_target_caller_fires() {
    // `admin_purge` is a target pub fn that no adapter touches at the
    // boundary. Its only caller in the target layer is another target
    // fn (`_legacy_wrapper`) that is ITSELF unreachable from any
    // adapter — a dead island within the target layer.
    //
    // Before the fix: `has_target_layer_caller` returned true (because
    // `_legacy_wrapper` is a target-layer caller) and the orphan
    // branch was suppressed → no finding. False negative.
    //
    // After: the orphan branch only suppresses when the target is
    // transitively reachable from at least one adapter touchpoint.
    // Since neither admin_purge nor _legacy_wrapper is reachable
    // from any adapter, the orphan finding fires.
    let ws = build_workspace(&[
        (
            "src/application/admin.rs",
            r#"
            pub fn admin_purge() {}
            pub fn _legacy_wrapper() { admin_purge(); }
            "#,
        ),
        // No adapter touches admin_purge or _legacy_wrapper.
        (
            "src/cli/handlers.rs",
            r#"
            pub fn cmd_other() {}
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            pub fn handle_other() {}
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let names: Vec<String> = missing_pairs(&findings)
        .into_iter()
        .map(|(t, _)| t)
        .collect();
    assert!(
        names.iter().any(|n| n.ends_with("admin_purge")),
        "orphan target with only dead target-internal callers must fire, got {names:?}"
    );
}

#[test]
fn test_target_reached_transitively_via_target_chain_no_finding() {
    // Wired chain: cli → session.search (boundary touchpoint) →
    // record_operation (target-internal). record_operation has zero
    // adapter coverage but is reachable through session.search from
    // cli. Must NOT fire (it's not orphan; it's wired).
    let ws = build_workspace(&[
        (
            "src/application/middleware.rs",
            r#"
            pub fn record_operation() {}
            "#,
        ),
        (
            "src/application/session.rs",
            r#"
            use crate::application::middleware::record_operation;
            pub fn search() { record_operation(); }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::search;
            pub fn cmd_search() { search(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::session::search;
            pub fn handle_search() { search(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let names: Vec<String> = missing_pairs(&findings)
        .into_iter()
        .map(|(t, _)| t)
        .collect();
    assert!(
        !names.iter().any(|n| n.ends_with("record_operation")),
        "transitively-reached target must not fire, got {names:?}"
    );
}

#[test]
fn test_target_self_caller_only_still_fires_orphan() {
    // Self-call: `admin_purge` calls itself recursively. Before the
    // fix, has_target_layer_caller saw `admin_purge` as its own caller
    // (target layer), suppressed the orphan branch. Should fire.
    let ws = build_workspace(&[(
        "src/application/admin.rs",
        r#"
        pub fn admin_purge() { admin_purge(); }
        "#,
    )]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let names: Vec<String> = missing_pairs(&findings)
        .into_iter()
        .map(|(t, _)| t)
        .collect();
    assert!(
        names.iter().any(|n| n.ends_with("admin_purge")),
        "self-only-caller orphan must still fire, got {names:?}"
    );
}

// ── Boundary semantic (v1.2.1) ─────────────────────────────────

#[test]
fn test_post_boundary_helper_not_flagged_when_transitive_reach_asymmetric() {
    // The asymmetric setup: cli reaches `record_operation` transitively
    // (via search), mcp doesn't reach it at all (handle_admin → admin,
    // which doesn't touch record_operation). Under the OLD leaf-
    // reachability semantic, this would fire a Check B finding for
    // `record_operation` ("missing from mcp"). Under the new boundary
    // semantic, `record_operation` is application-internal plumbing
    // that no adapter touches at the boundary — not a parity concern.
    let ws = build_workspace(&[
        (
            "src/application/middleware.rs",
            r#"
            pub fn record_operation() {}
            "#,
        ),
        (
            "src/application/session.rs",
            r#"
            use crate::application::middleware::record_operation;
            pub fn search() { record_operation(); }
            pub fn admin() {}
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::search;
            pub fn cmd_search() { search(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::session::admin;
            pub fn handle_admin() { admin(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    // `search` is reached only by cli → mismatch finding.
    // `admin` is reached only by mcp → mismatch finding.
    // `record_operation` is post-boundary plumbing → MUST NOT appear.
    let names: Vec<String> = pairs.iter().map(|(t, _)| t.clone()).collect();
    assert!(
        !names.iter().any(|n| n.ends_with("record_operation")),
        "post-boundary helper should not appear in findings, got {pairs:?}"
    );
}

#[test]
fn test_internal_application_chain_no_findings() {
    // session.search → record_operation → impact_count: a chain of
    // internal application fns. Adapters touch only `search`. None of
    // `record_operation` / `impact_count` should produce findings.
    let ws = build_workspace(&[
        (
            "src/application/middleware.rs",
            r#"
            pub fn impact_count() -> u32 { 0 }
            pub fn record_operation() { impact_count(); }
            "#,
        ),
        (
            "src/application/session.rs",
            r#"
            use crate::application::middleware::record_operation;
            pub fn search() { record_operation(); }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::search;
            pub fn cmd_search() { search(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::session::search;
            pub fn handle_search() { search(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(
        missing_pairs(&findings).is_empty(),
        "deeper application chain should not fire findings, got {findings:?}"
    );
}

#[test]
fn test_capability_in_one_adapter_only_fires_for_that_target() {
    // cli reaches `admin_purge`; mcp doesn't. mcp reaches `search` too,
    // both adapters cover that one. Only `admin_purge` produces a
    // finding (mismatch case: present in cli, missing from mcp).
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub fn search() {}
            pub fn admin_purge() {}
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::{search, admin_purge};
            pub fn cmd_search() { search(); }
            pub fn cmd_admin() { admin_purge(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::session::search;
            pub fn handle_search() { search(); }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    assert_eq!(pairs.len(), 1, "got {findings:?}");
    assert!(
        pairs[0].0.ends_with("admin_purge"),
        "expected admin_purge finding, got {pairs:?}"
    );
    assert_eq!(pairs[0].1, vec!["mcp".to_string()]);
}

#[test]
fn test_impl_in_separate_file_matches_receiver_tracked_calls() {
    // Regression: `use crate::application::session::Session; impl Session
    // { pub fn search() }` in a different file from the type declaration.
    // Without alias-map-based canonicalisation of the impl self-type,
    // Check B's node for `search` would be
    // `crate::application::session_impls::Session::search` while the
    // caller's receiver-tracked canonical is
    // `crate::application::session::Session::search` — the two never
    // match and every adapter looks like it's missing.
    let ws = build_workspace(&[
        ("src/application/session.rs", "pub struct Session;"),
        (
            "src/application/session_impls.rs",
            r#"
            use crate::application::session::Session;
            impl Session {
                pub fn open() -> Self { Session }
                pub fn search(&self) {}
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() {
                let s = Session::open();
                s.search();
            }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn handle_search() {
                let s = Session::open();
                s.search();
            }
            "#,
        ),
    ]);
    let cp = make_config(3, &["cli", "mcp"], &[]);
    let findings = run_check_b(&ws, &four_layer(), &cp, &empty_cfg_test());
    assert!(
        missing_pairs(&findings).is_empty(),
        "cross-file impl via use should match receiver-tracked calls, got {findings:?}"
    );
}

// ── Trait-method anchor coverage ──────────────────────────────

fn ports_cp() -> CompiledCallParity {
    CompiledCallParity {
        adapters: vec!["cli".to_string(), "mcp".to_string()],
        target: "application".to_string(),
        call_depth: 3,
        exclude_targets: globset(&[]),
        transparent_wrappers: HashSet::new(),
        transparent_macros: HashSet::new(),
        promoted_attributes: HashSet::new(),
        single_touchpoint: crate::config::architecture::SingleTouchpointMode::default(),
    }
}

#[test]
fn check_b_silent_when_anchor_covered_by_all_adapters() {
    // Trait in `ports`, impl in `application` (target). Both CLI and
    // MCP dispatch via `dyn Handler.handle()` — anchor
    // `crate::ports::handler::Handler::handle` is in both adapters'
    // touchpoint sets. The anchor IS a target capability (its impl
    // lives in application), and BOTH adapters reach it → Check B
    // must be silent.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self); }",
        ),
        (
            "src/application/logging.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct LoggingHandler;
            impl Handler for LoggingHandler { fn handle(&self) {} }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::ports::handler::Handler;
            pub fn cmd_dispatch(h: &dyn Handler) { h.handle(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::ports::handler::Handler;
            pub fn mcp_dispatch(h: &dyn Handler) { h.handle(); }
            "#,
        ),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::ports::handler::Handler::handle";
    assert!(
        !pairs.iter().any(|(target, _)| target == anchor),
        "anchor covered by all adapters must not produce a finding, got {pairs:?}"
    );
}

#[test]
fn check_b_silent_for_concrete_impl_when_only_anchor_reached() {
    // Both adapters dispatch via `dyn Handler.handle()`. The walker
    // registers ONLY the anchor `Handler::handle` as touchpoint —
    // concrete impl methods like `LoggingHandler::handle` never enter
    // the touchpoint set via dispatch. Without F5's anchor-backed-
    // concrete skip, Check B would flag `LoggingHandler::handle` as
    // an orphan even though the trait-method anchor IS covered by
    // both adapters.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self); }",
        ),
        (
            "src/application/logging.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct LoggingHandler;
            impl Handler for LoggingHandler { fn handle(&self) {} }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::ports::handler::Handler;
            pub fn cmd_dispatch(h: &dyn Handler) { h.handle(); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::ports::handler::Handler;
            pub fn mcp_dispatch(h: &dyn Handler) { h.handle(); }
            "#,
        ),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let concrete = "crate::application::logging::LoggingHandler::handle";
    assert!(
        !pairs.iter().any(|(target, _)| target == concrete),
        "concrete impl-method must NOT be flagged as orphan when its anchor is covered; got {pairs:?}"
    );
}

#[test]
fn check_b_flags_inherent_method_even_when_same_name_inherited_default_exists() {
    // Canonical collision: the inherent method `impl AppHandler { fn
    // handle… }` and the inherited-default `impl Handler for
    // AppHandler {}` share the canonical `AppHandler::handle`. The
    // inherent method has a real body and is a normal target pub-fn
    // — Check B must surface a missing-adapter finding when no
    // adapter reaches it. It must NOT be silently treated as
    // "anchor-backed" via the empty trait impl.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self) {} }",
        ),
        (
            "src/application/logging.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct AppHandler;
            impl Handler for AppHandler {}
            impl AppHandler { pub fn handle(&self) {} }
            "#,
        ),
        ("src/cli/handlers.rs", "pub fn cmd_other() {}"),
        ("src/mcp/handlers.rs", "pub fn mcp_other() {}"),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let inherent = "crate::application::logging::AppHandler::handle";
    assert!(
        pairs.iter().any(|(target, _)| target == inherent),
        "inherent method `AppHandler::handle` must produce a missing-adapter finding; it must not be silently absorbed into the trait anchor; got {pairs:?}"
    );
}

#[test]
fn check_b_silent_anchor_when_adapters_call_inherited_default_concretely() {
    // Inherited-default impl: every adapter covers the capability via
    // the concrete form (UFCS or struct-method call). The edge-rewrite
    // post-pass folds those phantom edges onto the trait anchor, so
    // coverage hits the anchor for both adapters and the anchor pass
    // stays silent.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self) {} }",
        ),
        (
            "src/application/logging.rs",
            // Empty impl — inherits the trait default body.
            r#"
            use crate::ports::handler::Handler;
            pub struct AppHandler;
            impl Handler for AppHandler {}
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::logging::AppHandler;
            pub fn cmd_log() { AppHandler::handle(&AppHandler); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::logging::AppHandler;
            pub fn mcp_log() { AppHandler::handle(&AppHandler); }
            "#,
        ),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::ports::handler::Handler::handle";
    assert!(
        !pairs.iter().any(|(target, _)| target == anchor),
        "anchor must be silent when every adapter covers the capability via the inherited-default concrete form; got {pairs:?}"
    );
}

#[test]
fn check_b_anchor_finding_excluded_via_impl_path_glob() {
    // `exclude_targets = ["application::admin::*"]` matches the impl
    // path; the anchor finding for `ports::Handler::handle` must be
    // silenced via the anchor's backed impl_method_canonicals.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self); }",
        ),
        (
            "src/application/admin.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct AdminHandler;
            impl Handler for AdminHandler { fn handle(&self) {} }
            "#,
        ),
        ("src/cli/handlers.rs", "pub fn cmd_other() {}"),
        ("src/mcp/handlers.rs", "pub fn mcp_other() {}"),
    ]);
    let mut cp = ports_cp();
    cp.exclude_targets = globset(&["application::admin::*"]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &cp, &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::ports::handler::Handler::handle";
    assert!(
        !pairs.iter().any(|(target, _)| target == anchor),
        "anchor finding must be silenced when exclude_targets matches an impl_method_canonical (`application::admin::*` matches `application::admin::AdminHandler::handle`); got {pairs:?}"
    );
}

#[test]
fn check_b_silent_anchor_when_all_adapters_cover_via_direct_concrete() {
    // Every adapter calls the concrete impl directly; no dispatch
    // anywhere. The anchor pass must suppress the orphan finding via
    // the impl-method-canonical coverage check.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self); }",
        ),
        (
            "src/application/logging.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct LoggingHandler;
            impl Handler for LoggingHandler { fn handle(&self) {} }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::logging::LoggingHandler;
            pub fn cmd_log() { LoggingHandler::handle(&LoggingHandler); }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::logging::LoggingHandler;
            pub fn mcp_log() { LoggingHandler::handle(&LoggingHandler); }
            "#,
        ),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::ports::handler::Handler::handle";
    assert!(
        !pairs.iter().any(|(target, _)| target == anchor),
        "anchor must be silent when the capability is covered via direct concrete by every adapter; got {pairs:?}"
    );
}

#[test]
fn check_b_does_not_skip_concrete_when_an_adapter_calls_it_directly() {
    // Mixed-form drift: cli direct concrete, mcp dispatch. The
    // concrete pass must still run so the form-mismatch surfaces.
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self); }",
        ),
        (
            "src/application/logging.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct LoggingHandler;
            impl Handler for LoggingHandler { fn handle(&self) {} }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::logging::LoggingHandler;
            pub fn cmd_log() {
                LoggingHandler::handle(&LoggingHandler);
            }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::ports::handler::Handler;
            pub fn mcp_dispatch(h: &dyn Handler) { h.handle(); }
            "#,
        ),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let concrete = "crate::application::logging::LoggingHandler::handle";
    let concrete_finding = pairs.iter().find(|(t, _)| t == concrete);
    assert!(
        concrete_finding.is_some(),
        "concrete impl-method must NOT be silently skipped when at least one adapter (cli) calls it directly — drift between cli (direct) and mcp (dispatch) must surface; got {pairs:?}"
    );
    if let Some((_, missing)) = concrete_finding {
        assert!(
            missing.iter().any(|a| a == "mcp"),
            "concrete pass must report mcp as missing (it reaches via dispatch, not direct concrete); got {missing:?}"
        );
    }
}

#[test]
fn check_b_flags_anchor_orphan_when_no_adapter_reaches_it() {
    // Trait `Orphan` in ports with overriding impl in application.
    // No adapter dispatches through it. The anchor is a target
    // capability that no adapter wires up → Check B must flag it
    // as orphan/missing-from-all-adapters.
    let ws = build_workspace(&[
        (
            "src/ports/orphan.rs",
            "pub trait Orphan { fn handle(&self); }",
        ),
        (
            "src/application/orphan_impl.rs",
            r#"
            use crate::ports::orphan::Orphan;
            pub struct OrphanImpl;
            impl Orphan for OrphanImpl { fn handle(&self) {} }
            "#,
        ),
        // CLI and MCP exist but never dispatch via `dyn Orphan`.
        ("src/cli/handlers.rs", "pub fn cmd_other() {}"),
        ("src/mcp/handlers.rs", "pub fn mcp_other() {}"),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::ports::orphan::Orphan::handle";
    assert!(
        pairs.iter().any(|(target, _)| target == anchor),
        "anchor reached by NO adapter must be flagged as orphan, got {pairs:?}"
    );
}

#[test]
fn anchor_finding_carries_trait_method_source_line() {
    // Anchor findings must carry the trait method's real file + line
    // (1-based) — line=0 placeholders break suppression-window matching,
    // the orphan detector's window scan, and SARIF startLine validity.
    let ws = build_workspace(&[
        (
            // Lines: 1=blank, 2=trait header, 3=method decl
            "src/ports/orphan.rs",
            "\npub trait Orphan {\n    fn handle(&self);\n}\n",
        ),
        (
            "src/application/orphan_impl.rs",
            r#"
            use crate::ports::orphan::Orphan;
            pub struct OrphanImpl;
            impl Orphan for OrphanImpl { fn handle(&self) {} }
            "#,
        ),
        ("src/cli/handlers.rs", "pub fn cmd_other() {}"),
        ("src/mcp/handlers.rs", "pub fn mcp_other() {}"),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let anchor = "crate::ports::orphan::Orphan::handle";
    let hit = findings
        .iter()
        .find(|f| match &f.kind {
            ViolationKind::CallParityMissingAdapter { target_fn, .. } => target_fn == anchor,
            _ => false,
        })
        .unwrap_or_else(|| panic!("anchor orphan finding missing, got {findings:?}"));
    assert_eq!(
        hit.file, "src/ports/orphan.rs",
        "anchor finding must carry the trait method's source file, got {hit:?}"
    );
    assert_eq!(
        hit.line, 3,
        "anchor finding must carry the trait method's 1-based line number, got {hit:?}"
    );
    // F6.3 cross-check: anchor finding line is non-zero AND a
    // valid 1-based line number, matching SARIF startLine
    // requirements and what suppression-window matchers expect.
    assert!(
        hit.line >= 1,
        "anchor finding line must be 1-based (>=1), got {}",
        hit.line
    );
}

#[test]
fn check_b_anchor_only_target_surface_still_inspected() {
    // Target layer has NO concrete pub fns — only a default-body trait
    // declared there. The trait method is a target capability via the
    // unified rule. Even though in practice `pub_fns_by_layer["application"]`
    // is created (empty vec) by the collector's `or_default()`, the
    // target-anchor branch must still fire a missing-adapter finding.
    // Sister test below directly exercises the `None` branch via a
    // hand-stripped pub_fns_by_layer.
    let ws = build_workspace(&[
        (
            "src/application/cap.rs",
            "pub trait Cap { fn run(&self) {} }",
        ),
        ("src/cli/handlers.rs", "pub fn cmd_other() {}"),
        ("src/mcp/handlers.rs", "pub fn mcp_other() {}"),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::application::cap::Cap::run";
    assert!(
        pairs.iter().any(|(target, _)| target == anchor),
        "anchor in anchor-only target layer must still fire missing-adapter, got {pairs:?}"
    );
}

#[test]
fn check_b_anchor_reached_transitively_via_target_chain_no_finding() {
    // cli reaches a target fn that dispatches via `dyn Handler`; mcp
    // doesn't reach the anchor at all. The anchor must stay silent
    // (post-boundary plumbing wired via at least one adapter).
    let ws = build_workspace(&[
        (
            "src/ports/handler.rs",
            "pub trait Handler { fn handle(&self); }",
        ),
        (
            "src/application/wires.rs",
            r#"
            use crate::ports::handler::Handler;
            pub struct LoggingHandler;
            impl Handler for LoggingHandler { fn handle(&self) {} }
            pub fn dispatch(h: &dyn Handler) { h.handle(); }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::wires::{dispatch, LoggingHandler};
            pub fn cmd_run() { dispatch(&LoggingHandler); }
            "#,
        ),
        ("src/mcp/handlers.rs", "pub fn cmd_other() {}"),
    ]);
    let findings = run_check_b(&ws, &ports_app_cli_mcp(), &ports_cp(), &empty_cfg_test());
    let pairs = missing_pairs(&findings);
    let anchor = "crate::ports::handler::Handler::handle";
    assert!(
        !pairs.iter().any(|(target, _)| target == anchor),
        "anchor reachable transitively via an adapter-touched target fn must be silent (post-boundary plumbing rule), got {pairs:?}"
    );
}

#[test]
fn check_b_anchor_inspected_even_when_target_layer_absent_from_pub_fns_map() {
    // Strips the target entry from pub_fns_by_layer to exercise the
    // `None` branch of `get(target)`. Anchor enumeration must still
    // run.
    use super::support::borrowed_files;
    use crate::adapters::analyzers::architecture::call_parity_rule::build_handler_touchpoints;
    use crate::adapters::analyzers::architecture::call_parity_rule::check_b::check_missing_adapter;
    use crate::adapters::analyzers::architecture::call_parity_rule::pub_fns::{
        collect_pub_fns_by_layer, PubFnInputs,
    };
    use crate::adapters::analyzers::architecture::call_parity_rule::workspace_graph::build_call_graph;

    let ws = build_workspace(&[
        (
            "src/application/cap.rs",
            "pub trait Cap { fn run(&self) {} }",
        ),
        ("src/cli/handlers.rs", "pub fn cmd_other() {}"),
        ("src/mcp/handlers.rs", "pub fn mcp_other() {}"),
    ]);
    let layers = ports_app_cli_mcp();
    let cp = ports_cp();
    let cfg_test = empty_cfg_test();
    let borrowed = borrowed_files(&ws);
    let crate_root_modules = HashSet::new();
    let workspace_module_paths = HashSet::new();
    let workspace = crate::adapters::analyzers::architecture::call_parity_rule::local_symbols::WorkspaceLookup {
        cfg_test_files: &cfg_test,
        crate_root_modules: &crate_root_modules,
        workspace_module_paths: &workspace_module_paths,
    };
    let mut pub_fns = collect_pub_fns_by_layer(PubFnInputs {
        files: &borrowed,
        aliases_per_file: &ws.aliases_per_file,
        layers: &layers,
        transparent_wrappers: &cp.transparent_wrappers,
        promoted_attributes: &cp.promoted_attributes,
        workspace: &workspace,
    });
    let graph = build_call_graph(
        &borrowed,
        &ws.aliases_per_file,
        &layers,
        &cp.transparent_wrappers,
        &workspace,
    );
    let touchpoints = build_handler_touchpoints(&pub_fns, &graph, &cp);
    pub_fns.remove("application");
    assert!(
        !pub_fns.contains_key("application"),
        "test precondition: target layer key must be absent before invoking check_missing_adapter"
    );
    let findings = check_missing_adapter(&pub_fns, &graph, &touchpoints, &cp);
    let pairs = missing_pairs(&findings);
    let anchor = "crate::application::cap::Cap::run";
    assert!(
        pairs.iter().any(|(target, _)| target == anchor),
        "with target layer absent from pub_fns_by_layer, anchor enumeration must still run; got {pairs:?}"
    );
}

// ─────────────────────────────────────────────────────────────────────
// Cascade clearance — when an adapter reaches a generic dispatcher
// that resolves to a trait-anchor edge, downstream callees of the
// impl method must be cleared from missing-adapter findings via the
// forward BFS through target-internal edges.
// ─────────────────────────────────────────────────────────────────────

#[test]
fn check_b_cascade_clears_when_target_reached_via_generic_trait_dispatch() {
    // An adapter reaches a generic runner that dispatches via
    // `Q::execute(...)` to a trait impl. The impl body calls another
    // application helper. With the trait-anchor edge in place, the
    // helper must NOT show up as missing — the BFS from the boundary
    // touchpoints follows the anchor to the impl, then onwards.
    let ws = build_workspace(&[
        (
            "src/application/symbol.rs",
            r#"
            pub trait SymbolQuery {
                fn execute(&self);
            }
            pub struct DepsQuery;
            impl SymbolQuery for DepsQuery {
                fn execute(&self) {
                    collect_callees();
                }
            }
            pub fn collect_callees() {}
            "#,
        ),
        (
            "src/application/runner.rs",
            r#"
            use crate::application::symbol::SymbolQuery;

            pub fn run<Q: SymbolQuery>(q: Q) {
                Q::execute(&q);
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::runner::run;
            use crate::application::symbol::DepsQuery;

            pub fn cmd_deps() {
                run(DepsQuery);
            }
            "#,
        ),
        (
            "src/mcp/handlers.rs",
            r#"
            use crate::application::runner::run;
            use crate::application::symbol::DepsQuery;

            pub fn handle_deps() {
                run(DepsQuery);
            }
            "#,
        ),
    ]);
    let findings = run_check_b(
        &ws,
        &three_layer(),
        &cli_mcp_config_full(),
        &empty_cfg_test(),
    );

    let collect_canonical = "crate::application::symbol::collect_callees";
    let missing = missing_adapters_for(&findings, collect_canonical);

    assert!(
        missing.is_none(),
        "`collect_callees` flagged as not-reached even though it's \
         called by an impl method that an adapter reaches via the \
         generic runner.\n\
         missing adapters for collect_callees: {missing:?}\n\
         all findings: {:?}",
        findings
            .iter()
            .filter_map(|f| match &f.kind {
                ViolationKind::CallParityMissingAdapter { target_fn, .. } =>
                    Some(target_fn.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>(),
    );
}

// ─────────────────────────────────────────────────────────────────────
// Promoted-attribute support — a private attributed fn (e.g.
// `#[tool] async fn ...`) inside an adapter impl block must be
// treated as a handler entry point when configured via
// `promoted_attributes`, so its body's calls count toward coverage.
// ─────────────────────────────────────────────────────────────────────

#[test]
fn check_b_promoted_attribute_lifts_private_fn_onto_handler_surface() {
    // Pattern: `async fn search` without a `pub` modifier inside an
    // inherent impl block — a proc-macro is expected to generate the
    // public dispatch wrapper at expansion time. Without
    // `promoted_attributes` configured, the private fn is filtered
    // out of the adapter's handler set and the call is invisible.
    // With `promoted_attributes = ["tool"]`, the fn is promoted onto
    // the surface and its body's calls satisfy coverage.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            pub struct MyErr;
            impl Session {
                pub fn open(_p: &str) -> Result<Self, MyErr> { todo!() }
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() {
                let _ = Session::open("/p");
            }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            use crate::application::session::{Session, MyErr};

            #[derive(Clone)]
            pub struct Server {
                pub(super) project_root: std::path::PathBuf,
            }

            pub struct Parameters<T>(pub T);
            pub struct SearchParams;
            pub struct CallToolResult;

            #[tool_router(vis = "pub(super)")]
            impl Server {
                #[tool(description = "search")]
                async fn search(
                    &self,
                    _params: Parameters<SearchParams>,
                ) -> Result<CallToolResult, MyErr> {
                    let _session = Session::open("/p");
                    todo!()
                }
            }
            "#,
        ),
    ]);
    let mut cp = cli_mcp_config_full();
    cp.promoted_attributes.insert("tool".to_string());
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());

    let open = "crate::application::session::Session::open";
    let missing = missing_adapters_for(&findings, open);

    assert!(
        missing
            .as_ref()
            .is_none_or(|m| !m.contains(&"mcp".to_string())),
        "with promoted_attributes=[\"tool\"], Session::open is still \
         flagged as not reached from mcp. The promotion in \
         pub_fns.rs::visit_impl_item_fn isn't picking up the #[tool] \
         attribute on the private async fn.\n\
         missing adapters for Session::open: {missing:?}\n\
         all findings: {:?}",
        findings
            .iter()
            .filter_map(|f| match &f.kind {
                ViolationKind::CallParityMissingAdapter { target_fn, .. } =>
                    Some(target_fn.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>(),
    );
}

// ─────────────────────────────────────────────────────────────────────
// Hint surfacing — when a missing adapter has a private fn carrying
// a custom attribute (`#[tool]`, etc.) that would resolve the finding
// after promotion, the finding's `hint` field must name it.
// Negative cases ensure spurious suggestions don't fire.
// ─────────────────────────────────────────────────────────────────────

#[test]
fn check_b_hint_suggests_private_attributed_fn_when_it_reaches_target() {
    // Positive case: missing adapter mcp has a private `#[tool]` fn
    // that transitively reaches the unreached target. Hint must name
    // file + fn + attribute so the author can immediately add
    // `promoted_attributes = ["tool"]`.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            pub struct MyErr;
            impl Session {
                pub fn open(_p: &str) -> Result<Self, MyErr> { todo!() }
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() {
                let _ = Session::open("/p");
            }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            use crate::application::session::{Session, MyErr};
            pub struct Server;
            impl Server {
                #[tool(description = "search")]
                async fn search(&self) -> Result<(), MyErr> {
                    let _ = Session::open("/p");
                    Ok(())
                }
            }
            "#,
        ),
    ]);
    let cp = cli_mcp_config_full();
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());

    let open = "crate::application::session::Session::open";
    let hint = hint_for(&findings, open).expect("expected hint on missing-adapter finding");
    assert!(
        hint.contains("search") && hint.contains("tool") && hint.contains("mcp"),
        "hint must name candidate fn `search`, its attribute `tool`, and \
         adapter `mcp`. Got:\n{hint}"
    );
    assert!(
        hint.contains("promoted_attributes"),
        "hint must point the author at the `promoted_attributes` config knob. Got:\n{hint}"
    );
}

#[test]
fn check_b_no_hint_when_no_private_attributed_fn_in_missing_adapter() {
    // Missing adapter mcp has NO private fn carrying any attribute
    // that reaches the target. Finding still fires but hint is None.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session {
                pub fn open(_p: &str) {}
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() { Session::open("/p"); }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            pub fn handle_other() {}
            "#,
        ),
    ]);
    let cp = cli_mcp_config_full();
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());

    let open = "crate::application::session::Session::open";
    let missing =
        missing_adapters_for(&findings, open).expect("expected open to be missing from mcp");
    assert!(missing.contains(&"mcp".to_string()));
    assert!(
        hint_for(&findings, open).is_none(),
        "no private attributed candidate in mcp → no hint expected"
    );
}

#[test]
fn check_b_no_hint_when_only_stdlib_attribute_on_candidate() {
    // Private fn carries only stdlib attributes (`#[allow]`,
    // `#[deprecated]`, etc.) — those are noise, not framework-handler
    // markers, so they must not trigger the hint.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session {
                pub fn open(_p: &str) {}
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() { Session::open("/p"); }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            use crate::application::session::Session;
            pub struct Server;
            impl Server {
                #[allow(dead_code)]
                fn search_internal(&self) {
                    Session::open("/p");
                }
            }
            "#,
        ),
    ]);
    let cp = cli_mcp_config_full();
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());

    let open = "crate::application::session::Session::open";
    assert!(
        hint_for(&findings, open).is_none(),
        "stdlib attribute (#[allow]) must not qualify the fn as a promotion candidate"
    );
}

#[test]
fn check_b_no_hint_when_candidate_body_does_not_reach_target() {
    // Private + attributed fn exists in the missing adapter but its
    // body doesn't reach the unreached target. Promoting it wouldn't
    // resolve the finding, so no hint.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session {
                pub fn open(_p: &str) {}
                pub fn other(&self) {}
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_search() { Session::open("/p"); }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            pub struct Server;
            impl Server {
                #[tool(description = "unrelated")]
                async fn unrelated(&self) {
                    // Doesn't call Session::open — calls nothing.
                }
            }
            "#,
        ),
    ]);
    let cp = cli_mcp_config_full();
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());

    let open = "crate::application::session::Session::open";
    assert!(
        hint_for(&findings, open).is_none(),
        "the #[tool] fn `unrelated` doesn't reach Session::open → no hint expected"
    );
}

#[test]
fn check_b_hint_excludes_adapters_already_covering_target() {
    // cli reaches target, mcp doesn't. The hint must mention only
    // mcp's candidate (if any), never cli's — cli already covers the
    // target, so promoting a cli candidate is irrelevant.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session {
                pub fn stats(&self) {}
            }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub struct CliCmds;
            impl CliCmds {
                #[tool(description = "diagnostic")]
                fn diagnostic_stats(s: &Session) { s.stats(); }
            }
            pub fn cmd_stats(s: &Session) { s.stats(); }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            pub fn handle_other() {}
            "#,
        ),
    ]);
    let cp = cli_mcp_config_full();
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());

    let stats = "crate::application::session::Session::stats";
    let missing = missing_adapters_for(&findings, stats).expect("stats must be missing from mcp");
    assert_eq!(missing, vec!["mcp".to_string()]);
    // cli has a candidate but cli isn't a missing adapter → no hint.
    assert!(
        hint_for(&findings, stats).is_none(),
        "candidate in cli (already covering) must not surface in the hint when only mcp is missing"
    );
}

#[test]
fn check_b_no_hint_when_candidate_path_exceeds_call_depth() {
    // A private #[tool] fn whose body chain reaches the target only
    // via depth > call_depth must NOT produce a hint — promotion
    // wouldn't help because compute_touchpoints stops at call_depth.
    //
    // call_depth = 1: handler (depth 0) → first callee (depth 1,
    // boundary). With this fixture, `tool_a` reaches `Session::open`
    // only via 2 hops, so even after promotion the walker stops at
    // `helper1` and never sees `open`.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session { pub fn open() {} }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cmd_open() { Session::open(); }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            use crate::application::session::Session;
            pub struct Server;
            impl Server {
                #[tool(description = "deep")]
                fn tool_a(&self) { helper1(); }
            }
            fn helper1() { Session::open(); }
            "#,
        ),
    ]);
    let mut cp = cli_mcp_config_full();
    cp.call_depth = 1;
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());
    let open = "crate::application::session::Session::open";
    assert!(
        hint_for(&findings, open).is_none(),
        "tool_a → helper1 → open is depth 2, exceeds call_depth=1 — \
         walker would not accept tool_a as touchpoint after promotion, \
         so no hint expected. Got: {:?}",
        hint_for(&findings, open),
    );
}

#[test]
fn check_b_no_hint_when_candidate_reaches_target_only_via_peer_adapter() {
    // A candidate in adapter A whose only path to the target goes
    // through adapter B's code must NOT produce a hint — touchpoint
    // computation from A stops at peer-adapter boundaries, so
    // promotion wouldn't add the target to A's coverage.
    let ws = build_workspace(&[
        (
            "src/application/session.rs",
            r#"
            pub struct Session;
            impl Session { pub fn open() {} }
            "#,
        ),
        (
            "src/cli/handlers.rs",
            r#"
            use crate::application::session::Session;
            pub fn cli_helper() { Session::open(); }
            pub fn cmd_open() { Session::open(); }
            "#,
        ),
        (
            "src/mcp/server.rs",
            r#"
            pub struct Server;
            impl Server {
                #[tool(description = "via peer")]
                fn tool_a(&self) { crate::cli::handlers::cli_helper(); }
            }
            "#,
        ),
    ]);
    let cp = cli_mcp_config_full();
    let findings = run_check_b(&ws, &three_layer(), &cp, &empty_cfg_test());
    let open = "crate::application::session::Session::open";
    assert!(
        hint_for(&findings, open).is_none(),
        "tool_a reaches open only via cli (peer adapter from mcp) — \
         walker would not traverse past cli boundary after promotion, \
         so no hint expected. Got: {:?}",
        hint_for(&findings, open),
    );
}