guibiao 0.9.0

圭表 (Guibiao) — Tianheng's dependency-light static observation core (derived from modou). Declare crate, module, and dependency-source boundaries in Rust — dependencies by name, module imports, and each dependency's declared source kind (git/registry/path) for manifest hygiene — observed from cargo metadata and source use-scans, reacted in CI. No AST: the syn-free gnomon of the family.
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
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
use super::helpers::*;
// --- inline-symbol-path confinement (`must_not_call_inline`) ----------------------------

pub(super) fn confine_core_clock() -> ModuleBoundary {
    ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_call_inline("std::time")
        .because("core reads no wall clock — time is injected, not read")
}

/// A read verb outside the declared set is not observed — the bound the adopter owns by narrowing.
///
/// Kept for the CONTRACT rather than for a change: `inline-symbol-path-confinement` declares that a
/// boundary narrowed with `.ending_with([…])` does not react to a verb outside that set, and nothing pinned
/// it. Measured before the assertion was written, with the declared verb beside it as the control, so the
/// empty result is about the narrowing rather than about a fixture that reacts to nothing.
#[test]
pub(super) fn inline_a_verb_outside_the_declared_set_is_a_bound() {
    let narrowed = || {
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(["now"])
            .because("core reads no wall clock — time is injected, not read")
    };

    let (result, violations) = run_module_check(
        "inline-verb-outside",
        &[
            ("lib.rs", "pub mod clock;\npub mod core;\n"),
            (
                "clock.rs",
                "pub fn now() -> u64 { 0 }\npub fn current() -> u64 { 0 }\n",
            ),
            (
                "core.rs",
                "fn stamp() { let _ = crate::clock::current(); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("crate::clock")
            .ending_with(["now"])
            .because("the clock is injected"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a verb outside the declared set is a bound the adopter owns: {violations:?}"
    );

    let (result, violations) = run_module_check(
        "inline-verb-declared",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn stamp() { let _ = std::time::SystemTime::now(); }\n",
            ),
        ],
        narrowed(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "the declared verb must react: {violations:?}"
    );
}

/// A foreign crate's re-export of the confined path is NOT observed — the stated bound, with its
/// control beside it so the assertion is discriminating rather than vacuous.
///
/// Kept for the CONTRACT rather than for a change: `inline-symbol-path-confinement` declares this bound
/// ("foreign AST is not scanned") and nothing pinned it, so a regression that started following a foreign
/// re-export — or a rewording that quietly widened the claim — had no reaction to trip. The control
/// direction is what makes the empty case mean something: the same call written through the confined
/// prefix reacts in the same fixture shape.
#[test]
pub(super) fn inline_foreign_reexport_of_the_confined_path_is_a_bound() {
    // The bound: reached through the foreign crate's own path, with that crate declared.
    let (result, violations) = run_module_check_with_deps(
        "inline-foreign-reexport",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn stamp() { let _ = shim::SystemTime::now(); }\n",
            ),
        ],
        &[("shim", None)],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a foreign re-export of the confined path is a stated bound, not a reaction: {violations:?}"
    );

    // The control: the identical call written through the confined prefix reacts, so the empty result
    // above is about the foreign path rather than about the fixture failing to be observed at all.
    let (result, violations) = run_module_check_with_deps(
        "inline-foreign-reexport-control",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn stamp() { let _ = std::time::SystemTime::now(); }\n",
            ),
        ],
        &[("shim", None)],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "control must react: {violations:?}");
}

/// A `#[path]`-remapped child of the confined module is observed, in both attribute forms.
///
/// Kept for the CONTRACT rather than for a change: the behaviour is already correct, and this pins it
/// so `intent/external-crate-confinement.md` cannot drift away from it again. It used to be claimed as an inherited scanner
/// bound — "the system does not claim to observe it" — which stopped being true when the scanner began
/// following an unconditional remap (0.2.2) and union-scanning a `cfg_attr`-wrapped one (0.3.x); the
/// prose outlived the behaviour on both counts, in the intent and in the typed bounds.
#[test]
pub(super) fn inline_path_remapped_child_is_observed() {
    for (label, declaration) in [
        ("direct", "#[path = \"elsewhere.rs\"]\npub mod inner;\n"),
        (
            "cfg_attr",
            "#[cfg_attr(unix, path = \"elsewhere.rs\")]\npub mod inner;\n",
        ),
    ] {
        let (result, violations) = run_module_check(
            &format!("inline-remap-{label}"),
            &[
                ("lib.rs", "pub mod core;\n"),
                ("core.rs", declaration),
                (
                    "elsewhere.rs",
                    "fn stamp() { let _ = std::time::Instant::now(); }\n",
                ),
            ],
            confine_core_clock(),
        );
        assert!(result.is_ok(), "{label}: {result:?}");
        assert_eq!(violations.len(), 1, "{label}: {violations:?}");
        assert_eq!(violations[0].target(), "std::time", "{label}");
        assert!(
            violations[0].finding.contains("crate::core::inner"),
            "{label}: the finding must name the remapped module, not the declaring file: {:?}",
            violations[0].finding
        );
    }
}

#[test]
pub(super) fn inline_default_reacts_on_an_associated_fn_call() {
    let (result, violations) = run_module_check(
        "inline-call",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn stamp() { let _ = std::time::SystemTime::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target(), "std::time");
    assert!(
        violations[0].finding.contains("std::time::SystemTime::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_default_passes_a_type_annotation() {
    let (result, violations) = run_module_check(
        "inline-annot",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn handle(now: std::time::Instant) { let _ = now; }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a type annotation is not a call: {violations:?}"
    );
}

#[test]
pub(super) fn inline_default_passes_a_constant() {
    let (result, violations) = run_module_check(
        "inline-const",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = std::time::SystemTime::UNIX_EPOCH; }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a constant read is not a call: {violations:?}"
    );
}

#[test]
pub(super) fn inline_resolves_a_rename() {
    let (result, violations) = run_module_check(
        "inline-rename",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "use std::time::SystemTime as SysT;\nfn f() { let _ = SysT::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a renamed alias resolves: {violations:?}"
    );
    assert!(
        violations[0].finding.contains("std::time::SystemTime::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_resolves_a_self_prefixed_group_alias() {
    // A use-group member whose name merely *starts with* the substring "self" (`self_utc`) is a
    // legal import, not the `self` leaf. An over-broad `starts_with("self")` dropped it, so the
    // alias was unresolved and a confined inline call through it silently passed — a false negative.
    let (result, violations) = run_module_check(
        "inline-self-prefixed-group",
        &[
            ("lib.rs", "pub mod clock;\npub mod core;\n"),
            (
                "clock.rs",
                "pub mod self_utc {\n    pub fn now() -> u8 { 0 }\n}\npub struct Duration;\n",
            ),
            (
                "core.rs",
                "#[allow(unused_imports)]\nuse crate::clock::{self_utc as clk, Duration};\nfn f() { let _ = clk::now(); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("crate::clock")
            .because("the clock is injected"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a self-prefixed group alias resolves and reacts: {violations:?}"
    );
    assert!(
        violations[0]
            .finding
            .contains("crate::clock::self_utc::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_resolves_a_bare_path() {
    let (result, violations) = run_module_check(
        "inline-bare",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "use std::time;\nfn f() { let _ = time::Instant::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "a bare path resolves: {violations:?}");
    assert!(
        violations[0].finding.contains("std::time::Instant::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_resolves_a_type_alias() {
    let (result, violations) = run_module_check(
        "inline-typealias",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "type Clock = std::time::SystemTime;\nfn f() { let _ = Clock::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "a type alias resolves: {violations:?}");
}

#[test]
pub(super) fn inline_resolves_a_multi_hop_type_alias() {
    let (result, violations) = run_module_check(
        "inline-multihop",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "type A = std::time::SystemTime;\ntype B = A;\nfn f() { let _ = B::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a multi-hop type alias chases to a fixpoint: {violations:?}"
    );
}

#[test]
pub(super) fn inline_resolves_a_type_alias_past_a_defaulted_generic_param() {
    // The generic parameter list carries its own `=` (`Tz = LocalTz`); it must not be mistaken for
    // the alias `=`, or the alias resolves to the default (`LocalTz`) instead of its real target
    // (`std::marker::PhantomData`) — a silent miss of the confined path (a false negative).
    let (result, violations) = run_module_check(
        "inline-defaulted-generic-alias",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "pub struct LocalTz;\ntype Clock<Tz = LocalTz> = std::marker::PhantomData<Tz>;\nfn f() { let _: Clock = Clock::default(); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::marker")
            .because("no markers are made inline"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "the alias resolves past the defaulted generic param to its real target: {violations:?}"
    );
}

#[test]
pub(super) fn inline_resolves_a_cross_module_local_reexport() {
    let (result, violations) = run_module_check(
        "inline-reexport",
        &[
            ("lib.rs", "pub mod core;\npub mod support;\n"),
            ("support.rs", "pub use std::time::SystemTime;\n"),
            (
                "core.rs",
                "use crate::support::SystemTime;\nfn f() { let _ = SystemTime::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a cross-module local re-export resolves: {violations:?}"
    );
}

#[test]
pub(super) fn inline_does_not_match_an_unresolved_same_named_local() {
    let (result, violations) = run_module_check(
        "inline-local",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "struct Instant;\nimpl Instant { fn now() {} }\nfn f() { Instant::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a same-named local is not matched by leaf: {violations:?}"
    );
}

#[test]
pub(super) fn inline_glob_of_the_prefix_reacts() {
    let (result, violations) = run_module_check(
        "inline-glob",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "use std::time::*;\n"),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a glob of the prefix reacts fail-closed: {violations:?}"
    );
    assert!(violations[0].finding.contains("glob"), "{violations:?}");
}

#[test]
pub(super) fn inline_glob_above_the_prefix_reacts() {
    let (result, violations) = run_module_check(
        "inline-glob-above",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "use std::*;\nfn f() { let _ = time::Instant::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.iter().any(|v| v.finding.contains("glob")),
        "an ancestor glob reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_glob_of_a_local_reexporting_module_reacts() {
    let (result, violations) = run_module_check(
        "inline-glob-local",
        &[
            ("lib.rs", "pub mod core;\npub mod support;\n"),
            ("support.rs", "pub use std::time::SystemTime;\n"),
            ("core.rs", "use crate::support::*;\n"),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a glob of a local re-exporting module reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_glob_of_a_module_that_itself_globs_the_prefix_reacts() {
    let (result, violations) = run_module_check(
        "inline-glob-recursive",
        &[
            ("lib.rs", "pub mod core;\npub mod support;\n"),
            ("support.rs", "pub use std::time::*;\n"),
            ("core.rs", "use crate::support::*;\n"),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "recursive glob hazard reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_narrowing_drops_a_benign_constructor_and_keeps_the_read() {
    let (result, violations) = run_module_check(
        "inline-narrow",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = std::time::Instant::now(); let _ = std::time::Duration::from_secs(5); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(["now"])
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "only the now-read reacts under narrowing: {violations:?}"
    );
    assert!(
        violations[0].finding.contains("Instant::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_narrowing_does_not_suppress_a_glob() {
    let (result, violations) = run_module_check(
        "inline-narrow-glob",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "use std::time::*;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(["now"])
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a glob still reacts under narrowing: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_flags_a_type_annotation() {
    let (result, violations) = run_module_check(
        "inline-strict",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn handle(now: std::time::Instant) { let _ = now; }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .strict_prefix_only()
            .because("core may not name std::time at all"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "strict flags a mention: {violations:?}"
    );
}

#[test]
pub(super) fn inline_value_capture_is_a_bound_under_the_default() {
    let (result, violations) = run_module_check(
        "inline-valuecap",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let g = std::time::SystemTime::now; let _ = g; }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "value-position capture is a stated bound under the default: {violations:?}"
    );
}

#[test]
pub(super) fn inline_scans_a_macro_body() {
    let (result, violations) = run_module_check(
        "inline-macro",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "macro_rules! some_macro { ($($t:tt)*) => { $($t)* }; }\nfn f() { some_macro! { let _ = std::time::Instant::now(); } }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a read inside a macro body is scanned, not skipped: {violations:?}"
    );
}

#[test]
pub(super) fn inline_empty_prefix_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "inline-empty",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("")
            .because("bad"),
    );
    assert_eq!(
        result.unwrap_err(),
        inline_empty_prefix_error("x", "must_not_call_inline")
    );
}

/// A misdeclaration the boundary alone decides is refused before any root is walked, so a module the walk cannot
/// back stands behind it rather than in front of the line the operator must change.
#[test]
pub(super) fn a_misdeclared_inline_confinement_is_refused_before_the_walk() {
    let files = &[
        ("lib.rs", "pub mod core;\npub mod clock;\nmod ghost;\n"),
        ("core.rs", "// clean\n"),
        ("clock.rs", "pub fn now() {}\n"),
    ];
    let cases: [(ModuleBoundary, String); 5] = [
        (
            ModuleBoundary::in_crate("x")
                .module("crate::core")
                .must_not_call_inline("")
                .because("bad"),
            inline_empty_prefix_error("x", "must_not_call_inline"),
        ),
        (
            ModuleBoundary::in_crate("x")
                .module("crate")
                .confine_inline_call("crate::clock")
                .because("bad"),
            crate::errors::confine_inline_call_on_crate_error("x"),
        ),
        (
            ModuleBoundary::in_crate("x")
                .module("crate::clock")
                .confine_inline_call("crate::clock")
                .depth(crate::ScanDepth::Shallow)
                .because("bad"),
            crate::errors::confine_inline_call_shallow_error("x"),
        ),
        (
            ModuleBoundary::in_crate("x")
                .module("crate::core")
                .must_not_call_inline("crate::clock")
                .ending_with(["now"])
                .strict_prefix_only()
                .because("bad"),
            inline_narrow_and_strict_error("x", "must_not_call_inline"),
        ),
        (
            ModuleBoundary::in_crate("x")
                .module("crate::core")
                .must_not_call_inline("crate::clock")
                .ending_with(Vec::<String>::new())
                .because("bad"),
            crate::errors::inline_empty_verbs_error("x", "must_not_call_inline"),
        ),
    ];
    for (index, (boundary, expected)) in cases.into_iter().enumerate() {
        let (result, _) = run_module_check(&format!("inline-misdeclared-{index}"), files, boundary);
        assert_eq!(result.unwrap_err(), expected, "case {index}");
    }
}

#[test]
pub(super) fn inline_narrow_and_strict_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "inline-combo",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(["now"])
            .strict_prefix_only()
            .because("contradiction"),
    );
    assert_eq!(
        result.unwrap_err(),
        inline_narrow_and_strict_error("x", "must_not_call_inline")
    );
}

#[test]
pub(super) fn inline_valid_zero_match_is_clean() {
    let (result, violations) = run_module_check(
        "inline-clean",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "fn f() { let _ = std::cmp::max(1, 2); }\n"),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a subtree with no std::time call is clean: {violations:?}"
    );
}

// --- inline-symbol-path: strict-external opt-in (`.strict_external()`) -------------------

/// A strict-external confinement on `chrono::Utc`, with `chrono` declared as a dependency. `name`
/// keys a per-test temp dir (must be unique, since tests run in parallel).
pub(super) fn confine_chrono_strict(
    name: &str,
    files: &[(&str, &str)],
) -> (Result<(), String>, Vec<Violation>) {
    run_module_check_with_deps(
        name,
        files,
        &[("chrono", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .strict_external()
            .because("core reads no wall clock — time is injected"),
    )
}

#[test]
pub(super) fn inline_strict_external_reacts_on_a_fully_qualified_external_call() {
    // 4.1 Guard (FN close): a fully-qualified, un-`use`d `chrono::Utc::now()` REACTS under the flag.
    let (result, violations) = confine_chrono_strict(
        "inline-strict-ext-fq",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "fn stamp() { let _ = chrono::Utc::now(); }\n"),
        ],
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target(), "chrono::Utc");
    assert!(
        violations[0].finding.contains("chrono::Utc::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_absent_fully_qualified_call_is_a_bound() {
    // 4.2 Default unchanged: the SAME call without the flag does NOT react (stated bound).
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-default",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "fn stamp() { let _ = chrono::Utc::now(); }\n"),
        ],
        &[("chrono", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a fully-qualified external call is a stated bound under the default: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_deep_local_module_stays_clean() {
    // 4.3 FP safety — a DEEP local module (non-crate-root) named like the dependency wins by local
    // precedence: the module's scope declares it, at depth, not only at the crate root.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-deepmod",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "pub mod time;\nfn f() { let _ = time::format(); }\n",
            ),
            ("core/time.rs", "pub fn format() {}\n"),
        ],
        &[("time", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("time")
            .strict_external()
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a deep local module named like a dep stays local: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_local_fn_definition_stays_clean() {
    // 4.4 FP safety — a local `fn` named like the dependency wins by local precedence: the module's
    // scope declares it.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-localfn",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn rand() -> u32 { 4 }\nfn f() { let _ = rand(); }\n",
            ),
        ],
        &[("rand", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("rand")
            .strict_external()
            .because("core is deterministic"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a local fn shadowing a dep name stays local: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_local_alias_stays_clean() {
    // 4.5 FP safety — a local `use crate::clock as time;` alias resolves through its `use` binding,
    // which the scope lookup reads before any dependency match, and stays clean.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-alias",
        &[
            ("lib.rs", "pub mod core;\npub mod clock;\n"),
            ("clock.rs", "pub fn read() {}\n"),
            (
                "core.rs",
                "use crate::clock as time;\nfn f() { let _ = time::read(); }\n",
            ),
        ],
        &[("time", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("time")
            .strict_external()
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a local alias shadowing a dep name resolves through its binding: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_glob_reacts_and_default_glob_does_not() {
    // 4.6 An external-crate glob `use chrono::*;` reacts under the flag (an external glob is an
    // ancestor of the confined prefix); the same glob under the default does NOT react.
    let files = &[
        ("lib.rs", "pub mod core;\n"),
        ("core.rs", "use chrono::*;\n"),
    ];
    let (result, violations) = confine_chrono_strict("inline-strict-ext-glob", files);
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "external glob reacts: {violations:?}");
    assert!(violations[0].finding.contains("glob"), "{violations:?}");

    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-glob-default",
        files,
        &[("chrono", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "the same glob under the default names nothing and does not react: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_composes_with_narrowing() {
    // 4.7 `.strict_external().ending_with(["now"])` reacts on `now()` and not on `today()`.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-narrow",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = chrono::Utc::now(); let _ = chrono::Utc::today(); }\n",
            ),
        ],
        &[("chrono", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .strict_external()
            .ending_with(["now"])
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "only the now-read reacts under narrowing: {violations:?}"
    );
    assert!(
        violations[0].finding.contains("chrono::Utc::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_adds_nothing_to_paths_that_already_react() {
    // 4.9 A `use chrono::Utc; Utc::now()` reacts WITHOUT the flag; and a cross-module
    // `pub use chrono::Utc;` chased to `Utc::now()` reacts WITHOUT the flag — the flag adds nothing.
    let files: &[(&str, &str)] = &[
        ("lib.rs", "pub mod core;\npub mod support;\n"),
        ("support.rs", "pub use chrono::Utc;\n"),
        (
            "core.rs",
            "use chrono::Utc;\nuse crate::support::Utc as SupUtc;\nfn f() { let _ = Utc::now(); let _ = SupUtc::now(); }\n",
        ),
    ];
    // Without the flag.
    let (result, plain) = run_module_check_with_deps(
        "inline-strict-ext-already-default",
        files,
        &[("chrono", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        plain.len(),
        1,
        "the used import + chased re-export already react under the default: {plain:?}"
    );
    // With the flag — same finding count (adds nothing, no over-reach, no double count).
    let (result, flagged) = run_module_check_with_deps(
        "inline-strict-ext-already-flag",
        files,
        &[("chrono", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("chrono::Utc")
            .strict_external()
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        flagged.len(),
        plain.len(),
        "the flag adds nothing to paths that already react: {flagged:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_preserves_identity_no_baseline_churn() {
    // 4.10 Baseline-churn guard: a sysroot `std::time::…::now()` finding must have byte-identical
    // (target, rule, finding) whether or not `.strict_external()` is added — so a baselined finding
    // survives the flag (identity parity, task 1.3). Locks target/rule-key/fact.
    let files: &[(&str, &str)] = &[
        ("lib.rs", "pub mod core;\n"),
        (
            "core.rs",
            "fn f() { let _ = std::time::SystemTime::now(); }\n",
        ),
    ];
    let (r1, plain) = run_module_check(
        "inline-identity-default",
        files,
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .because("core reads no wall clock"),
    );
    let (r2, flagged) = run_module_check_with_deps(
        "inline-identity-flag",
        files,
        &[],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .strict_external()
            .because("core reads no wall clock"),
    );
    assert!(r1.is_ok() && r2.is_ok(), "{r1:?} {r2:?}");
    assert_eq!(plain.len(), 1, "{plain:?}");
    assert_eq!(flagged.len(), 1, "{flagged:?}");
    assert_eq!(plain[0].target(), flagged[0].target(), "target parity");
    assert_eq!(plain[0].rule, flagged[0].rule, "rule (label) parity");
    assert_eq!(plain[0].finding, flagged[0].finding, "finding parity");
    assert_eq!(
        plain[0].rule, "inline symbol path confined to module",
        "the presentation label is unchanged by the flag"
    );
}

#[test]
pub(super) fn inline_strict_external_runs_the_exit_2_checks() {
    // 4.11 The new variant must still run the exit-2 constitution checks, never silently skip them.
    // Contradictory triple → narrow-and-strict error.
    let (contradiction, _) = run_module_check_with_deps(
        "inline-strict-ext-contradiction",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
        &[("std", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(["now"])
            .strict_prefix_only()
            .strict_external()
            .because("contradiction"),
    );
    assert_eq!(
        contradiction.unwrap_err(),
        inline_narrow_and_strict_error("x", "must_not_call_inline")
    );
    // Empty prefix → empty-prefix error.
    let (empty, _) = run_module_check_with_deps(
        "inline-strict-ext-empty",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
        &[],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("")
            .strict_external()
            .because("bad"),
    );
    assert_eq!(
        empty.unwrap_err(),
        inline_empty_prefix_error("x", "must_not_call_inline")
    );
}

#[test]
pub(super) fn inline_strict_external_cross_module_local_item_does_not_mask() {
    // The cardinal false negative: the item-definition set MUST be
    // module-qualified. A `fn rand` in `crate::helpers` must NOT suppress a real external
    // `rand::random()` call in the governed `crate::core` (a different module). Pre-fix, the set was
    // crate-flat and this call was silently passed (FN); this guard reacts.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-xmod",
        &[
            ("lib.rs", "pub mod core;\npub mod helpers;\n"),
            ("helpers.rs", "pub fn rand() -> u32 { 4 }\n"),
            ("core.rs", "fn f() { let _ = rand::random(); }\n"),
        ],
        &[("rand", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("rand")
            .strict_external()
            .because("core is deterministic"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a same-named item of ANOTHER module must not mask a real external call: {violations:?}"
    );
    assert_eq!(violations[0].target(), "rand");
    assert!(
        violations[0].finding.contains("rand::random"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_block_local_item_does_not_mask() {
    // The residual of that same class: only MODULE-TOP-LEVEL items shadow a bare head. A block-local
    // `const log` (brace depth ≥ 1) is NOT reachable as a bare head, so it must NOT suppress a real
    // external `log::logger()` call in the same module. Pre-fix (capture-all depth), the nested name
    // was captured and silently masked the call (a false negative); this guard reacts.
    // (A `const` keeps the case to the depth exclusion alone; a colliding `fn log`'s own name is its
    // definition and is never read as a call.)
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-blocklocal",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() {\n    const log: u32 = 3;\n    let _ = log::logger();\n}\n",
            ),
        ],
        &[("log", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("log")
            .strict_external()
            .because("core does not log"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a block-local item (depth ≥ 1) must not mask a same-module external call: {violations:?}"
    );
    assert_eq!(violations[0].target(), "log");
    assert!(
        violations[0].finding.contains("log::logger"),
        "{violations:?}"
    );
}

// --- inline-symbol-path: adversarial-review regression + coverage ------------------------

#[test]
pub(super) fn inline_reacts_on_a_leading_colon_path() {
    // A leading `::std::time::…::now()` must be extracted (its head sits after `::`).
    let (result, violations) = run_module_check(
        "inline-leading-colon",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = ::std::time::SystemTime::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a leading-:: call reacts: {violations:?}"
    );
    assert!(
        violations[0].finding.contains("std::time::SystemTime::now"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_reacts_on_a_nested_grouped_glob() {
    // `use std::{time::*, cmp::max}` — the nested glob member `time::*` reaches under
    // the prefix and must react fail-closed, though it is not a top-level `*`.
    let (result, violations) = run_module_check(
        "inline-nested-glob",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "use std::{cmp::max, time::*};\n"),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.iter().any(|v| v.finding.contains("glob")),
        "a nested grouped glob of the prefix reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_reacts_on_a_two_hop_use_realias() {
    // `use std::time::SystemTime; use self::SystemTime as Clock;` — the second use-hop
    // must resolve through the module's own `use` binding, not only through `pub` re-exports.
    let (result, violations) = run_module_check(
        "inline-two-hop-use",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "use std::time::SystemTime;\nuse self::SystemTime as Clock;\nfn f() { let _ = Clock::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a two-hop use re-alias resolves to a fixpoint: {violations:?}"
    );
}

/// Deliberately source rustc rejects — the nested groups name no module of `std`
/// (`error[E0433]: cannot find `a` in `std``) — since what is under test is the nesting depth the scanner
/// refuses past, not an answer about a program.
#[test]
pub(super) fn inline_glob_nested_past_the_depth_cap_is_a_scan_error_not_a_silent_drop() {
    // A pathologically brace-nested grouped glob must not silently vanish from the glob-hazard
    // observation past the use-tree parser's depth cap — a real, compilable glob nested that deep would
    // otherwise pass unobserved with no report, the false negative PROJECT.md's core contract
    // forbids. Past the cap, this must be a scan error, never a silent truncation: the one use-tree parser's cap,
    // which every reader of imports shares.
    let depth = 200;
    let source = format!(
        "use std::{{{}time::*{}}};",
        "a::{".repeat(depth),
        "}".repeat(depth)
    );
    let (result, _violations) = run_module_check(
        "inline-glob-depth-cap",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", &source)],
        confine_core_clock(),
    );
    let err = result.expect_err(
        "a grouped glob nested past the depth cap must be a scan error, not a silent drop",
    );
    assert!(
        err.contains("brace levels"),
        "the error must name the depth bound it could not judge past: {err}"
    );
}

/// Deliberately source rustc rejects (`error[E0433]`), for the reason the glob sibling above gives: the
/// subject is the refusal past the nesting cap.
#[test]
pub(super) fn inline_alias_chain_nested_past_the_depth_cap_is_a_scan_error_not_a_silent_drop() {
    // The identical false-negative shape as the glob test above, for the use-tree parser's named
    // leaves: a pathologically nested grouped `use` introducing an alias must not silently drop the
    // alias's binding past the depth cap — an inline call through that alias would
    // otherwise pass unresolved (never even reaching the confinement check).
    let depth = 200;
    let source = format!(
        "use std::{{{}time::SystemTime as Clock{}}};\nfn f() {{ let _ = Clock::now(); }}\n",
        "a::{".repeat(depth),
        "}".repeat(depth)
    );
    let (result, _violations) = run_module_check(
        "inline-alias-depth-cap",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", &source)],
        confine_core_clock(),
    );
    let err = result
        .expect_err("an alias nested past the depth cap must be a scan error, not a silent drop");
    assert!(
        err.contains("brace levels"),
        "the error must name the depth bound it could not judge past: {err}"
    );
}

#[test]
pub(super) fn inline_grouped_glob_nested_moderately_is_still_observed() {
    // Control: nesting comfortably under the depth cap is unaffected — the fix must not narrow
    // ordinary observation of a real, deeply (but not pathologically) nested grouped glob.
    // Braces-only nesting (no extra path segment per layer), so the glob still resolves to
    // exactly `std::time::*` regardless of depth — the pathological tests above only need SOME
    // resolvable-or-not path, but this control must still name the real confined prefix.
    let depth = 40;
    let source = format!(
        "use std::{}time::*{};",
        "{".repeat(depth),
        "}".repeat(depth)
    );
    let (result, violations) = run_module_check(
        "inline-glob-under-cap",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", &source)],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.iter().any(|v| v.finding.contains("glob")),
        "a moderately nested grouped glob of the prefix still reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_reacts_through_a_mid_path_turbofish() {
    // `Clock::<u8>::new()` — the mid-path turbofish must not break the path, and the
    // terminal `new` call must still react (via the resolved `std::vec::Vec::new`).
    let (result, violations) = run_module_check(
        "inline-turbofish",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "type Clock<T> = std::vec::Vec<T>;\nfn f() { let _ = Clock::<u8>::new(); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::vec")
            .because("no vectors are made inline"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a mid-path turbofish call reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_reacts_through_interior_whitespace_and_field_colon() {
    // Interior whitespace in the path, and a no-space struct-field `:` before a path.
    let (result, violations) = run_module_check(
        "inline-ws",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = std :: time :: Instant :: now(); }\nstruct E { at: std::time::SystemTime }\nfn g() -> E { E { at:std::time::SystemTime::now() } }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    // Two distinct now-reads (Instant::now, SystemTime::now); the `at: SystemTime` annotation is a
    // non-call mention and does not react.
    assert_eq!(
        violations.len(),
        2,
        "interior-whitespace and field-colon calls both react: {violations:?}"
    );
}

#[test]
pub(super) fn inline_ufcs_is_a_documented_bound_under_the_default() {
    // Stated bound: a UFCS-qualified call `<Type as Trait>::now()` puts the type inside `<…>`, not
    // a plain path — like a receiver-method read, out of scope under the default (strict catches
    // the mention). Asserted non-reaction so the bound is a declared non-observation, not silent.
    let (result, violations) = run_module_check(
        "inline-ufcs",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "trait Now { fn now(); }\nimpl Now for std::time::SystemTime { fn now() {} }\nfn f() { <std::time::SystemTime as Now>::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "UFCS is a stated bound under the default (type in <…>): {violations:?}"
    );
}

#[test]
pub(super) fn inline_receiver_method_read_is_a_bound() {
    // Stated bound: `inst.elapsed()` — the receiver's type is not in the written path (no type
    // inference), so it is out of scope. Asserted non-reaction (declared, not silent).
    let (result, violations) = run_module_check(
        "inline-receiver",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f(inst: std::time::Instant) { let _ = inst.elapsed(); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(["now", "elapsed"])
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a receiver-method read is a stated bound (type not in path): {violations:?}"
    );
}

#[test]
pub(super) fn inline_grouped_self_glob_reacts() {
    let (result, violations) = run_module_check(
        "inline-selfglob",
        &[
            ("lib.rs", "pub mod core;\n"),
            ("core.rs", "use std::time::{self, Duration, *};\n"),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.iter().any(|v| v.finding.contains("glob")),
        "a grouped `{{self, *}}` glob reacts: {violations:?}"
    );
}

#[test]
pub(super) fn inline_two_distinct_calls_stay_distinct() {
    // Identity: two distinct canonical calls in one module are two findings (no dedup masking).
    let (result, violations) = run_module_check(
        "inline-distinct",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = std::time::Instant::now(); let _ = std::time::SystemTime::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        2,
        "two distinct canonical calls stay distinct findings: {violations:?}"
    );
}

#[test]
pub(super) fn inline_prefix_is_carried_in_the_violation_target() {
    // Identity: the confined prefix is the violation target, so nested-prefix confinements (`std`
    // vs `std::time`) breached by the same call never share an identity (no baseline masking).
    let files: &[(&str, &str)] = &[
        ("lib.rs", "pub mod core;\n"),
        ("core.rs", "fn f() { let _ = std::time::Instant::now(); }\n"),
    ];
    let (r1, v1) = run_module_check(
        "inline-target-time",
        files,
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .because("no clock"),
    );
    let (r2, v2) = run_module_check(
        "inline-target-std",
        files,
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std")
            .because("no std calls"),
    );
    assert!(r1.is_ok() && r2.is_ok(), "{r1:?} {r2:?}");
    assert_eq!(v1[0].target(), "std::time");
    assert_eq!(v2[0].target(), "std");
    assert_ne!(
        v1[0].target(),
        v2[0].target(),
        "distinct prefixes → distinct identity"
    );
}

#[test]
pub(super) fn inline_warn_severity_is_advisory() {
    let (result, violations) = run_module_check(
        "inline-warn",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn f() { let _ = std::time::SystemTime::now(); }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .warn()
            .because("advisory"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].severity, Severity::Warn);
}

#[test]
pub(super) fn inline_empty_verbs_is_a_constitution_error() {
    let (result, _v) = run_module_check(
        "inline-emptyverbs",
        &[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .ending_with(Vec::<String>::new())
            .because("bad"),
    );
    assert_eq!(
        result.unwrap_err(),
        inline_empty_verbs_error("x", "must_not_call_inline")
    );
}

/// Every body here is deliberately malformed (rustc: `expected type, found `>``, among others); the test asserts
/// the scan completes, never an answer about a program: clean, a violation, or a refusal to judge the tokens it
/// cannot read — `use ::;`, whose path ends in `::` — never a panic, a hang or any other error.
#[test]
pub(super) fn inline_scanner_does_not_panic_or_hang_on_odd_input() {
    // Robustness: malformed `use`/brace/self-referential-alias input must never panic or hang.
    for body in [
        "use } {;\n",
        "use std::{time::*;\n",
        "type A = A::B;\nfn f() { let _ = A::now(); }\n",
        "use ::;\nfn f() { ::::(); }\n",
        "fn f() { <>::(); std :: :: now (); }\n",
    ] {
        let (result, _v) = run_module_check(
            "inline-odd",
            &[("lib.rs", "pub mod core;\n"), ("core.rs", body)],
            confine_core_clock(),
        );
        assert!(
            match &result {
                Ok(_) => true,
                Err(refusal) => refusal.contains("cannot judge"),
            },
            "odd input must complete, or be refused as unjudgeable: {body:?} -> {result:?}"
        );
    }
}

#[test]
pub(super) fn inline_in_macro_body_alias_is_a_bound() {
    // Stated bound: an alias DEFINED INSIDE a macro body binds nothing in the scope table, so a
    // call through it inside the same macro body does not resolve — a declared non-observation
    // (the macro body IS scanned for direct paths, but a body-local alias is out of scope).
    let (result, violations) = run_module_check(
        "inline-macro-alias",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "macro_rules! some_macro { ($($t:tt)*) => { $($t)* }; }\nfn f() { some_macro! { use std::time::SystemTime as X; let _ = X::now(); } }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "an alias defined inside a macro body is a stated bound: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_inline_submodule_call_is_not_masked() {
    // Cardinal false-negative guard: a file-top `fn rand` must NOT mask a real external
    // `rand::random()` call inside an inline `mod tests { … }`. The call's TRUE module is
    // `crate::core::tests`, so the file-top item `crate::core::rand` cannot claim its head — the
    // external match fires. Pre-fix the call scan tracked no inline-`mod` nesting, so the file-top
    // item silently shadowed the submodule call (the bug the review caught); this guard reacts.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-submod-call",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn rand() -> u32 { 4 }\nmod tests { fn t() { let _ = rand::random(); } }\n",
            ),
        ],
        &[("rand", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("rand")
            .strict_external()
            .because("core is deterministic"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a file-top item must not mask an external call inside an inline submodule: {violations:?}"
    );
    assert_eq!(violations[0].target(), "rand");
    assert!(
        violations[0].finding.contains("rand::random"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_submodule_local_item_stays_clean() {
    // Bonus FP guard: a submodule-local `fn rand` IS now captured under its true module
    // (`crate::core::tests::rand`), so a bare `rand()` call in that same submodule resolves to the
    // local item and stays clean. (Pre-fix the item was at brace depth ≥ 1 and never captured, so
    // this could false-positive; the inline-aware keying closes it.)
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-submod-local",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "mod tests { fn rand() -> u32 { 4 } fn t() { let _ = rand(); } }\n",
            ),
        ],
        &[("rand", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("rand")
            .strict_external()
            .because("core is deterministic"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a submodule-local item named like a dep must claim its own submodule's call: {violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_deeply_nested_submodule_reacts() {
    // The inline-`mod` stack composes to any depth: a file-top `fn rand` cannot mask a
    // `rand::random()` call two submodules deep (`crate::core::a::b`), so the external match fires.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-nested",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn rand() -> u32 { 4 }\nmod a { mod b { fn t() { let _ = rand::random(); } } }\n",
            ),
        ],
        &[("rand", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("rand")
            .strict_external()
            .because("core is deterministic"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a file-top item must not mask a call in a deeply nested submodule: {violations:?}"
    );
    assert_eq!(violations[0].target(), "rand");
    assert!(
        violations[0].finding.contains("rand::random"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_cfg_gated_submodule_reacts() {
    // A `#[cfg(test)]` attribute on the inline `mod` carries only `(…)`/`[…]` — no `{`/`}` — so it
    // does not perturb the brace-depth tracking: the `mod tests { … }` body is still entered and the
    // `rand::random()` call inside it is attributed to `crate::core::tests`, unmasked by the
    // file-top `fn rand`.
    let (result, violations) = run_module_check_with_deps(
        "inline-strict-ext-cfg-gated",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn rand() -> u32 { 4 }\n#[cfg(test)]\nmod tests { fn t() { let _ = rand::random(); } }\n",
            ),
        ],
        &[("rand", None)],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("rand")
            .strict_external()
            .because("core is deterministic"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a cfg-gated inline submodule must not perturb brace tracking: {violations:?}"
    );
    assert_eq!(violations[0].target(), "rand");
    assert!(
        violations[0].finding.contains("rand::random"),
        "{violations:?}"
    );
}

#[test]
pub(super) fn inline_strict_external_default_path_module_attribution_unshifted() {
    // Default-path byte-identity: a NON-strict inline confinement whose call sits inside an inline
    // `mod tests { … }` must still attribute the finding to the FILE module (`crate::core`), NOT the
    // submodule — proving the new per-occurrence inline module is computed only under the flag and
    // never leaks into default attribution.
    let (result, violations) = run_module_check(
        "inline-default-attr",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "mod tests { fn t() { let _ = std::time::SystemTime::now(); } }\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_call_inline("std::time")
            .because("core reads no wall clock"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert!(
        violations[0].finding.ends_with("in crate::core"),
        "default attribution must stay on the FILE module, not the inline submodule: {violations:?}"
    );
}

#[test]
pub(super) fn scan_depth_shallow_vs_subtree_evaluates_submodule_matching() {
    let files = &[
        (
            "lib.rs",
            "pub mod forbidden_on_core {}\npub mod forbidden_on_sub {}\npub mod core;\n",
        ),
        ("core.rs", "pub mod sub;\nuse crate::forbidden_on_core;\n"),
        ("core/sub.rs", "use crate::forbidden_on_sub;\n"),
    ];

    // 1. Shallow depth: boundary on crate::core only governs core.rs, so import in core/sub.rs does NOT react
    let shallow_boundary = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_import("crate::forbidden_on_sub")
        .depth(xuanji::ScanDepth::Shallow)
        .because("core seam does not import forbidden_on_sub");
    let (res1, shallow_violations) =
        run_module_check("scan-depth-shallow", files, shallow_boundary);
    assert!(res1.is_ok(), "{res1:?}");
    assert_eq!(
        shallow_violations.len(),
        0,
        "Shallow depth ignores submodule files"
    );

    // 2. Subtree depth: boundary on crate::core governs core.rs AND core/sub.rs, so import in core/sub.rs DOES react
    let subtree_boundary = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_import("crate::forbidden_on_sub")
        .depth(xuanji::ScanDepth::Subtree)
        .because("core subtree does not import forbidden_on_sub");
    let (res2, subtree_violations) =
        run_module_check("scan-depth-subtree", files, subtree_boundary);
    assert!(res2.is_ok(), "{res2:?}");
    assert_eq!(
        subtree_violations.len(),
        1,
        "Subtree depth evaluates submodule files"
    );
    assert_eq!(
        subtree_violations[0]
            .rule_key()
            .fields()
            .collect::<Vec<_>>(),
        vec![("module", "crate::forbidden_on_sub")]
    );
}

#[test]
pub(super) fn module_boundary_including_submodules_is_a_compatible_subtree_modifier() {
    let default = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_import("crate::adapter")
        .because("r");
    let explicit = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_import("crate::adapter")
        .depth(xuanji::ScanDepth::Subtree)
        .because("r");
    let ergonomic = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_import("crate::adapter")
        .depth(xuanji::ScanDepth::Shallow)
        .including_submodules()
        .because("r");

    assert_eq!(default.scan_depth(), xuanji::ScanDepth::Subtree);
    assert_eq!(explicit.scan_depth(), xuanji::ScanDepth::Subtree);
    assert_eq!(ergonomic.scan_depth(), xuanji::ScanDepth::Subtree);
    assert_eq!(default.rule_key(), ergonomic.rule_key());
}

#[test]
pub(super) fn shallow_restrict_imports_to_ignores_descendant_imports() {
    let files = &[
        ("lib.rs", "pub mod adapter {}\npub mod core;\n"),
        ("core.rs", "pub mod detail;\n"),
        ("core/detail.rs", "use crate::adapter;\n"),
    ];
    let shallow = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .restrict_imports_to(["crate::core"])
        .depth(xuanji::ScanDepth::Shallow)
        .because("the core seam depends inward");
    let (shallow_result, shallow_violations) =
        run_module_check("shallow-restrict-imports", files, shallow);
    assert!(shallow_result.is_ok(), "{shallow_result:?}");
    assert!(shallow_violations.is_empty(), "{shallow_violations:?}");

    let subtree = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .restrict_imports_to(["crate::core"])
        .because("the core subtree depends inward");
    let (subtree_result, subtree_violations) =
        run_module_check("subtree-restrict-imports", files, subtree);
    assert!(subtree_result.is_ok(), "{subtree_result:?}");
    assert_eq!(subtree_violations.len(), 1, "{subtree_violations:?}");
}

#[test]
pub(super) fn shallow_inbound_rules_protect_only_the_exact_module() {
    let files = &[
        (
            "lib.rs",
            "pub mod facade {}\npub mod protected;\npub mod client;\n",
        ),
        ("protected.rs", "pub mod detail;\n"),
        ("protected/detail.rs", "pub struct Item;\n"),
        ("client.rs", "use crate::protected::detail::Item;\n"),
    ];

    let shallow_forbid = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_not_be_imported_by("crate::client")
        .depth(xuanji::ScanDepth::Shallow)
        .because("only the protected seam rejects this importer");
    let (_, shallow_forbid_violations) =
        run_module_check("shallow-inbound-forbid", files, shallow_forbid);
    assert!(
        shallow_forbid_violations.is_empty(),
        "{shallow_forbid_violations:?}"
    );

    let subtree_forbid = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_not_be_imported_by("crate::client")
        .because("the protected subtree rejects this importer");
    let (_, subtree_forbid_violations) =
        run_module_check("subtree-inbound-forbid", files, subtree_forbid);
    assert_eq!(
        subtree_forbid_violations.len(),
        1,
        "{subtree_forbid_violations:?}"
    );

    let shallow_allow = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_only_be_imported_by(["crate::facade"])
        .depth(xuanji::ScanDepth::Shallow)
        .because("only the protected seam has a closed importer set");
    let (_, shallow_allow_violations) =
        run_module_check("shallow-inbound-allow", files, shallow_allow);
    assert!(
        shallow_allow_violations.is_empty(),
        "{shallow_allow_violations:?}"
    );

    let subtree_allow = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_only_be_imported_by(["crate::facade"])
        .because("the protected subtree has a closed importer set");
    let (_, subtree_allow_violations) =
        run_module_check("subtree-inbound-allow", files, subtree_allow);
    assert_eq!(
        subtree_allow_violations.len(),
        1,
        "{subtree_allow_violations:?}"
    );
}

#[test]
pub(super) fn shallow_inbound_rules_react_to_an_item_import_of_the_anchored_module() {
    // An item-form import (`use crate::protected::Secret;`, an item declared directly in the
    // anchored module) must still react under Shallow — unlike an import of a descendant
    // module's item (already covered by `shallow_inbound_rules_protect_only_the_exact_module`),
    // this import's target module IS the anchored module itself, so narrowing to Shallow must
    // not exempt it. A lexical string comparison of the full import path against the anchored
    // module conflates the two cases; this regression pins the anchored one distinctly.
    let files = &[
        (
            "lib.rs",
            "pub mod facade {}\npub mod protected;\npub mod client;\n",
        ),
        ("protected.rs", "pub struct Secret;\n"),
        ("client.rs", "use crate::protected::Secret;\n"),
    ];

    let shallow_forbid = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_not_be_imported_by("crate::client")
        .depth(xuanji::ScanDepth::Shallow)
        .because("an item import of the anchored module still reacts under Shallow");
    let (forbid_result, forbid_violations) =
        run_module_check("shallow-inbound-item-forbid", files, shallow_forbid);
    assert!(forbid_result.is_ok(), "{forbid_result:?}");
    assert_eq!(
        forbid_violations.len(),
        1,
        "an item-form import of the anchored module must react even under Shallow: {forbid_violations:?}"
    );

    let shallow_allow = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_only_be_imported_by(["crate::facade"])
        .depth(xuanji::ScanDepth::Shallow)
        .because("an item import of the anchored module still reacts under Shallow");
    let (allow_result, allow_violations) =
        run_module_check("shallow-inbound-item-allow", files, shallow_allow);
    assert!(allow_result.is_ok(), "{allow_result:?}");
    assert_eq!(
        allow_violations.len(),
        1,
        "an item-form import by an importer outside the allowlist must react even under Shallow: {allow_violations:?}"
    );
}

#[test]
pub(super) fn shallow_inbound_rules_never_flag_the_protected_modules_own_descendant_as_an_importer()
{
    // The self-import exemption ("a file within the protected module's own subtree is never an
    // inbound importer") is unconditional in `intent/module-boundary.md`, not depth-gated — narrowing to Shallow
    // scopes what counts as *reaching* the protected module, never who counts as *inside* it.
    // A descendant submodule of the protected module importing an item declared directly in the
    // protected module itself must stay exempt even under Shallow, exactly as it already is under
    // Subtree — otherwise fixing the target-match precision (the item-import false negative)
    // would introduce a false positive here instead.
    let files = &[
        ("lib.rs", "pub mod facade {}\npub mod protected;\n"),
        ("protected.rs", "pub mod detail;\npub struct Secret;\n"),
        ("protected/detail.rs", "use crate::protected::Secret;\n"),
    ];

    let shallow_allow = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_only_be_imported_by(["crate::facade"])
        .depth(xuanji::ScanDepth::Shallow)
        .because("the protected module's own descendant is never an inbound importer");
    let (allow_result, allow_violations) = run_module_check(
        "shallow-inbound-self-descendant-allow",
        files,
        shallow_allow,
    );
    assert!(allow_result.is_ok(), "{allow_result:?}");
    assert!(
        allow_violations.is_empty(),
        "a descendant of the protected module importing the protected module's own item must \
         never be flagged, even under Shallow: {allow_violations:?}"
    );

    let shallow_forbid = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_not_be_imported_by("crate::protected::detail")
        .depth(xuanji::ScanDepth::Shallow)
        .because("the protected module's own descendant is never an inbound importer");
    let (forbid_result, forbid_violations) = run_module_check(
        "shallow-inbound-self-descendant-forbid",
        files,
        shallow_forbid,
    );
    assert!(forbid_result.is_ok(), "{forbid_result:?}");
    assert!(
        forbid_violations.is_empty(),
        "a descendant of the protected module is never an inbound importer, even when it is also \
         (degenerately) named as the forbidden importer: {forbid_violations:?}"
    );
}

#[test]
pub(super) fn shallow_inbound_target_match_observes_the_value_namespace() {
    // Rust resolves `mod foo` and `fn foo` in DIFFERENT namespaces, so both may live in one module
    // and one `use protected::foo;` binds both — verified against rustc, not reasoned: an importer
    // writing only that `use` can call `foo()` and also reach `foo::INSIDE`.
    //
    // `resolve_import_module` sees only the path, so on its own it returns the module reading. Under
    // `Shallow` anchored at `crate::protected`, the value reading (an item declared directly in the
    // protected module — reacts) and the module reading (only a descendant module — does not react)
    // disagree, and the module reading used to win: a real import reaching the protected module was
    // unobserved. That was recorded as a stated bound on the grounds that closing it "needs a
    // value-namespace item observation guibiao does not have".
    //
    // 圭表 DOES have it. `symbol_scan`'s definition collector already reads every module's own
    // top-level `fn`/`const`/`static` from the token tree, with the true-inline-module
    // qualification and module-top-level-only disciplines already worked out. So the reaction now
    // consults it, and reacts only when the governed module really declares a value item of that
    // name — which is what keeps `shallow_inbound_rules_protect_only_the_exact_module` (an ordinary
    // `use protected::child;`, module-only) passing unchanged. The narrow false negative is closed
    // without buying the broad false positive that reacting on both readings would have cost.
    let files = &[
        (
            "lib.rs",
            "pub mod facade {}\npub mod protected;\npub mod consumer;\n",
        ),
        ("protected.rs", "pub mod foo;\npub fn foo() -> u8 { 7 }\n"),
        ("protected/foo.rs", "pub const INSIDE: u8 = 1;\n"),
        ("consumer.rs", "use crate::protected::foo;\n"),
    ];

    let shallow = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_only_be_imported_by(["crate::facade"])
        .depth(xuanji::ScanDepth::Shallow)
        .because("only the facade may reach into protected");
    let (shallow_result, shallow_violations) =
        run_module_check("namespace-blind-shallow", files, shallow);
    assert!(shallow_result.is_ok(), "{shallow_result:?}");
    assert_eq!(
        shallow_violations.len(),
        1,
        "`use crate::protected::foo;` binds the `fn foo` declared directly in the protected module, \
         so it reaches that module and must react under Shallow: {shallow_violations:?}"
    );
    assert!(
        shallow_violations[0].finding.contains("crate::consumer"),
        "the finding names the importing module: {:?}",
        shallow_violations[0].finding
    );

    // Under `Subtree` both readings lie within the protected module, so the import reacts either
    // way — the bound is confined to the `Shallow` cell, which is what makes it narrow.
    let subtree = ModuleBoundary::in_crate("x")
        .module("crate::protected")
        .must_only_be_imported_by(["crate::facade"])
        .depth(xuanji::ScanDepth::Subtree)
        .because("only the facade may reach into protected");
    let (subtree_result, subtree_violations) =
        run_module_check("namespace-blind-subtree", files, subtree);
    assert!(subtree_result.is_ok(), "{subtree_result:?}");
    assert_eq!(
        subtree_violations.len(),
        1,
        "under Subtree the two readings coincide, so the import must react: {subtree_violations:?}"
    );
    assert_eq!(subtree_violations[0].finding, "crate::consumer");
}

#[test]
pub(super) fn shallow_inbound_rules_do_not_read_a_file_the_self_import_exemption_excuses() {
    // The exemption above is observable in the violation output at either depth, because the
    // per-import check excuses these importers even when the file IS read. What was NOT the same at
    // both depths was whether the file gets read at all: a depth-gated fast path over a depth-free
    // exemption skipped the read only under `Subtree`, so at `Shallow` a file inside the protected
    // subtree was read and scanned — and any read that can fail then diverges. A `use` tree nested
    // past the scanner's brace-nesting cap is such a failure (fail-loud by design, exit 2), so it
    // pins the divergence: the identical protected-subtree file must be excused, not judged, at both
    // depths. Anything the exemption excuses must not be able to decide the exit code.
    let deep_use = format!(
        "use crate::protected::{}Secret{};\n",
        "{".repeat(200),
        "}".repeat(200)
    );
    let files = &[
        ("lib.rs", "pub mod facade {}\npub mod protected;\n"),
        ("protected.rs", "pub mod detail;\npub struct Secret;\n"),
        ("protected/detail.rs", deep_use.as_str()),
    ];

    for depth in [xuanji::ScanDepth::Shallow, xuanji::ScanDepth::Subtree] {
        let boundary = ModuleBoundary::in_crate("x")
            .module("crate::protected")
            .must_only_be_imported_by(["crate::facade"])
            .depth(depth)
            .because("the protected module's own descendant is never an inbound importer");
        let ws = TempWorkspace::new("shallow-inbound-self-descendant-unread");
        for (file, source) in files {
            ws.write(file, source);
        }
        let scans = crate::module_scan::EvaluationScans::shared();
        let mut violations = Vec::new();
        let result = crate::module_check::check_module_boundary(
            &ws.metadata("x"),
            &scans,
            &boundary,
            &mut violations,
        );
        assert!(
            result.is_ok(),
            "a file the self-import exemption excuses must never be read, so its content cannot \
             produce a scan error at {depth:?}: {result:?}"
        );
        assert!(violations.is_empty(), "{depth:?}: {violations:?}");
        assert_eq!(
            scans.classifications(),
            std::collections::HashMap::from([((ws.src().join("lib.rs"), "crate".to_string()), 1)]),
            "only the root's imports are read; a file the self-import exemption excuses is never classified at {depth:?}"
        );
    }
}

#[test]
pub(super) fn shallow_external_confinement_permits_only_the_exact_module() {
    let files = &[
        ("lib.rs", "pub mod secret;\n"),
        ("secret.rs", "pub mod detail;\n"),
        ("secret/detail.rs", "use libc::c_int;\n"),
    ];
    let shallow = ModuleBoundary::in_crate("x")
        .module("crate::secret")
        .confine_external_crate("libc")
        .depth(xuanji::ScanDepth::Shallow)
        .because("only the secret seam may import libc");
    let (shallow_result, shallow_violations) = run_module_check_with_deps(
        "shallow-external-confinement",
        files,
        &[("libc", None)],
        shallow,
    );
    assert!(shallow_result.is_ok(), "{shallow_result:?}");
    assert_eq!(shallow_violations.len(), 1, "{shallow_violations:?}");

    let subtree = ModuleBoundary::in_crate("x")
        .module("crate::secret")
        .confine_external_crate("libc")
        .because("the secret subtree may import libc");
    let (subtree_result, subtree_violations) = run_module_check_with_deps(
        "subtree-external-confinement",
        files,
        &[("libc", None)],
        subtree,
    );
    assert!(subtree_result.is_ok(), "{subtree_result:?}");
    assert!(subtree_violations.is_empty(), "{subtree_violations:?}");
}

#[test]
pub(super) fn scan_depth_projection_omits_legacy_subtree_and_emits_shallow() {
    let legacy = Constitution::new("legacy").boundary(
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_import("crate::adapter")
            .because("core depends inward only"),
    );
    let legacy_json: serde_json::Value = serde_json::from_str(&constitution_json(&legacy)).unwrap();
    assert!(
        legacy_json["boundaries"][0].get("scan_depth").is_none(),
        "legacy subtree projection must stay byte-compatible: {legacy_json}"
    );

    let shallow = Constitution::new("shallow").boundary(
        ModuleBoundary::in_crate("x")
            .module("crate::core")
            .must_not_import("crate::adapter")
            .depth(xuanji::ScanDepth::Shallow)
            .because("only the core seam depends inward"),
    );
    let shallow_json: serde_json::Value =
        serde_json::from_str(&constitution_json(&shallow)).unwrap();
    assert_eq!(shallow_json["boundaries"][0]["scan_depth"], "shallow");
}

#[test]
pub(super) fn legacy_inline_confinement_defaults_to_subtree_and_preserves_identity() {
    let files = &[
        ("lib.rs", "pub mod core;\n"),
        ("core.rs", "pub mod sub;\n"),
        (
            "core/sub.rs",
            "fn t() { let _ = std::time::SystemTime::now(); }\n",
        ),
    ];

    // 1. Legacy inline boundary without explicit depth -> defaults to Subtree -> catches call in core/sub.rs
    let legacy_boundary = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_call_inline("std::time")
        .because("core reads no wall clock");
    let (res, violations) = run_module_check("legacy-inline-subtree", files, legacy_boundary);
    assert!(res.is_ok(), "{res:?}");
    assert_eq!(
        violations.len(),
        1,
        "Legacy inline boundary governs submodules"
    );
    // Verify legacy RuleKey identity has NO "scan_depth" field (zero baseline breakage)
    assert_eq!(
        violations[0].rule_key().fields().collect::<Vec<_>>(),
        vec![
            ("ending_with", "[]"),
            ("prefix", "std::time"),
            ("strict", "false")
        ]
    );

    // 2. Explicit Shallow depth -> restricts observation seam to core.rs -> ignores call in core/sub.rs
    let shallow_boundary = ModuleBoundary::in_crate("x")
        .module("crate::core")
        .must_not_call_inline("std::time")
        .depth(xuanji::ScanDepth::Shallow)
        .because("core seam reads no wall clock");
    let (res2, shallow_violations) =
        run_module_check("shallow-inline-seam", files, shallow_boundary);
    assert!(res2.is_ok(), "{res2:?}");
    assert_eq!(
        shallow_violations.len(),
        0,
        "Explicit Shallow depth ignores submodule calls"
    );
}

/// Two-crate reproduction of the audit-sweep finding: identical governed module path + rule
/// declared against two different workspace members must stay two distinct violations, never
/// dedup into one and never let one crate's baseline suppress the other's unaccepted violation.
/// Mirrors the exact shape `crates/shengmo/src/law.rs` declares on itself
/// (the identical rule on guibiao/hunyi/louke).
#[test]
pub(super) fn two_crates_with_the_identical_module_boundary_stay_distinct_violations() {
    let alpha = TempWorkspace::new("identity-scope-alpha");
    alpha.write("lib.rs", "pub mod app;\npub mod secret;\n");
    alpha.write("app.rs", "use crate::secret::S;\n");
    alpha.write("secret.rs", "pub struct S;\n");

    let beta = TempWorkspace::new("identity-scope-beta");
    beta.write("lib.rs", "pub mod app;\npub mod secret;\n");
    beta.write("app.rs", "use crate::secret::S;\n");
    beta.write("secret.rs", "pub struct S;\n");

    fn package_json(ws: &TempWorkspace, name: &str) -> serde_json::Value {
        let manifest = ws.dir().join("Cargo.toml");
        serde_json::json!({
            "name": name,
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        })
    }
    let metadata = serde_json::json!({
        "packages": [package_json(&alpha, "alpha"), package_json(&beta, "beta")]
    });

    fn boundary_for(package: &str) -> ModuleBoundary {
        ModuleBoundary::in_crate(package)
            .module("crate::app")
            .must_not_import("crate::secret")
            .because("app must not touch secret")
    }

    // Both crates violating, evaluated together: must yield two distinct violations, not one.
    let constitution = Constitution::new("probe")
        .boundary(boundary_for("alpha"))
        .boundary(boundary_for("beta"));
    let outcome = evaluate(&constitution, &metadata);
    let report = match outcome {
        Outcome::Violations(report) => report,
        other => panic!("expected two violations, got {other:?}"),
    };
    assert_eq!(
        report.violations.len(),
        2,
        "each crate's violation must survive dedup: {:?}",
        report.violations
    );
    let ids: std::collections::BTreeSet<_> = report.violations.iter().map(Violation::id).collect();
    assert_eq!(
        ids.len(),
        2,
        "identity must differ by crate, not collapse to one"
    );
    let files: std::collections::BTreeSet<_> = report
        .violations
        .iter()
        .map(|v| v.file.clone().expect("each violation carries a file"))
        .collect();
    assert_eq!(
        files.len(),
        2,
        "each violation must keep its own crate's file, not share one"
    );

    // Baseline written against alpha alone must not suppress beta's unaccepted violation.
    let alpha_only_constitution = Constitution::new("probe").boundary(boundary_for("alpha"));
    let alpha_only_report = match evaluate(&alpha_only_constitution, &metadata) {
        Outcome::Violations(report) => report,
        other => panic!("expected alpha's violation, got {other:?}"),
    };
    assert_eq!(alpha_only_report.violations.len(), 1);
    let baseline = Baseline::of(&alpha_only_report);

    let both_constitution = Constitution::new("probe")
        .boundary(boundary_for("alpha"))
        .boundary(boundary_for("beta"));
    let mut both_report = match evaluate(&both_constitution, &metadata) {
        Outcome::Violations(report) => report,
        other => panic!("expected two violations, got {other:?}"),
    };
    apply_baseline(&mut both_report, &baseline);
    let alpha_violation = both_report
        .violations
        .iter()
        .find(|v| v.target() == "crate::app" && baseline.contains(v))
        .expect("alpha's violation must match the baseline");
    assert!(alpha_violation.baselined, "alpha's violation was accepted");
    let unbaselined: Vec<_> = both_report
        .violations
        .iter()
        .filter(|v| !v.baselined)
        .collect();
    assert_eq!(
        unbaselined.len(),
        1,
        "beta's violation must react as new, not be suppressed by alpha's baseline: {:?}",
        both_report.violations
    );
}

/// A source file ending in an unterminated block comment (no closing `*/`, no trailing newline)
/// that swallows a multi-byte UTF-8 character must react 0/1/2 like any other source, never
/// panic. The shape is the one where a byte-at-a-time reader of a comment can stop with fewer bytes left
/// than a character's length: the comment runs to end of input and the input ends inside a multi-byte
/// character's span, so a reader that resumes on the remaining byte indexes into the middle of a character.
///
/// Deliberately source rustc rejects (`error[E0758]: unterminated block comment`): the subject is that the
/// lexer survives it.
#[test]
pub(super) fn an_unterminated_block_comment_swallowing_a_multibyte_char_does_not_panic() {
    let (result, violations) = run_module_check(
        "unterminated-block-comment-multibyte",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\npub mod child;\n/* \u{672a}\u{5b8c}",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
            ("child.rs", "use crate::forbidden::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::child")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(
        result.is_ok(),
        "an unterminated block comment must not abort the scan: {result:?}"
    );
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target(), "crate::child");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

/// The identical defect, triggered on the crate root file directly (governed at `crate` rather
/// than a submodule) with only a single `pub mod` before the unterminated comment, so the
/// swallowed trailing byte lands at a different absolute offset — exercising the same code path
/// from a second, independently-chosen position rather than only the sibling test's exact shape.
///
/// Deliberately source rustc rejects (`error[E0758]: unterminated block comment`), as its sibling is.
#[test]
pub(super) fn an_unterminated_block_comment_at_end_of_file_with_no_trailing_newline_does_not_panic()
{
    let (result, violations) = run_module_check(
        "unterminated-block-comment-eof",
        &[
            ("lib.rs", "pub mod forbidden {}\npub mod child;\n/*\u{7121}"),
            ("child.rs", "use crate::forbidden::Thing;\n"),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::child")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(
        result.is_ok(),
        "an unterminated block comment must not abort the scan: {result:?}"
    );
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target(), "crate::child");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

/// A non-ASCII char literal immediately adjacent to a `'{'` literal (`['«','{']`, no space) must
/// not be read as a structural brace: a spurious one would pair with a later closer and drop every
/// later top-level `mod` from the reachable set, so a boundary anchored above the affected module
/// would pass a real forbidden import (exit 0 Clean on source `rustc` compiles as-is).
#[test]
pub(super) fn a_non_ascii_char_literal_adjacent_to_a_brace_literal_does_not_leak_a_spurious_brace()
{
    let (result, violations) = run_module_check(
        "char-literal-brace-leak-no-space",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\nconst Q: [char; 2] = ['\u{ab}','{'];\npub mod hidden;\n",
            ),
            (
                "hidden.rs",
                "use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

/// The identical shape, but the boundary is anchored directly at the module the leak used to drop
/// (`crate::hidden`) rather than above it. Before the fix this failed loud (exit 2, "module
/// 'crate::hidden' is not found among the reachable modules") instead of silently passing — after
/// the fix the module is genuinely reachable, so the boundary resolves and reacts normally.
#[test]
pub(super) fn a_boundary_anchored_directly_at_the_previously_dropped_module_resolves() {
    let (result, violations) = run_module_check(
        "char-literal-brace-leak-anchored-at-dropped",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\nconst Q: [char; 2] = ['\u{ab}','{'];\npub mod hidden;\n",
            ),
            (
                "hidden.rs",
                "use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::hidden")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(
        result.is_ok(),
        "crate::hidden must be reachable, not a constitution error: {result:?}"
    );
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target(), "crate::hidden");
}

/// The identical defect in its everyday form — a `match` arm pattern, not an array literal — one
/// hop from the audit's original trigger shape, exercising the same lexer branch from different
/// surrounding syntax. The pipe must sit with **no surrounding spaces** (`'é'|'{'`, matching the
/// audit's exact citation) — a spaced pipe (`'é' | '{'`) inserts extra separator bytes between the
/// misread closing quote and the next literal's opening quote, which happens not to collide with
/// this exact defect and would silently test nothing (confirmed while writing this test: the
/// spaced form passed even with the bug still present).
#[test]
pub(super) fn a_non_ascii_char_literal_adjacent_to_a_brace_literal_in_a_match_arm_does_not_leak() {
    let (result, violations) = run_module_check(
        "char-literal-brace-leak-match-arm",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\npub fn is_special(c: char) -> bool { match c { '\u{e9}'|'{' => true, _ => false } }\npub mod hidden;\n",
            ),
            (
                "hidden.rs",
                "use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

/// Control: the identical array literal but with a space inserted (`['«', '{']`) already worked
/// correctly before this fix and must keep working — locks in that the fix does not regress the
/// already-passing spelling.
#[test]
pub(super) fn the_spaced_spelling_of_the_same_array_literal_already_reacts_and_keeps_reacting() {
    let (result, violations) = run_module_check(
        "char-literal-brace-leak-with-space",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\nconst Q: [char; 2] = ['\u{ab}', '{'];\npub mod hidden;\n",
            ),
            (
                "hidden.rs",
                "use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

/// A 4-byte scalar (an emoji) adjacent to `'{'` — added after an independent apply-stage review
/// constructed this case and confirmed it fails without the fix, generalizing the defect beyond
/// the 2/3-byte scalars the other tests exercise.
#[test]
pub(super) fn a_four_byte_scalar_char_literal_adjacent_to_a_brace_literal_does_not_leak() {
    let (result, violations) = run_module_check(
        "char-literal-brace-leak-four-byte-scalar",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\nconst Q: [char; 2] = ['\u{1f980}','{'];\npub mod hidden;\n",
            ),
            (
                "hidden.rs",
                "use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

/// Three char literals in a row, `['«','{','{']` — a cascading version of the two-literal defect:
/// the misread first literal's closing quote can coincidentally swallow *each subsequent* literal's
/// opening quote in turn (closing-quote, comma, opening-quote matches the old one-byte assumption
/// every time), so a fix that only demonstrably closes the single-literal case could still leak a
/// *second*, unmatched brace one hop further. Deliberately two unmatched `{` rather than a `{`/`}`
/// pair: a leaked *matched* pair nets to zero depth change and was verified, while constructing
/// this test, to pass even with the bug present — it doesn't actually corrupt the reachability
/// walker's brace-depth tracking, so it would have been a vacuous regression test. Two unmatched
/// opens do shift depth permanently, which is what a naive one-hop fix could still miss.
#[test]
pub(super) fn two_unmatched_braces_cascading_from_chained_char_literals_do_not_leak() {
    let (result, violations) = run_module_check(
        "char-literal-brace-leak-two-unmatched-cascade",
        &[
            (
                "lib.rs",
                "pub mod forbidden;\nconst Q: [char; 3] = ['\u{ab}','{','{'];\npub mod hidden;\n",
            ),
            (
                "hidden.rs",
                "use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
            ),
            ("forbidden.rs", "pub struct Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_import("crate::forbidden")
            .because("probe"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}

// --- inline-call prefixes: one canonical spelling, naming something that exists ---------------

/// Every spelling an inline-call prefix is judged on, with the form it is accepted as or the
/// suggestion its refusal must carry. Where a path starts is judged against the crate afterwards;
/// this table is the spelling alone.
const INLINE_PREFIX_SPELLINGS: &[(&str, Result<&str, Option<&str>>)] = &[
    ("std::time", Ok("std::time")),
    ("crate::clock", Ok("crate::clock")),
    ("crate::r#clock", Ok("crate::clock")),
    ("r#std::time", Ok("std::time")),
    ("clock", Ok("clock")),
    ("crate::clock::", Err(Some("crate::clock"))),
    ("::std::time", Ok("::std::time")),
    ("::std::time::", Err(Some("::std::time"))),
    ("crate::::clock", Err(Some("crate::clock"))),
    ("std :: time", Err(Some("std::time"))),
    (" crate::clock", Err(Some("crate::clock"))),
    ("r#crate::clock", Err(Some("crate::clock"))),
    ("self::clock", Err(None)),
    ("Self::clock", Err(None)),
    ("super::clock", Err(None)),
    ("std::time::*", Err(None)),
    ("std::process\u{200e}", Err(None)),
    ("std::\u{2028}time", Err(Some("std::time"))),
    ("std::pro\u{ad}cess", Err(None)),
    ("std::\u{2060}process", Err(None)),
    ("std::process\u{2014}", Err(None)),
    ("core::pro\u{ad}cess", Err(None)),
    ("md5x::pro\u{ad}cess", Err(None)),
    ("md5x::\u{2060}hash", Err(None)),
    ("md5x::\u{1f980}", Err(None)),
    ("md5x::\u{e9}t\u{e9}", Ok("md5x::\u{e9}t\u{e9}")),
    ("md5x::\u{6a21}\u{7d44}", Ok("md5x::\u{6a21}\u{7d44}")),
    ("md5x::_\u{e9}", Ok("md5x::_\u{e9}")),
    ("proc_macro::Token\u{405}tream", Err(None)),
    ("test::bl\u{43e}ck_box", Err(None)),
    ("std::_", Err(None)),
    ("md5x::_", Err(None)),
];

#[test]
pub(super) fn an_inline_prefix_is_accepted_only_in_its_canonical_spelling() {
    let wrong: Vec<_> = INLINE_PREFIX_SPELLINGS
        .iter()
        .filter_map(|(written, expected)| {
            let answer =
                crate::module_scan::canonical_symbol_path_spelling(written).map(|prefix| {
                    match prefix.root {
                        crate::module_scan::PrefixRoot::Global => format!("::{}", prefix.path),
                        crate::module_scan::PrefixRoot::Bare => prefix.path,
                    }
                });
            let expected = expected
                .map(str::to_string)
                .map_err(|s| s.map(str::to_string));
            (answer != expected).then(|| format!("{written:?}: {answer:?}, expected {expected:?}"))
        })
        .collect();
    assert!(wrong.is_empty(), "{wrong:#?}");
}

/// A library `x` declaring `crate::clock` (with the item `now` and the type `Clock`) and `crate::core`,
/// which calls `crate::clock::now()`; a binary declaring `crate::cli`; and three dependencies, `extdep`,
/// `otherdep` imported as `renamed`, and `my-dep`.
fn inline_prefix_fixture(label: &str) -> (TempWorkspace, Value) {
    let ws = TempWorkspace::new(label);
    ws.write("lib.rs", "pub mod clock;\npub mod core;\n");
    ws.write(
        "clock.rs",
        "pub fn now() -> u64 { 0 }\npub struct Clock;\nimpl Clock { pub fn now() -> u64 { 0 } }\n",
    );
    ws.write("core.rs", "pub fn tick() -> u64 { crate::clock::now() }\n");
    ws.write("bin/tool.rs", "mod cli;\nfn main() {}\n");
    ws.write("bin/cli.rs", "pub fn run() {}\n");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "dependencies": [
                { "name": "extdep" },
                { "name": "otherdep", "rename": "renamed" },
                { "name": "my-dep" },
            ],
            "targets": [
                { "name": "x", "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
                { "name": "tool", "kind": ["bin"], "src_path": ws.src().join("bin/tool.rs").to_string_lossy() },
            ],
        }],
    });
    (ws, metadata)
}

type PrefixRole = fn(&str) -> ModuleBoundary;

/// Both builders that take an inline-call prefix, with `prefix` in that position, and the name each
/// refusal quotes. `confine_inline_call` permits the prefix in `crate::clock`, so `crate::core`'s
/// call reacts under either.
fn inline_prefix_roles() -> [(&'static str, PrefixRole); 2] {
    [
        ("must_not_call_inline", |p| {
            ModuleBoundary::in_crate("x")
                .module("crate::core")
                .must_not_call_inline(p)
                .because("r")
        }),
        ("confine_inline_call", |p| {
            ModuleBoundary::in_crate("x")
                .module("crate::clock")
                .confine_inline_call(p)
                .because("r")
        }),
    ]
}

fn check_prefix(
    metadata: &Value,
    boundary: ModuleBoundary,
) -> (Result<(), String>, Vec<Violation>) {
    let mut violations = Vec::new();
    let result = check_module_boundary(metadata, &boundary, &mut violations);
    (result, violations)
}

/// The prefix written correctly reacts on the call it names, under either builder.
#[test]
pub(super) fn an_inline_prefix_naming_a_module_reacts_on_its_call() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-module");
    let expected = Ok(vec!["crate::clock::now in crate::core".to_string()]);
    assert_every_prefix(&metadata, &["crate::clock", "crate::clock::now"], |_, _| {
        expected.clone()
    });
}

/// A misspelled `crate::` prefix names nothing, and is refused rather than judged clean.
#[test]
pub(super) fn a_misspelled_crate_prefix_is_refused_not_judged_clean() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-misspelled");
    assert_every_prefix(
        &metadata,
        &["crate::clcok", "crate::clock::nwo", "crate::cli::x"],
        |rule, prefix| {
            Err(crate::errors::unknown_inline_prefix_error(
                prefix, "x", rule,
            ))
        },
    );
}

/// A prefix written without its `crate::` root, where the rooted path names something the crate
/// declares, is refused with the rooted spelling as the repair — the one reading of an unconfirmed first
/// segment the text determines.
#[test]
pub(super) fn a_prefix_written_without_its_crate_root_is_refused_with_the_rooted_spelling() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-unrooted");
    assert_every_prefix(&metadata, &["clock", "clock::now"], |rule, prefix| {
        Err(crate::errors::unknown_inline_prefix_head_error(
            prefix,
            "x",
            rule,
            &format!("crate::{prefix}"),
        ))
    });
}

/// A first segment naming another crate is accepted whether or not the metadata confirms it: a sysroot
/// crate the manifest never declares, the package's own library named from its binary, and a dependency
/// whose crate name differs from its package name, which `--no-deps` metadata does not report.
#[test]
pub(super) fn a_first_segment_naming_another_crate_is_accepted() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-other-crate");
    assert_every_prefix(
        &metadata,
        &["proc_macro", "test", "x::core", "inilike::load", "my_dep"],
        |_, _| Ok(Vec::new()),
    );
}

/// A prefix outside the canonical spelling is refused before anything is read, suggesting it. The
/// sysroot and dependency spellings are the ones only this refusal reaches: what follows their head is
/// not read, so nothing after it would refuse them.
#[test]
pub(super) fn a_prefix_with_a_trailing_separator_is_refused() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-trailing");
    let suggestion = |prefix: &str| match prefix {
        "crate::clock::" => Some("crate::clock"),
        "::std::time::" => Some("::std::time"),
        "std::time::" => Some("std::time"),
        "extdep::api::" => Some("extdep::api"),
        _ => None,
    };
    assert_every_prefix(
        &metadata,
        &[
            "crate::clock::",
            "std::time::",
            "::std::time::",
            "extdep::api::",
            "my-dep",
            "self::clock",
            "Self::clock",
        ],
        |rule, prefix| {
            Err(crate::errors::non_canonical_inline_prefix_error(
                prefix,
                "x",
                rule,
                suggestion(prefix),
            ))
        },
    );
}

/// The precision half: a prefix naming an item, a raw-spelled module, a sysroot path, a dependency
/// under its local name, or a module only the binary declares is accepted, and a blank prefix keeps
/// its own refusal.
#[test]
pub(super) fn an_inline_prefix_naming_something_that_exists_is_accepted() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-exists");
    let accepted = [
        "crate::clock::now",
        "crate::r#clock",
        "crate::clock::Clock",
        "crate",
        "::std::time",
        "std::time",
        "core::time",
        "alloc::vec",
        "extdep",
        "extdep::api",
        "renamed::x",
        "my_dep::f",
        "crate::cli",
        "crate::cli::run",
    ];
    assert_every_prefix(&metadata, &accepted, |rule, prefix| {
        let (result, violations) = check_prefix(&metadata, inline_prefix_role(rule)(prefix));
        result.map(|()| findings_of(&violations))
    });
    assert_every_prefix(&metadata, &[" "], |rule, _| {
        Err(crate::errors::inline_empty_prefix_error("x", rule))
    });
}

/// Segments guibiao cannot read are not verified: past a sysroot crate or a dependency, whose
/// contents are another crate's; past an item of this crate, whose associated items are not collected;
/// and a first segment no metadata confirms whose `crate::` reading names nothing. A misspelling there
/// is accepted and matches nothing — a stated bound.
#[test]
pub(super) fn a_prefix_past_what_guibiao_reads_is_not_verified() {
    let (_ws, metadata) = inline_prefix_fixture("inline-prefix-unread");
    assert_every_prefix(
        &metadata,
        &[
            "std::tiem",
            "extdep::nosuch",
            "crate::clock::Clock::nwo",
            "clcok",
            "otherdep",
        ],
        |_, _| Ok(Vec::new()),
    );
}

/// An item a macro invocation defines is not in the item set, so a `crate::` prefix naming it is refused
/// as naming nothing, though the call it names compiles — a stated bound. The braced invocation is the row
/// only the macro body's own exclusion holds: its item stands directly in a brace group, where an item may.
#[test]
pub(super) fn a_prefix_naming_a_macro_generated_item_is_refused() {
    let mut wrong = Vec::new();
    for (form, invocation) in [
        ("parenthesized", "make!(pub fn stamp() -> u64 { 0 });"),
        ("braced", "make! { pub fn stamp() -> u64 { 0 } }"),
    ] {
        let ws = TempWorkspace::new(&format!("inline-prefix-macro-item-{form}"));
        ws.write("lib.rs", "pub mod clock;\npub mod core;\n");
        ws.write(
            "clock.rs",
            &format!("macro_rules! make {{ ($i:item) => {{ $i }}; }}\n{invocation}\n"),
        );
        ws.write(
            "core.rs",
            "pub fn tick() -> u64 { crate::clock::stamp() }\n",
        );
        let metadata = ws.metadata("x");
        for (rule, role) in inline_prefix_roles() {
            let (result, violations) = check_prefix(&metadata, role("crate::clock::stamp"));
            let want = Err(crate::errors::unknown_inline_prefix_error(
                "crate::clock::stamp",
                "x",
                rule,
            ));
            if result != want {
                wrong.push(format!("{form} {rule}: got {result:?} {violations:?}"));
            }
        }
    }
    assert!(wrong.is_empty(), "\n{}", wrong.join("\n"));
}

fn inline_prefix_role(rule: &str) -> PrefixRole {
    inline_prefix_roles()
        .into_iter()
        .find_map(|(name, role)| (name == rule).then_some(role))
        .expect("a role the table declares")
}

fn findings_of(violations: &[Violation]) -> Vec<String> {
    violations.iter().map(|v| v.finding.clone()).collect()
}

/// Judge every prefix under both builders against `expected(rule, prefix)` — the findings, or the
/// refusal — and fail once, listing every pair that disagreed.
fn assert_every_prefix(
    metadata: &Value,
    prefixes: &[&str],
    expected: impl Fn(&str, &str) -> Result<Vec<String>, String>,
) {
    let mut wrong = Vec::new();
    for (rule, role) in inline_prefix_roles() {
        for prefix in prefixes {
            let (result, violations) = check_prefix(metadata, role(prefix));
            let answer = result.map(|()| findings_of(&violations));
            let want = expected(rule, prefix);
            if answer != want {
                wrong.push(format!(
                    "{rule}({prefix:?}):\n   got {answer:?}\n  want {want:?}"
                ));
            }
        }
    }
    assert!(wrong.is_empty(), "\n{}", wrong.join("\n"));
}