rustqual 1.2.3

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
//! 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, empty_cfg_test, four_layer, globset, ports_app_cli_mcp, run_check_b,
};
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(),
    }
}

/// 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 mut pub_fns = collect_pub_fns_by_layer(PubFnInputs {
        files: &borrowed,
        aliases_per_file: &ws.aliases_per_file,
        layers: &layers,
        cfg_test_files: &cfg_test,
        transparent_wrappers: &cp.transparent_wrappers,
        promoted_attributes: &cp.promoted_attributes,
    });
    let graph = build_call_graph(
        &borrowed,
        &ws.aliases_per_file,
        &cfg_test,
        &layers,
        &cp.transparent_wrappers,
    );
    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:?}"
    );
}