guibiao 0.2.2

圭表 (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
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
//! White-box unit tests for the crate-private machinery — the baseline, the JSON
//! and text projections, and the source scanner. Black-box behavior (running
//! `check` against fixture workspaces) lives in `tests/dogfood.rs`.
use super::*;

fn test_id(target: &str, rule: &str, finding: &str) -> ViolationId {
    let finding = match finding.split_once('/') {
        Some((package, feature)) => crate::finding::CrateFact::feature(
            package.to_string(),
            feature.to_string(),
            DependencyKind::Normal,
        )
        .into_finding(),
        None => crate::finding::CrateFact::dependency(finding.to_string(), DependencyKind::Normal)
            .into_finding(),
    };
    ViolationId::new(target, rule, finding)
}

fn one_enforce_violation() -> Report {
    Report::new(vec![Violation::new(
        BoundaryKind::Crate,
        test_id("core", "deny external dependencies", "serde"),
        "core must stay dependency-light".to_string(),
        Severity::Enforce,
    )])
}

#[cfg(unix)]
#[test]
fn rust_files_does_not_recurse_into_a_symlinked_directory_cycle() {
    // A directory symlink pointing back at an ancestor would make a symlink-following walk recurse
    // forever (stack overflow). `rust_files` decides recursion from `file_type()` (no symlink
    // follow), so the cycle is not entered and the real source file is still found.
    use std::os::unix::fs::symlink;
    let dir = std::env::temp_dir().join(format!("guibiao-symlink-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("mkdir src");
    std::fs::write(src.join("lib.rs"), "// root\n").expect("write lib.rs");
    symlink(&src, src.join("loop")).expect("create a directory symlink cycle");
    let files = crate::module_scan::rust_files(&src);
    let _ = std::fs::remove_dir_all(&dir);
    let files = files.expect("rust_files must not error on a symlink cycle");
    assert_eq!(
        files.len(),
        1,
        "only the real source file; the symlinked directory must not be followed: {files:?}"
    );
}

#[cfg(unix)]
#[test]
fn rust_files_governs_a_symlinked_source_file() {
    // A symlink whose target is a real `.rs` file is compiled by rustc (once `mod`-declared) and
    // must be governed — it must NOT be dropped as a non-`is_file()` symlink, which would silently
    // miss its imports. Only the directory branch is symlink-blind (for cycle safety).
    use std::os::unix::fs::symlink;
    let dir = std::env::temp_dir().join(format!("guibiao-symlink-file-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    let ext = dir.join("external");
    std::fs::create_dir_all(&src).expect("mkdir src");
    std::fs::create_dir_all(&ext).expect("mkdir external");
    std::fs::write(src.join("lib.rs"), "// root\n").expect("write lib.rs");
    std::fs::write(ext.join("shared.rs"), "// shared\n").expect("write symlink target");
    symlink(ext.join("shared.rs"), src.join("shared.rs")).expect("symlink a source file in");
    let files = crate::module_scan::rust_files(&src);
    let _ = std::fs::remove_dir_all(&dir);
    let files = files.expect("rust_files must not error");
    assert_eq!(
        files.len(),
        2,
        "both the real file and the symlinked-in source file are governed: {files:?}"
    );
}

#[cfg(unix)]
#[test]
fn a_plain_child_reached_only_through_a_symlinked_directory_is_governed() {
    // `rust_files` deliberately never recurses into a symlinked directory (its own cycle guard,
    // see the sibling tests above), so a file that lives only behind one is absent from the
    // structural file list `governed_files` scans from. But `reachable_modules`'s live probe for
    // a plain child resolves the candidate path via `is_file`/`canonicalize`, which DO follow a
    // symlinked directory component — so before this fix, such a child was marked reachable and
    // even read/descended into, yet was absent from every `governed_files` output (neither the
    // structural iterator, which never walked it, nor `remapped`, since its naive path
    // structurally agreed with its own module path). Verified against a real `cargo check`: this
    // exact layout compiles `real_target/child.rs` as `crate::mymod::child` through the symlink.
    use std::os::unix::fs::symlink;
    let dir = std::env::temp_dir().join(format!("guibiao-symlinked-child-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("mkdir src");
    std::fs::create_dir_all(dir.join("real_target")).expect("mkdir real_target");
    std::fs::write(
        src.join("lib.rs"),
        "pub mod mymod;\npub mod secret { pub struct Thing; }\n",
    )
    .expect("write lib.rs");
    std::fs::write(src.join("mymod.rs"), "pub mod child;\n").expect("write mymod.rs");
    std::fs::write(
        dir.join("real_target").join("child.rs"),
        "use crate::secret::Thing;\n",
    )
    .expect("write real_target/child.rs");
    symlink(dir.join("real_target"), src.join("mymod")).expect("symlink src/mymod -> real_target");

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate::mymod")
        .must_not_import("crate::secret")
        .because("a symlinked-directory child must still be governed, not silently invisible");
    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);

    result.expect("a symlinked-directory-reached child is a valid, governable target");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::mymod");
    let file = violations[0]
        .file
        .as_deref()
        .expect("a module-import violation carries its source file");
    assert!(
        file.ends_with("child.rs"),
        "the violation must name the real file reached through the symlinked directory: {file}"
    );
}

#[cfg(unix)]
#[test]
fn a_symlinked_module_aliasing_an_unrelated_walked_file_is_still_governed_under_its_own_path() {
    // Round-6 regression in the fix above: `files_canon` compared CANONICAL (symlink-resolved)
    // identity, so a module reached through a symlinked directory that happens to alias the same
    // physical file as some OTHER, unrelated, genuinely-walked module was wrongly treated as
    // "already found by the structural iterator" merely because canon(candidate) == canon(some
    // files entry) — even though the candidate itself was never walked. Here `mod real;` is
    // backed directly by `src/real/mod.rs` (normally walked), and a SEPARATE `mod kernel;` is
    // backed by `src/kernel/mod.rs`, where `src/kernel` is a symlink to `src/real` (never walked,
    // since rust_files skips symlinked directories) — so canon(src/kernel/mod.rs) ==
    // canon(src/real/mod.rs) even though they are two distinct, separately-declared modules.
    // Verified against a real `cargo check`: both crate::real and crate::kernel compile as
    // distinct modules, each observing `use crate::secret::Thing;`. Comparing LITERAL (not
    // canonical) path identity closes this: two on-disk paths are never literally equal merely
    // because they resolve to the same target.
    use std::os::unix::fs::symlink;
    let dir = std::env::temp_dir().join(format!("guibiao-symlink-alias-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(src.join("real")).expect("mkdir src/real");
    std::fs::write(
        src.join("lib.rs"),
        "pub mod real;\npub mod kernel;\npub mod secret { pub struct Thing; }\n",
    )
    .expect("write lib.rs");
    std::fs::write(
        src.join("real").join("mod.rs"),
        "use crate::secret::Thing;\n",
    )
    .expect("write src/real/mod.rs");
    symlink("real", src.join("kernel")).expect("symlink src/kernel -> real");

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate::kernel")
        .must_not_import("crate::secret")
        .because(
            "a symlink-aliased module must be governed under its own path, not silently dropped",
        );
    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);

    result.expect(
        "crate::kernel is a valid, governable target even though it aliases crate::real's file",
    );
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::kernel");
}

#[test]
fn expand_use_tree_does_not_overflow_on_pathological_nesting() {
    // A pathologically brace-nested `use` must not overflow the stack. The depth cap bounds the
    // recursion and returns (truncated past the cap — the safe direction for adversarial input no
    // real, rustfmt-clean source reaches). The point of the test is that it terminates.
    let deep = format!("use {}b{};", "a::{".repeat(20_000), "}".repeat(20_000));
    let out = crate::module_scan::imported_module_paths(&deep, "crate::m", &[]);
    assert!(
        out.is_empty(),
        "past the depth cap the sub-tree is not expanded: {out:?}"
    );
}

#[test]
fn a_raw_identifier_use_does_not_swallow_the_following_real_use() {
    use crate::module_scan::imported_module_paths;
    // `r#use` is a valid raw identifier (a field here). `#` is not an identifier byte, so a naive
    // "the byte before `use` is not an ident byte" test would treat the `use` inside `r#use` as the
    // keyword, scan to the next `;`, and swallow the following real `use` — a false negative that
    // silently disables the import boundary. The observed imports must be identical to the same
    // source without the raw-identifier field, and must include the real import.
    let with_raw = "struct Config { r#use: bool }\nuse crate::secret::Thing;\n";
    let without = "struct Config { flag: bool }\nuse crate::secret::Thing;\n";
    let observed = imported_module_paths(with_raw, "crate::m", &[]);
    assert_eq!(
        observed,
        imported_module_paths(without, "crate::m", &[]),
        "an r#use field must not change which imports are observed"
    );
    assert!(
        !observed.is_empty(),
        "the real `use crate::secret::Thing` after an r#use field must still be observed: {observed:?}"
    );
}

#[test]
fn a_use_in_a_whitespace_spaced_macro_body_is_not_a_real_import() {
    use crate::module_scan::imported_module_paths;
    // Rust allows whitespace between a macro path and its `!` (`cfg_if ! { … }`). The body is a
    // macro-generated context, out of scope per the module-boundary spec, so its `use` must be
    // stripped — not observed as a real import (a false positive).
    let spaced = "cfg_if ! { use crate::secret::X; }\n";
    assert!(
        imported_module_paths(spaced, "crate::m", &[]).is_empty(),
        "a use inside a whitespace-spaced macro invocation body is macro-generated, not a real import"
    );
    // But a unary `!` on a real block after a keyword (`return !{ … }`) is NOT a macro — its block
    // is real code, and a `use` inside it must still be observed (guarding against a false negative
    // if the whitespace tolerance forgot the keyword check).
    let keyword_not = "pub fn f() -> bool { return !{ use crate::real::Y; true }; }\n";
    assert!(
        !imported_module_paths(keyword_not, "crate::m", &[]).is_empty(),
        "a use in a real block after `return !` must still be observed — a keyword is not a macro name"
    );
}

#[test]
fn a_submodule_file_named_lib_rs_is_governed_at_its_own_path() {
    // `lib.rs`/`main.rs` are segment-less only at the crate root. A declared submodule file
    // `foo/lib.rs` is `crate::foo::lib` (matching rustc and 渾儀's descent), so a boundary on it
    // resolves and reacts instead of raising a false inline-module exit-2 or scanning the wrong
    // module.
    let (result, violations) = run_module_check(
        "submodule-named-lib",
        &[
            ("lib.rs", "pub mod foo;\npub mod sink;\n"),
            ("foo.rs", "pub mod lib;\n"),
            ("foo/lib.rs", "use crate::sink;\n"),
            ("sink.rs", "// target\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::foo::lib")
            .must_not_import("crate::sink")
            .because("foo::lib must not touch sink"),
    );
    assert!(
        result.is_ok(),
        "the submodule file must resolve, not raise a false exit-2: {result:?}"
    );
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::foo::lib");
    assert_eq!(violations[0].rule, "module must not import");
    assert_eq!(violations[0].finding, "crate::sink");
    let id = violations[0].id();
    let key = id
        .finding_key()
        .expect("a production violation has structured identity");
    assert_eq!(key.namespace(), "guibiao");
    assert_eq!(key.code(), "imported_path");
    assert_eq!(
        key.fields().collect::<Vec<_>>(),
        vec![("path", "crate::sink")]
    );
}

/// An unreadable governed source file must surface as a scan error (exit 2),
/// not a silent skip that could hide a real module-boundary violation. Unix
/// only (permission-based) and self-calibrating: it skips under a privileged
/// user (e.g. root in CI), where mode 0 is still readable, rather than
/// false-passing.
#[cfg(unix)]
#[test]
fn unreadable_governed_file_is_a_scan_error() {
    use std::os::unix::fs::PermissionsExt;

    let dir = std::env::temp_dir().join(format!("guibiao-unreadable-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("create temp src");
    let file = src.join("lib.rs");
    std::fs::write(&file, "use crate::forbidden::Thing;\n").expect("write governed file");
    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o000))
        .expect("drop read permission");

    // Self-calibrating root guard: if mode 0 is still readable, permissions do
    // not bite here, so the premise cannot hold — skip rather than false-pass.
    if std::fs::read_to_string(&file).is_ok() {
        let _ = std::fs::remove_dir_all(&dir);
        return;
    }

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate")
        .must_not_import("crate::forbidden")
        .because("the test module must not import the forbidden module");

    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);

    let _ = std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644));
    let _ = std::fs::remove_dir_all(&dir);

    assert!(
        result.is_err(),
        "an unreadable governed file must be a scan error, not a silent skip"
    );
}

/// An unreadable governed *directory* must surface as a scan error (exit 2), the
/// same "cannot judge, not nothing to judge" rule as an unreadable file: a skipped
/// subtree could hide a real module-boundary violation. Unix only and
/// self-calibrating (skips under a privileged user where mode 0 is still readable).
#[cfg(unix)]
#[test]
fn unreadable_governed_directory_is_a_scan_error() {
    use std::os::unix::fs::PermissionsExt;

    let dir = std::env::temp_dir().join(format!("guibiao-unreadable-dir-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("create temp src");
    std::fs::write(src.join("lib.rs"), "// nothing\n").expect("write lib.rs");
    let sub = src.join("sub");
    std::fs::create_dir_all(&sub).expect("create sub dir");
    std::fs::write(sub.join("inner.rs"), "use crate::forbidden::Thing;\n").expect("write inner");
    std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o000))
        .expect("drop dir read/exec permission");

    // Self-calibrating root guard: if the directory is still traversable, the
    // premise cannot hold — skip rather than false-pass.
    if std::fs::read_dir(&sub).is_ok() {
        let _ = std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755));
        let _ = std::fs::remove_dir_all(&dir);
        return;
    }

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate")
        .must_not_import("crate::forbidden")
        .because("the test module must not import the forbidden module");

    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);

    let _ = std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755));
    let _ = std::fs::remove_dir_all(&dir);

    assert!(
        result.is_err(),
        "an unreadable governed directory must be a scan error, not a silent skip"
    );
}

/// A module whose name is a raw identifier (`mod r#type;`, file `type.rs`) must be
/// governable and its forbidden imports observed — exercising the canonicalization
/// in `check_module_boundary` end to end. The boundary is declared with the *plain*
/// form (`crate::type`) and still matches the raw-identifier source.
#[test]
fn a_raw_identifier_module_is_governed_and_its_import_observed() {
    let dir = std::env::temp_dir().join(format!("guibiao-rawid-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("create temp src");
    std::fs::write(src.join("lib.rs"), "pub mod r#type;\n").expect("write lib.rs");
    std::fs::write(src.join("type.rs"), "use crate::r#mod::Thing;\n").expect("write type.rs");

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate::type")
        .must_not_import("crate::mod")
        .because("a raw-identifier module must be governable");

    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);

    assert!(
        result.is_ok(),
        "a raw-identifier module must be found, not an unknown-module error: {result:?}"
    );
    assert_eq!(
        violations.len(),
        1,
        "the forbidden import from inside the raw-identifier module must be observed: {violations:?}"
    );
    assert_eq!(violations[0].target, "crate::type");
    assert_eq!(violations[0].finding, "crate::mod::Thing");
}

#[test]
fn module_boundary_uses_the_package_target_src_path() {
    let dir = std::env::temp_dir().join(format!("guibiao-custom-lib-path-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).expect("create temp crate");
    let root = dir.join("lib.rs");
    std::fs::write(&root, "pub mod kernel;\n").expect("write custom lib root");
    std::fs::write(dir.join("kernel.rs"), "use crate::io::Sink;\n").expect("write custom module");

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
            "targets": [{
                "kind": ["lib"],
                "src_path": root.to_string_lossy().into_owned()
            }]
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate::kernel")
        .must_not_import("crate::io")
        .because("module boundaries must scan the compiled source root");

    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);

    assert!(
        result.is_ok(),
        "a custom [lib] path must not be misresolved to manifest_dir/src: {result:?}"
    );
    assert_eq!(
        violations.len(),
        1,
        "the forbidden import under the custom source root must be observed"
    );
    assert_eq!(violations[0].finding, "crate::io::Sink");
}

#[test]
fn path_remapped_module_is_followed_not_governed_via_a_conventional_orphan() {
    // rustc ground truth: `#[path = "weird.rs"] pub mod kernel;` compiles `weird.rs` as
    // `crate::kernel` (verified with a real `cargo build`), never the same-named conventional
    // orphan `kernel.rs`. The boundary must react on the REAL target's import, naming it as the
    // offending file, and must never react on the orphan's (different) import — a same-named
    // orphan is not compiled, so its content must never surface as this module's finding.
    let (result, violations) = run_module_check(
        "path-remap-boundary",
        &[
            ("lib.rs", "#[path = \"weird.rs\"]\npub mod kernel;\n"),
            ("weird.rs", "use crate::projection::Thing;\n"),
            ("kernel.rs", "use crate::projection::Wrong;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::projection")
            .because("closing the #[path]-following divergence from 渾儀/漏刻"),
    );

    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::kernel");
    assert_eq!(
        violations[0].finding, "crate::projection::Thing",
        "the real target's import is observed, never the orphan's: {violations:?}"
    );
    let file = violations[0]
        .file
        .as_deref()
        .expect("a module-import violation carries its source file");
    assert!(
        file.ends_with("weird.rs"),
        "the violation names the real #[path] target, not the conventional orphan: {file}"
    );
}

/// An unconditional `#[path = "…"]` preceding an INLINE module header is not a no-op: it
/// relocates the base directory the inline body's OWN file-form children resolve from, exactly
/// like a file-form `#[path]`. Verified against a real `cargo check`: `#[path = "thread_files"]
/// pub mod thread { pub mod local_data; }` compiles `thread_files/local_data.rs` as
/// `crate::thread::local_data`, with no `src/thread/` directory at all — the naive
/// (non-relocated) location `thread/local_data.rs` does not even exist. Before this fix the
/// scanner treated the preceding `#[path]` as a pure no-op and always looked in the naive
/// location, silently finding nothing and leaving the real file's imports unobserved.
#[test]
fn an_unconditional_path_on_an_inline_module_relocates_its_own_file_form_children() {
    let (result, violations) = run_module_check(
        "inline-path-relocate",
        &[
            (
                "lib.rs",
                "#[path = \"thread_files\"]\npub mod thread {\n    pub mod local_data;\n}\n\
                     pub mod secret { pub struct Thing; }\n",
            ),
            ("thread_files/local_data.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::thread")
            .must_not_import("crate::secret")
            .because("an inline module's #[path] must relocate its own children, not no-op"),
    );
    result.expect("the relocated child must be a valid, governable target");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::thread");
    let file = violations[0]
        .file
        .as_deref()
        .expect("a module-import violation carries its source file");
    assert!(
        file.ends_with("thread_files/local_data.rs")
            || file.ends_with("thread_files\\local_data.rs"),
        "the violation must name the #[path]-relocated file, not a naive thread/local_data.rs: {file}"
    );
}

/// An inline `mod kernel { … }` is reachable but owns no source file, so it cannot
/// be a governed target (targets are file-based). The reaction must fail loud (exit 2)
/// with a *self-describing* error that names the inline cause — not the misleading
/// "not found among the reachable modules", which would suggest a typo. A genuinely
/// unknown module still gets the "not found" message.
#[test]
fn an_inline_module_target_is_a_self_describing_constitution_error() {
    let dir = std::env::temp_dir().join(format!("guibiao-inline-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("create temp src");
    std::fs::write(
            src.join("lib.rs"),
            "pub mod kernel { use crate::projection::Thing; }\npub mod projection { pub struct Thing; }\n",
        )
        .expect("write lib.rs");

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "app",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });

    let inline = ModuleBoundary::in_crate("app")
        .module("crate::kernel")
        .must_not_import("crate::projection")
        .because("the kernel must not import a projection");
    let mut violations = Vec::new();
    let inline_err = check_module_boundary(&metadata, &inline, &mut violations)
        .expect_err("an inline target must be a constitution error");
    // Assert against the single-source constructor, not a brittle substring: the
    // inline target reports the inline cause, never the unknown-module message.
    assert_eq!(
        inline_err,
        inline_module_target_error("crate::kernel", "app", "kernel")
    );
    assert_ne!(inline_err, unknown_module_error("crate::kernel", "app"));

    // A genuinely unknown module path still gets the unknown-module message.
    let typo = ModuleBoundary::in_crate("app")
        .module("crate::ghost")
        .must_not_import("crate::projection")
        .because("typo");
    let typo_err = check_module_boundary(&metadata, &typo, &mut violations)
        .expect_err("an unknown module is a constitution error");
    let _ = std::fs::remove_dir_all(&dir);
    assert_eq!(typo_err, unknown_module_error("crate::ghost", "app"));
}

/// The inline-target constitution error must hold **even when a same-named conventional orphan
/// file** sits beside the inline body. Rust compiles the inline body and never the orphan, so
/// governing the orphan (and silently missing the inline body's imports) is a false negative —
/// the one forbidden bug, and the inline twin of the `#[path]` orphan-shadow hazard. The orphan
/// must not make the inline target look file-backed.
#[test]
fn an_inline_target_with_a_same_named_orphan_file_is_still_a_constitution_error() {
    let (result, _) = run_module_check(
        "inline-orphan",
        &[
            ("lib.rs", "pub mod kernel { use crate::secret::Thing; }\n"),
            // Orphan: Rust never compiles this as `crate::kernel` (the inline body is it).
            ("kernel.rs", "// clean — no forbidden import\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::secret")
            .because("the kernel must not import a secret"),
    );
    let err = result.expect_err(
        "an inline target must stay the inline constitution error even with a same-named \
             orphan file — governing the orphan and missing the inline body is the forbidden \
             false negative, never a silent pass",
    );
    assert_eq!(
        err,
        inline_module_target_error("crate::kernel", "x", "kernel")
    );
}

/// An orphan beside an inline module contributes **no phantom child module**: the orphan is
/// not compiled, so its own `mod` declarations name no reachable module. Governing such a
/// phantom child is a not-found constitution error, never a silent pass over the orphan's file.
#[test]
fn an_orphan_beside_an_inline_module_contributes_no_phantom_child() {
    let (result, _) = run_module_check(
        "inline-phantom",
        &[
            ("lib.rs", "pub mod kernel { }\n"),
            ("kernel.rs", "pub mod deep;\n"), // orphan's declaration — phantom
            ("kernel/deep.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel::deep")
            .must_not_import("crate::secret")
            .because("deep must not import a secret"),
    );
    let err = result.expect_err("a phantom child of an orphan is not a reachable module");
    assert_eq!(err, unknown_module_error("crate::kernel::deep", "x"));
}

/// Only inline-occupied files are excluded: a genuinely file-backed module (`mod real;` +
/// `real.rs`) is still governed, its imports observed — proving the exclusion is not
/// over-broad.
#[test]
fn a_file_backed_module_is_still_governed() {
    let (result, violations) = run_module_check(
        "file-backed",
        &[
            ("lib.rs", "pub mod real;\n"),
            ("real.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::real")
            .must_not_import("crate::secret")
            .because("real must not import a secret"),
    );
    result.expect("a file-backed module is a valid, governable target");
    assert!(
        !violations.is_empty(),
        "the file-backed module's forbidden import must still be observed"
    );
}

/// A path declared **both** file-form (`mod kernel;`) and inline (`mod kernel { … }`) — which in
/// valid source arises only under mutually-exclusive `#[cfg]` — is NOT inline-only, so its
/// conventional file stays governed. This pins that the inline-only exclusion leaves the
/// existing cfg-blind lexical bound exactly as it was (never turning it into an inline error).
#[test]
fn a_cfg_dual_declared_module_keeps_governing_its_conventional_file() {
    let (result, violations) = run_module_check(
        "cfg-dual",
        &[
            (
                "lib.rs",
                "#[cfg(feature = \"k\")]\npub mod kernel;\n\
                     #[cfg(not(feature = \"k\"))]\npub mod kernel { }\n",
            ),
            ("kernel.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::secret")
            .because("kernel must not import a secret"),
    );
    result.expect("a cfg-dual-declared module keeps its conventional file as a valid target");
    assert!(
        !violations.is_empty(),
        "the conventional file must still be observed — the cfg-blind bound is unchanged"
    );
}

/// Stated bound (not a fix): a package that builds a lib AND a bin observes its whole `src/`
/// under one conventional-path tree, so both roots resolve to `crate` and there are no
/// per-target module graphs. A submodule declared inline in one root and file-backed in the
/// other governs the file-backed one; the inline body's imports are NOT observed. Closing it
/// needs per-target graphs (distinguishing the lib crate's `crate::shared` from the bin's) —
/// beyond the conventional-path scanner. Recorded here and in `module-boundary`, never a silent
/// claim of cleanliness.
#[test]
fn a_cross_root_same_named_submodule_is_a_documented_bound() {
    let (result, violations) = run_module_check(
        "cross-root-submodule",
        &[
            ("lib.rs", "pub mod shared { use crate::forbidden::X; }\n"),
            ("main.rs", "pub mod shared;\nfn main() {}\n"),
            ("shared.rs", "// clean — the bin root's shared module\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::shared")
            .must_not_import("crate::forbidden")
            .because("shared must not import forbidden"),
    );
    result.expect("a file-backed shared (via the bin root) is a valid target");
    assert!(
        violations.is_empty(),
        "documented lib+bin bound: the lib root's inline `mod shared` body is not observed \
             (shared.rs is governed instead) — recorded, not silently claimed clean: {violations:?}"
    );
}

/// A `#[cfg_attr(cond, path = …)]` IS recognized as a (conditional) remap, the same
/// stated `#[path]` bound as the separate `#[cfg(cond)] #[path = …]` spelling. Not recognizing it
/// would govern the conventionally-named file — a cfg-blind mishandling that is a
/// false POSITIVE when the cfg path is active (rustc compiles the remap target, not the
/// conventional file) and, when no conventional file exists, a silent false NEGATIVE (the real
/// remapped source never scanned). The remapped module is out of scope: a boundary on it
/// fails loud (exit 2, "cannot judge") rather than guessing a file, and the conventional file is
/// not silently governed as the wrong module.
#[test]
fn a_cfg_attr_wrapped_path_is_recognized_as_a_remap() {
    let (result, _violations) = run_module_check(
        "cfg-attr-path",
        &[
            (
                "lib.rs",
                "#[cfg_attr(unix, path = \"weird.rs\")]\npub mod foo;\n",
            ),
            ("foo.rs", "use crate::forbidden::Y;\n"),
            ("weird.rs", "// the cfg(unix) remap target, clean\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::foo")
            .must_not_import("crate::forbidden")
            .because("foo must not import forbidden"),
    );
    // crate::foo is a remapped module, out of scope — so a boundary anchored on it is a constitution
    // error (exit 2), matching a direct `#[path]` remap. The conventional foo.rs is NOT governed as
    // crate::foo (no false positive on the active-cfg configuration, no silent guess).
    assert!(
        result.is_err(),
        "a cfg_attr-remapped module is out of scope; a boundary on it must fail loud, not guess \
         the conventional file"
    );
}

/// Run a module boundary against a synthetic one-package workspace whose `src`
/// holds `files` (each `(relative path, contents)`), under a unique temp dir keyed
/// by `name`. Returns the check result and the collected violations.
fn run_module_check(
    name: &str,
    files: &[(&str, &str)],
    boundary: ModuleBoundary,
) -> (Result<(), String>, Vec<Violation>) {
    let dir = std::env::temp_dir().join(format!("guibiao-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    for (rel, contents) in files {
        let path = src.join(rel);
        std::fs::create_dir_all(path.parent().expect("file has a parent"))
            .expect("create src dirs");
        std::fs::write(&path, contents).expect("write source file");
    }
    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);
    (result, violations)
}

/// Like [`run_module_check`], but with declared dependencies in the synthesized `cargo metadata`
/// package — needed by the strict-external inline confinement, whose head ladder matches a bare
/// head against declared dependency import identifiers. Each dep is `(name, rename)`: `rename` is
/// the Cargo `pkg = { package = "…" }` alias when `Some` (the `-`→`_` fold is applied by the
/// reader under test, so pass names verbatim).
fn run_module_check_with_deps(
    name: &str,
    files: &[(&str, &str)],
    deps: &[(&str, Option<&str>)],
    boundary: ModuleBoundary,
) -> (Result<(), String>, Vec<Violation>) {
    let dir = std::env::temp_dir().join(format!("guibiao-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    for (rel, contents) in files {
        let path = src.join(rel);
        std::fs::create_dir_all(path.parent().expect("file has a parent"))
            .expect("create src dirs");
        std::fs::write(&path, contents).expect("write source file");
    }
    let manifest = dir.join("Cargo.toml");
    let dependencies: Vec<serde_json::Value> = deps
        .iter()
        .map(|(dep_name, rename)| match rename {
            Some(rename) => serde_json::json!({ "name": dep_name, "rename": rename }),
            None => serde_json::json!({ "name": dep_name }),
        })
        .collect();
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": dependencies,
        }]
    });
    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);
    (result, violations)
}

fn restrict_kernel_to_types(governed: &str, allowed: &[&str]) -> ModuleBoundary {
    ModuleBoundary::in_crate("x")
        .module(governed)
        .restrict_imports_to(allowed.to_vec())
        .because("the kernel may import only the allowed modules")
}

#[test]
fn restrict_imports_to_flags_an_import_outside_the_allowlist() {
    let (result, violations) = run_module_check(
        "restrict-outside",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::io::Sink;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::kernel");
    assert_eq!(violations[0].finding, "crate::io::Sink");
}

#[test]
fn a_module_violation_carries_its_offending_file() {
    // The offending import sits in kernel.rs; the violation names that source file so an
    // agent knows where to repair — a faithful byproduct of the scan, not a new observation.
    let (result, violations) = run_module_check(
        "module-file",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::io::Sink;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    let file = violations[0]
        .file
        .as_deref()
        .expect("a module-import violation carries its source file");
    assert!(
        file.ends_with("kernel.rs"),
        "file names the offending source: {file}"
    );
}

#[test]
fn a_module_backed_by_two_files_yields_one_violation_with_a_file() {
    // `crate` is backed by both lib.rs and main.rs (a lib+bin package); the same forbidden
    // import in each must still collapse to exactly one violation (the file is attached
    // after collapsing by identity, never a de-dup key), and that one carries a file.
    let (result, violations) = run_module_check(
        "module-two-files",
        &[
            ("lib.rs", "use crate::forbidden::Thing;\n"),
            ("main.rs", "use crate::forbidden::Thing;\nfn main() {}\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_import("crate::forbidden")
            .because("crate must not import forbidden"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "two files of one module collapse to one violation: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate::forbidden::Thing");
    assert!(
        violations[0].file.is_some(),
        "the surviving violation carries a representative file"
    );
}

#[test]
fn restrict_imports_to_is_clean_within_the_allowlist() {
    let (result, violations) = run_module_check(
        "restrict-within",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::types::Id;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(violations.is_empty(), "{violations:?}");
}

#[test]
fn restrict_imports_to_allows_the_governed_modules_own_subtree() {
    // The exact module (`crate::kernel`), a descendant, and a `self::` import all
    // resolve within the governed subtree and are not outward edges — so none need
    // to be listed in the allowlist.
    let (result, violations) = run_module_check(
        "restrict-ownsubtree",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            (
                "kernel.rs",
                "use crate::kernel;\nuse crate::kernel::detail::Thing;\nuse self::other::Thing2;\n",
            ),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(violations.is_empty(), "own-subtree imports: {violations:?}");
}

#[test]
fn restrict_imports_to_with_an_empty_allowlist_forbids_outward_imports() {
    let (result, violations) = run_module_check(
        "restrict-empty",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::types::Id;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &[]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::types::Id");
}

#[test]
fn restrict_imports_to_does_not_treat_a_prefix_colliding_sibling_as_allowed() {
    // The `::`-delimited containment must not let `crate::types_extra` ride in on the
    // `crate::types` allowlist entry — the headline regression guard.
    let (result, violations) = run_module_check(
        "restrict-sibling",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            (
                "kernel.rs",
                "use crate::types::Id;\nuse crate::types_extra::Y;\n",
            ),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "only the sibling violates: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate::types_extra::Y");
}

#[test]
fn restrict_imports_to_never_flags_an_external_import() {
    let (result, violations) = run_module_check(
        "restrict-external",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use serde::Deserialize;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &[]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "externals are out of scope: {violations:?}"
    );
}

#[test]
fn restrict_imports_to_governs_a_super_reaching_outward_import() {
    let (result, violations) = run_module_check(
        "restrict-super",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use super::other::Thing;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(
        violations[0].finding, "crate::other::Thing",
        "super:: resolves to an absolute outward path that is governed"
    );
}

#[test]
fn restrict_imports_to_canonicalizes_a_raw_identifier_allowlist_entry() {
    let (result, violations) = run_module_check(
        "restrict-rawid",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::r#type::Thing;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::r#type"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "the raw-id entry canonicalizes to match the import: {violations:?}"
    );
}

#[test]
fn restrict_imports_to_on_the_crate_root_is_a_constitution_error() {
    // The crate root has no outward internal edge, so the rule could never react —
    // fail loud (exit 2), never silently pass.
    let (result, _violations) = run_module_check(
        "restrict-crate",
        &[("lib.rs", "use crate::anything::X;\n")],
        restrict_kernel_to_types("crate", &["crate::types"]),
    );
    let err = result.expect_err("governing `crate` must be a constitution error");
    assert_eq!(err, restrict_imports_to_on_crate_error("x"));
}

#[test]
fn restrict_imports_to_honors_warn_severity_and_its_distinct_label() {
    let (result, violations) = run_module_check(
        "restrict-warn",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::io::Sink;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .restrict_imports_to(["crate::types"])
            .warn()
            .because("the kernel should import only types"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].severity, Severity::Warn);
    // A label distinct from `must not import`, so baseline identity does not collide.
    assert_eq!(violations[0].rule, "restrict imports to");
}

fn protect_internal_from(importer: &str) -> ModuleBoundary {
    ModuleBoundary::in_crate("x")
        .module("crate::internal")
        .must_not_be_imported_by(importer)
        .because("internal is private to its layer")
}

#[test]
fn must_not_be_imported_by_flags_the_forbidden_importer_only() {
    let (result, violations) = run_module_check(
        "inbound-basic",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\npub mod api;\n"),
            ("internal.rs", "// protected\n"),
            ("http.rs", "use crate::internal::Secret;\n"),
            ("api.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    // Only crate::http is beneath the forbidden importer; crate::api imports internal
    // too but is outside crate::http, so it is clean.
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::internal");
    assert_eq!(violations[0].finding, "crate::http");
    assert_eq!(violations[0].rule, "module must not be imported by");
}

#[test]
fn must_not_be_imported_by_flags_an_inline_module_importer() {
    // `crate::http` is an INLINE module in lib.rs, not a file. Its `use crate::internal`
    // is attributed to the inline importer `crate::http`, not the file's module `crate`, so the
    // forbidden inbound edge reacts. File-granular attribution would test `crate` against
    // the forbidden importer, pre-filter the file out, and silently miss the edge.
    let (result, violations) = run_module_check(
        "inbound-inline-importer",
        &[
            (
                "lib.rs",
                "pub mod internal;\nmod http { use crate::internal::Secret; }\n",
            ),
            ("internal.rs", "// protected\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::internal");
    assert_eq!(violations[0].finding, "crate::http");
}

#[test]
fn must_not_be_imported_by_applies_beneath_the_importer() {
    let (result, violations) = run_module_check(
        "inbound-beneath-importer",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            ("http.rs", "pub mod v1;\n"),
            ("http/v1.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(
        violations[0].finding, "crate::http::v1",
        "the importer beneath crate::http is named"
    );
}

#[test]
fn must_not_be_imported_by_applies_beneath_the_protected_module() {
    let (result, violations) = run_module_check(
        "inbound-beneath-protected",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            ("http.rs", "use crate::internal::deep::Thing;\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "an import beneath the protected module violates: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate::http");
}

#[test]
fn must_not_be_imported_by_ignores_prefix_colliding_siblings_on_both_sides() {
    let (result, violations) = run_module_check(
        "inbound-collision",
        &[
            (
                "lib.rs",
                "pub mod internal;\npub mod http;\npub mod httpx;\n",
            ),
            ("internal.rs", "// protected\n"),
            // forbidden importer is crate::http; crate::http imports a sibling of the
            // protected module (internal_util), which is clean.
            ("http.rs", "use crate::internal_util::X;\n"),
            // crate::httpx is a sibling of the forbidden importer; importing internal
            // is clean.
            ("httpx.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "::-delimited containment must not match siblings on either side: {violations:?}"
    );
}

#[test]
fn must_not_be_imported_by_does_not_flag_the_protected_modules_own_subtree() {
    let (result, violations) = run_module_check(
        "inbound-own-subtree",
        &[
            ("lib.rs", "pub mod a;\n"),
            ("a.rs", "pub mod b;\n"),
            // crate::a::b is the protected module; it imports its own subtree and sits
            // beneath the forbidden importer crate::a — but a module importing itself
            // is not an inbound edge, so it is clean.
            ("a/b.rs", "use crate::a::b::detail::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::a::b")
            .must_not_be_imported_by("crate::a")
            .because("a::b is private"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "the protected module's own subtree is not an importer: {violations:?}"
    );
}

#[test]
fn must_not_be_imported_by_ignores_external_imports() {
    let (result, violations) = run_module_check(
        "inbound-external",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            ("http.rs", "use serde::Deserialize;\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "externals are out of scope: {violations:?}"
    );
}

#[test]
fn must_not_be_imported_by_crate_forbids_every_outside_importer() {
    let (result, violations) = run_module_check(
        "inbound-x-crate",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            ("http.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate"),
    );
    assert!(result.is_ok(), "{result:?}");
    // Forbidding importer `crate` means nobody outside internal's own subtree may
    // import it; crate::http violates, internal's own files stay clean.
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::http");
}

#[test]
fn must_not_be_imported_by_on_the_crate_root_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "inbound-m-crate",
        &[("lib.rs", "pub mod http;\n"), ("http.rs", "// nothing\n")],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_not_be_imported_by("crate::http")
            .because("the crate root cannot be protected this way"),
    );
    let err = result.expect_err("protecting `crate` must be a constitution error");
    assert_eq!(err, must_not_be_imported_by_on_crate_error("x"));
}

#[test]
fn must_not_be_imported_by_dedups_multiple_imports_from_one_importer() {
    let (result, violations) = run_module_check(
        "inbound-dedup",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            (
                "http.rs",
                "use crate::internal::A;\nuse crate::internal::B;\n",
            ),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "one offending importer module yields one violation: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate::http");
}

#[test]
fn must_not_be_imported_by_honors_warn_severity() {
    let (result, violations) = run_module_check(
        "inbound-warn",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            ("http.rs", "use crate::internal::Secret;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::internal")
            .must_not_be_imported_by("crate::http")
            .warn()
            .because("internal should be private"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].severity, Severity::Warn);
}

#[test]
fn must_not_be_imported_by_projects_its_importer() {
    let constitution = Constitution::new("p").boundary(
        ModuleBoundary::in_crate("app")
            .module("crate::internal")
            .must_not_be_imported_by("crate::http")
            .because("internal is private to its layer"),
    );

    let text = constitution_text(&constitution);
    assert!(
        text.contains("must not be imported by crate::http"),
        "{text}"
    );

    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(
        doc["boundaries"][0]["rule"],
        "module must not be imported by"
    );
    assert_eq!(doc["boundaries"][0]["target"], "crate::internal");
    // The declared forbidden importer projects as `importer`; no `forbidden`/`only`.
    assert_eq!(doc["boundaries"][0]["importer"], "crate::http");
    assert!(doc["boundaries"][0]["forbidden"].is_null());
    assert!(doc["boundaries"][0]["only"].is_null());
}

#[test]
fn must_not_be_imported_by_unknown_protected_module_is_a_constitution_error() {
    // The protected-module validation must fire for the inbound rule too: an unknown
    // `m` is exit 2 before any scan, never a silent clean.
    let (result, _violations) = run_module_check(
        "inbound-unknown-m",
        &[("lib.rs", "pub mod http;\n"), ("http.rs", "// nothing\n")],
        ModuleBoundary::in_crate("x")
            .module("crate::nope")
            .must_not_be_imported_by("crate::http")
            .because("typo target"),
    );
    let err = result.expect_err("an unknown protected module is a constitution error");
    assert_eq!(err, unknown_module_error("crate::nope", "x"));
}

#[test]
fn must_not_be_imported_by_inline_protected_module_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "inbound-inline-m",
        &[
            (
                "lib.rs",
                "pub mod kernel { pub struct K; }\npub mod http;\n",
            ),
            ("http.rs", "// nothing\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_be_imported_by("crate::http")
            .because("inline target"),
    );
    let err = result.expect_err("an inline protected module is a constitution error");
    assert_eq!(
        err,
        inline_module_target_error("crate::kernel", "x", "kernel")
    );
}

#[test]
fn must_not_be_imported_by_matches_a_raw_identifier_importer() {
    // The forbidden importer is declared with a raw identifier; the importing file's
    // module canonicalizes to the same path, so the violation still fires (guards the
    // canonicalization lockstep against a false negative).
    let (result, violations) = run_module_check(
        "inbound-rawid-importer",
        &[
            ("lib.rs", "pub mod internal;\npub mod r#async;\n"),
            ("internal.rs", "// protected\n"),
            ("async.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate::r#async"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::async");
}

#[test]
fn must_not_be_imported_by_protects_a_raw_identifier_module() {
    let (result, violations) = run_module_check(
        "inbound-rawid-protected",
        &[
            ("lib.rs", "pub mod r#type;\npub mod http;\n"),
            ("type.rs", "// protected\n"),
            ("http.rs", "use crate::r#type::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::r#type")
            .must_not_be_imported_by("crate::http")
            .because("type is private"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::type");
    assert_eq!(violations[0].finding, "crate::http");
}

#[test]
fn must_not_be_imported_by_flags_a_mod_rs_backed_importer() {
    let (result, violations) = run_module_check(
        "inbound-modrs",
        &[
            ("lib.rs", "pub mod internal;\npub mod http;\n"),
            ("internal.rs", "// protected\n"),
            ("http/mod.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate::http"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::http");
}

#[test]
fn must_not_be_imported_by_orders_multiple_offenders_deterministically() {
    let (result, violations) = run_module_check(
        "inbound-multi",
        &[
            (
                "lib.rs",
                "pub mod internal;\npub mod zeta;\npub mod alpha;\n",
            ),
            ("internal.rs", "// protected\n"),
            ("zeta.rs", "use crate::internal::Secret;\n"),
            ("alpha.rs", "use crate::internal::Secret;\n"),
        ],
        protect_internal_from("crate"),
    );
    assert!(result.is_ok(), "{result:?}");
    let findings: Vec<&str> = violations.iter().map(|v| v.finding.as_str()).collect();
    assert_eq!(
        findings,
        ["crate::alpha", "crate::zeta"],
        "multiple offenders are sorted deterministically"
    );
}

#[test]
fn must_not_be_imported_by_dedups_an_importer_backed_by_lib_and_main() {
    // A lib+bin package has both `lib.rs` and `main.rs` at module `crate`. With
    // `must_not_be_imported_by("crate")`, both root files importing the protected
    // module would push `crate` twice — the spec's dedup must collapse it to one.
    let (result, violations) = run_module_check(
        "inbound-lib-and-main",
        &[
            (
                "lib.rs",
                "pub mod internal;\nuse crate::internal::Secret;\n",
            ),
            ("main.rs", "use crate::internal::Secret;\n"),
            ("internal.rs", "// protected\n"),
        ],
        protect_internal_from("crate"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "one offending importer module, even when backed by two root files: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate");
    // The collapsed inbound violation still carries a representative file (the inbound path
    // also collects (key, file) before de-duplication), so the two-file case is locked on
    // the inbound rule, not only the outbound one.
    assert!(
        violations[0].file.is_some(),
        "the surviving inbound violation carries a representative file"
    );
}

#[test]
fn must_not_import_dedups_a_finding_across_subtree_files() {
    // crate::kernel spans kernel.rs + kernel/sub.rs; both import the forbidden module.
    // The same finding must be reported once, not once per file.
    let (result, violations) = run_module_check(
        "dedup-mni-subtree",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "pub mod sub;\nuse crate::forbidden::X;\n"),
            ("kernel/sub.rs", "use crate::forbidden::X;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::forbidden")
            .because("kernel must not import forbidden"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "one violation per distinct finding: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate::forbidden::X");
}

#[test]
fn restrict_imports_to_dedups_a_finding_across_subtree_files() {
    let (result, violations) = run_module_check(
        "dedup-rit-subtree",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "pub mod sub;\nuse crate::io::Sink;\n"),
            ("kernel/sub.rs", "use crate::io::Sink;\n"),
        ],
        restrict_kernel_to_types("crate::kernel", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "one violation per distinct finding: {violations:?}"
    );
    assert_eq!(violations[0].finding, "crate::io::Sink");
}

#[test]
fn outbound_dedup_collapses_identical_findings_but_keeps_distinct_ones() {
    // Two subtree files: one imports X, the other imports X (duplicate) and Y.
    // Result must be {X, Y} — the identical finding collapsed, the distinct one kept.
    let (result, violations) = run_module_check(
        "dedup-distinct",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "pub mod sub;\nuse crate::forbidden::X;\n"),
            (
                "kernel/sub.rs",
                "use crate::forbidden::X;\nuse crate::forbidden::Y;\n",
            ),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::forbidden")
            .because("kernel must not import forbidden"),
    );
    assert!(result.is_ok(), "{result:?}");
    let findings: Vec<&str> = violations.iter().map(|v| v.finding.as_str()).collect();
    assert_eq!(
        findings,
        ["crate::forbidden::X", "crate::forbidden::Y"],
        "{violations:?}"
    );
    // And no two violations share an identity (target, rule, finding).
    let mut ids: Vec<_> = violations
        .iter()
        .map(|v| (&v.target, &v.rule, &v.finding))
        .collect();
    let before = ids.len();
    ids.sort();
    ids.dedup();
    assert_eq!(ids.len(), before, "no duplicate violation identities");
}

#[test]
fn restrict_imports_to_does_not_flag_an_over_popped_super() {
    // `crate::a` over-pops with `super::super`; the path names no internal module, so
    // it must not be observed — and must not be mistaken for an outward edge that the
    // allowlist would flag (the regression this guards).
    let (result, violations) = run_module_check(
        "restrict-super-overflow",
        &[
            ("lib.rs", "pub mod a;\n"),
            ("a.rs", "use super::super::other::X;\n"),
        ],
        restrict_kernel_to_types("crate::a", &["crate::types"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "an over-popped super is not an outward edge: {violations:?}"
    );
}

#[test]
fn baseline_round_trips_through_json() {
    let report = one_enforce_violation();
    let json = Baseline::of(&report).to_json();
    let parsed = Baseline::from_json(&json).expect("a written baseline parses");
    assert!(
        parsed.contains(&report.violations[0]),
        "round-trip must preserve the violation identity"
    );
}

#[test]
fn from_json_rejects_malformed_and_unknown_version() {
    assert!(Baseline::from_json("not json").is_err());
    assert!(Baseline::from_json(r#"{"version":3,"violations":[]}"#).is_err());
    assert!(
        Baseline::from_json(r#"{"violations":[]}"#).is_err(),
        "a missing version must be an error, not a silent empty baseline"
    );
}

#[test]
fn a_baselined_enforce_violation_does_not_fail() {
    let mut report = one_enforce_violation();
    let baseline = Baseline::of(&report);
    apply_baseline(&mut report, &baseline);
    assert!(report.violations[0].baselined);
    assert_eq!(
        Outcome::Violations(report).exit_code(),
        0,
        "a fully baselined run must not fail"
    );
}

#[test]
fn a_new_enforce_violation_fails_against_a_baseline() {
    let baseline = Baseline::from_json(
            r#"{"version":1,"violations":[{"target":"core","rule":"deny external dependencies","finding":"other"}]}"#,
        )
        .unwrap();
    let mut report = one_enforce_violation();
    apply_baseline(&mut report, &baseline);
    assert!(
        !report.violations[0].baselined,
        "serde is not in the baseline"
    );
    assert_eq!(Outcome::Violations(report).exit_code(), 1);
}

#[test]
fn stale_finds_entries_with_no_current_match() {
    let report = one_enforce_violation();
    let baseline = Baseline::from_json(
            r#"{"version":1,"violations":[{"target":"core","rule":"deny external dependencies","finding":"gone"}]}"#,
        )
        .unwrap();
    let stale = baseline.stale(&report);
    assert_eq!(stale.len(), 1);
    assert_eq!(stale[0].finding, "gone");
}

#[test]
fn report_json_projects_a_violation_with_its_kind() {
    let json = report_json(&Outcome::Violations(one_enforce_violation()), &[], None);
    let doc: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
    assert_eq!(doc["outcome"], "violations");
    assert_eq!(doc["exit_code"], 1);
    let violation = &doc["violations"][0];
    assert_eq!(violation["kind"], "crate");
    assert_eq!(violation["finding"], "serde");
    assert_eq!(violation["finding_key"]["namespace"], "guibiao");
    assert_eq!(violation["finding_key"]["code"], "dependency");
    assert_eq!(violation["finding_key"]["fields"]["package"], "serde");
    assert_eq!(violation["severity"], "enforce");
    assert_eq!(violation["baselined"], false);
    // `reason` is the repair hint; there is no separate field.
    assert!(violation["reason"].as_str().is_some_and(|r| !r.is_empty()));
    assert!(doc.get("repair_hint").is_none());
}

#[test]
fn report_json_renders_clean_and_constitution_error() {
    let clean: serde_json::Value =
        serde_json::from_str(&report_json(&Outcome::Clean, &[], None)).unwrap();
    assert_eq!(clean["outcome"], "clean");
    assert_eq!(clean["exit_code"], 0);
    assert_eq!(clean["violations"].as_array().unwrap().len(), 0);
    assert!(clean.get("coverage").is_none(), "no coverage when None");

    let error: serde_json::Value = serde_json::from_str(&report_json(
        &Outcome::ConstitutionError("boom".into()),
        &[],
        None,
    ))
    .unwrap();
    assert_eq!(error["outcome"], "constitution_error");
    assert_eq!(error["exit_code"], 2);
    assert_eq!(error["error"], "boom");
}

#[test]
fn report_json_reflects_baseline_and_stale_in_gate() {
    let mut report = one_enforce_violation();
    let baseline = Baseline::of(&report);
    apply_baseline(&mut report, &baseline);
    // A baseline entry that no current violation matches is stale.
    let stale = vec![test_id("core", "deny external dependencies", "gone")];
    let doc: serde_json::Value =
        serde_json::from_str(&report_json(&Outcome::Violations(report), &stale, None)).unwrap();
    assert_eq!(doc["exit_code"], 0, "a fully baselined run does not fail");
    assert_eq!(doc["violations"][0]["baselined"], true);
    assert_eq!(doc["stale_baseline"][0]["finding"], "gone");
    assert!(doc["stale_baseline"][0]["finding_key"].is_object());

    let legacy = Baseline::from_json(
        r#"{"version":1,"violations":[{
            "target":"core","rule":"deny external dependencies","finding":"legacy-gone"
        }]}"#,
    )
    .unwrap();
    let legacy_stale: Vec<ViolationId> = legacy
        .stale(&Report::empty())
        .into_iter()
        .cloned()
        .collect();
    let legacy_doc: serde_json::Value =
        serde_json::from_str(&report_json(&Outcome::Clean, &legacy_stale, None)).unwrap();
    assert_eq!(legacy_doc["stale_baseline"][0]["finding"], "legacy-gone");
    assert_eq!(legacy_doc["stale_baseline"][0]["finding_key"], Value::Null);
}

#[test]
fn report_json_includes_coverage_when_present() {
    let coverage = Coverage {
        total: 3,
        uncovered: vec!["memory".to_string()],
    };
    let doc: serde_json::Value =
        serde_json::from_str(&report_json(&Outcome::Clean, &[], Some(&coverage))).unwrap();
    assert_eq!(doc["coverage"]["workspace_crates"], 3);
    assert_eq!(doc["coverage"]["uncovered"][0], "memory");
}

#[test]
fn external_classification_treats_any_non_null_source_as_external() {
    // A path/internal dep has a null `source`; registry, git, and alternative
    // (sparse) registry deps all have a non-null source and must be classified
    // external. The sparse case is the regression guard: a fixed `registry+`/
    // `git+` prefix list would silently pass an alternative `sparse+` registry.
    let package = serde_json::json!({
        "dependencies": [
            { "name": "internal", "source": null, "kind": null },
            {
                "name": "crates_io",
                "source": "registry+https://github.com/rust-lang/crates.io-index",
                "kind": null
            },
            { "name": "git_dep", "source": "git+https://example.com/x", "kind": null },
            { "name": "alt_sparse", "source": "sparse+https://my.registry/index/", "kind": null },
            {
                "name": "a_dev",
                "source": "registry+https://github.com/rust-lang/crates.io-index",
                "kind": "dev"
            },
        ]
    });
    assert_eq!(
        external_dependencies(&package, DependencyKind::Normal),
        vec![
            "alt_sparse".to_string(),
            "crates_io".to_string(),
            "git_dep".to_string(),
        ],
        "every non-null-source normal dep is external (incl. a sparse alt \
             registry); the null-source internal dep and the dev dep are excluded",
    );
}

#[test]
fn a_crate_violation_reports_no_file() {
    // A crate-dependency violation is an edge in the dependency graph (a manifest
    // relation), not a source line, so its `file` is a faithful `None`.
    let metadata = serde_json::json!({
        "packages": [{
            "name": "core",
            "dependencies": [
                {
                    "name": "serde",
                    "source": "registry+https://github.com/rust-lang/crates.io-index",
                    "kind": null
                }
            ],
        }]
    });
    let boundary = CrateBoundary::crate_("core")
        .deny_external_dependencies()
        .because("core stays dependency-light");
    let mut violations = Vec::new();
    let result = check_crate_boundary(&metadata, &[], &boundary, &mut violations);
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].kind, BoundaryKind::Crate);
    assert_eq!(violations[0].finding, "serde");
    assert!(
        violations[0].file.is_none(),
        "a crate-dependency violation has no single source file"
    );
}

#[test]
fn dedup_keeps_the_more_severe_of_duplicate_violations() {
    // The same crate rule declared once `warn` and once `enforce` on one crate — a plausible
    // mid-promotion state — flags the same dependency twice with equal `(target, rule, finding)`
    // identity but different severity. Deduping must keep the ENFORCE reaction: keeping the
    // first-seen `warn` would collapse to an advisory and drop exit-1 to exit-0 (a false
    // negative). Verified in both declaration orders (the fix is order-independent).
    let metadata = serde_json::json!({
        "packages": [{
            "name": "core",
            "dependencies": [
                { "name": "serde", "source": "registry+x", "kind": null }
            ],
        }]
    });
    let warn = || {
        CrateBoundary::crate_("core")
            .deny_external_dependencies()
            .warn()
            .because("observing before enforcing")
    };
    let enforce = || {
        CrateBoundary::crate_("core")
            .deny_external_dependencies()
            .because("core stays dependency-light")
    };
    for (first, second) in [(warn(), enforce()), (enforce(), warn())] {
        let constitution = Constitution::new("mid-promotion")
            .boundary(first)
            .boundary(second);
        let outcome = evaluate(&constitution, &metadata);
        let Outcome::Violations(report) = &outcome else {
            panic!("expected violations, got {outcome:?}");
        };
        assert_eq!(
            report.violations.len(),
            1,
            "duplicates collapse to one: {report:?}"
        );
        assert_eq!(
            report.violations[0].severity,
            Severity::Enforce,
            "the more severe reaction is kept"
        );
        assert_eq!(
            outcome.exit_code(),
            1,
            "an enforce violation fails the reaction"
        );
    }
}

#[test]
fn dependency_kind_selects_which_table_is_observed() {
    // `serde` is a normal dep; `proptest` is a dev-dep; `cc` is a build-dep.
    let package = serde_json::json!({
        "dependencies": [
            { "name": "serde", "source": "registry+x", "kind": null },
            { "name": "proptest", "source": "registry+x", "kind": "dev" },
            { "name": "cc", "source": "registry+x", "kind": "build" },
        ]
    });
    let deny = Rule::DenyExternalDependencies { allowed: vec![] };
    // Default (normal) sees only serde; dev sees only proptest; build only cc. The dev/build
    // findings carry a kind suffix so the same dep name in two tables stays a distinct finding.
    assert_eq!(
        deny.findings(&package, &[], DependencyKind::Normal),
        vec!["serde".to_string()]
    );
    assert_eq!(
        deny.findings(&package, &[], DependencyKind::Dev),
        vec!["proptest (dev)".to_string()]
    );
    assert_eq!(
        deny.findings(&package, &[], DependencyKind::Build),
        vec!["cc (build)".to_string()]
    );
}

#[test]
fn the_same_dep_in_two_tables_yields_distinct_findings() {
    // The one forbidden bug for the dependency family: `serde` from a git source in BOTH the
    // normal and the dev table, governed by same-rule boundaries differing only by kind, must
    // not collapse to one `(target, rule, finding)` — else baselining the normal violation
    // masks a new dev one. The kind suffix keeps them distinct.
    let package = serde_json::json!({
        "dependencies": [
            { "name": "serde", "source": "git+https://x", "kind": null },
            { "name": "serde", "source": "git+https://x", "kind": "dev" },
        ]
    });
    let rule = Rule::RestrictDependencySourcesTo {
        allowed: vec![SourceKind::Registry],
    };
    let normal = rule.findings(&package, &[], DependencyKind::Normal);
    let dev = rule.findings(&package, &[], DependencyKind::Dev);
    assert_eq!(normal, vec!["serde".to_string()]);
    assert_eq!(dev, vec!["serde (dev)".to_string()]);
    assert_ne!(normal, dev, "same dep in two tables must not collide");
}

#[test]
fn workspace_member_names_are_the_no_deps_packages() {
    // With `--no-deps`, `packages` is exactly the workspace members.
    let metadata = serde_json::json!({
        "packages": [ { "name": "core" }, { "name": "adapters" } ]
    });
    assert_eq!(
        workspace_member_names(&metadata),
        vec!["adapters".to_string(), "core".to_string()],
    );
}

#[test]
fn workspace_rule_flags_only_unlisted_workspace_members() {
    // Deps: two workspace members (core, adapters), one external (serde), and one
    // path dependency that is NOT a workspace member (outside).
    let package = serde_json::json!({
        "dependencies": [
            { "name": "core", "source": null, "kind": null },
            { "name": "adapters", "source": null, "kind": null },
            {
                "name": "serde",
                "source": "registry+https://github.com/rust-lang/crates.io-index",
                "kind": null
            },
            { "name": "outside", "source": null, "kind": null },
        ]
    });
    let workspace = vec!["core".to_string(), "adapters".to_string()];

    // Restrict to [core]: adapters is an unlisted workspace member → flagged;
    // serde (external) and outside (path, non-member) are ignored.
    let restrict = Rule::RestrictWorkspaceDependenciesTo {
        allowed: vec!["core".to_string()],
    };
    assert_eq!(
        restrict.findings(&package, &workspace, DependencyKind::Normal),
        vec!["adapters".to_string()],
    );

    // Empty allowlist forbids every workspace member, still ignoring external and
    // the non-member path dependency.
    let forbid_all = Rule::RestrictWorkspaceDependenciesTo { allowed: vec![] };
    assert_eq!(
        forbid_all.findings(&package, &workspace, DependencyKind::Normal),
        vec!["adapters".to_string(), "core".to_string()],
    );
}

#[test]
fn workspace_rule_never_flags_a_crates_own_self_referential_dev_dependency() {
    // Round-11 finding: Cargo genuinely permits (and real projects use, e.g. a doctest/
    // dogfooding pattern) a crate declaring itself as a `[dev-dependencies]` path dependency
    // on itself (`main = { path = "." }`), and `cargo metadata --no-deps` emits this edge
    // verbatim (verified against real cargo). `workspace_member_names` trivially includes the
    // crate's own name, and `dependencies()` matches by bare package name with no
    // self-exclusion — so before this fix, a `forbid_all_workspace_dependencies` /
    // `restrict_workspace_dependencies_to` boundary declared on that crate flagged its own
    // legitimate self-dev-dependency as an "unlisted workspace dependency", even though a
    // self-dependency can never be an inter-crate layering violation (there is no OTHER crate
    // to leak across a boundary to).
    let package = serde_json::json!({
        "name": "main",
        "dependencies": [
            { "name": "main", "source": null, "kind": "dev" },
        ]
    });
    let workspace = vec!["main".to_string()];
    let forbid_all = Rule::RestrictWorkspaceDependenciesTo { allowed: vec![] };
    assert_eq!(
        forbid_all.findings(&package, &workspace, DependencyKind::Dev),
        Vec::<String>::new(),
        "a crate's own self-referential dev-dependency must never be flagged as an unlisted \
         workspace dependency"
    );
}

#[test]
fn no_dependency_rule_ever_flags_a_crates_own_self_referential_dependency() {
    // Round-12 finding: round 11 excluded a crate's own self-referential dependency (Cargo's
    // legal `[dev-dependencies] main = { path = "." }` doctest/dogfooding pattern) ONLY inside
    // Rule::RestrictWorkspaceDependenciesTo's own arm — leaving the IDENTICAL false positive live
    // in every sibling rule reading the same `dependencies()` / `dependencies_with_disallowed_source()`
    // observation (ForbidDependencyOn, RestrictDependenciesTo, RestrictDependencySourcesTo, and
    // the feature-granularity rules when the boundary happens to name the target's own crate).
    // A self-dependency is never a CROSS-crate concern any of these rules exist to govern, so the
    // exclusion is now at the shared observation source (`cargo_metadata.rs::is_self_dependency`),
    // closing every rule at once rather than one at a time.
    let package = serde_json::json!({
        "name": "main",
        "dependencies": [
            { "name": "main", "source": null, "kind": "dev", "features": ["x"] },
        ]
    });
    let workspace = vec!["main".to_string()];

    assert_eq!(
        Rule::ForbidDependencyOn {
            crates: vec!["main".to_string()]
        }
        .findings(&package, &workspace, DependencyKind::Dev),
        Vec::<String>::new(),
        "ForbidDependencyOn must not flag the crate's own self-dependency"
    );
    assert_eq!(
        Rule::RestrictDependenciesTo {
            allowed: vec!["serde".to_string()]
        }
        .findings(&package, &workspace, DependencyKind::Dev),
        Vec::<String>::new(),
        "RestrictDependenciesTo must not flag the crate's own self-dependency"
    );
    assert_eq!(
        Rule::RestrictDependencySourcesTo {
            allowed: vec![SourceKind::Registry]
        }
        .findings(&package, &workspace, DependencyKind::Dev),
        Vec::<String>::new(),
        "RestrictDependencySourcesTo must not flag the crate's own self-dependency's Path source"
    );
    assert_eq!(
        Rule::RestrictFeaturesOf {
            crate_: "main".to_string(),
            allowed: vec![]
        }
        .findings(&package, &workspace, DependencyKind::Dev),
        Vec::<String>::new(),
        "RestrictFeaturesOf must not observe the crate's own self-dependency's declared features"
    );
    assert_eq!(
        Rule::ForbidFeaturesOf {
            crate_: "main".to_string(),
            forbidden: vec!["x".to_string()]
        }
        .findings(&package, &workspace, DependencyKind::Dev),
        Vec::<String>::new(),
        "ForbidFeaturesOf must not observe the crate's own self-dependency's declared features"
    );
}

#[test]
fn coverage_counts_a_module_only_covered_crate_as_covered() {
    let members = vec!["app".to_string(), "core".to_string(), "memory".to_string()];
    let constitution = Constitution::new("c")
        .boundary(
            CrateBoundary::crate_("core")
                .forbid_all_workspace_dependencies()
                .because("core is independent"),
        )
        .boundary(
            ModuleBoundary::in_crate("app")
                .module("crate::kernel")
                .must_not_import("crate::projection")
                .because("layering"),
        );
    let coverage = coverage_from(members, &constitution);
    assert_eq!(coverage.total, 3);
    // `app` is covered by the module boundary, `core` by the crate boundary;
    // only `memory` has no boundary at all.
    assert_eq!(coverage.uncovered, vec!["memory".to_string()]);
}

fn mixed_constitution() -> Constitution {
    Constitution::new("my-project")
        .boundary(
            CrateBoundary::crate_("my-core")
                .deny_external_dependencies()
                .allow_external(["serde"])
                .because("my-core must stay dependency-light"),
        )
        .boundary(
            CrateBoundary::crate_("my-core")
                .forbid_dependency_on(["my-adapters"])
                .because("the core must not depend on adapters"),
        )
        .boundary(
            ModuleBoundary::in_crate("my-app")
                .module("crate::domain")
                .must_not_import("crate::http")
                .warn()
                .because("the domain must not import the HTTP layer"),
        )
}

#[test]
fn constitution_text_projects_every_boundary_with_its_parameters() {
    let text = constitution_text(&mixed_constitution());
    assert!(
        text.contains("Constitution: my-project  (3 boundaries)"),
        "{text}"
    );
    assert!(text.contains("crate my-core"), "{text}");
    assert!(
        text.contains("deny external dependencies (allow: serde)"),
        "{text}"
    );
    assert!(text.contains("forbid dependency on: my-adapters"), "{text}");
    assert!(text.contains("module crate::domain in my-app"), "{text}");
    assert!(text.contains("must not import crate::http"), "{text}");
    // Severity and reason both surface.
    assert!(
        text.contains("[warn]") && text.contains("[enforce]"),
        "{text}"
    );
    assert!(
        text.contains("the domain must not import the HTTP layer"),
        "{text}"
    );
}

#[test]
fn constitution_json_projects_boundaries_with_kinds_and_parameters() {
    let json = constitution_json(&mixed_constitution());
    let doc: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
    assert_eq!(doc["constitution"], "my-project");
    let boundaries = doc["boundaries"].as_array().expect("array");
    assert_eq!(boundaries.len(), 3);

    // Crate boundary with an allowlist.
    assert_eq!(boundaries[0]["kind"], "crate");
    assert_eq!(boundaries[0]["target"], "my-core");
    assert_eq!(boundaries[0]["rule"], "deny external dependencies");
    assert_eq!(boundaries[0]["severity"], "enforce");
    assert_eq!(boundaries[0]["allowed"][0], "serde");

    // Forbid-dependency-on carries its crate list.
    assert_eq!(boundaries[1]["rule"], "forbid dependency on");
    assert_eq!(boundaries[1]["crates"][0], "my-adapters");

    // Module boundary: target is the module path (report convention), plus crate
    // and forbidden import.
    assert_eq!(boundaries[2]["kind"], "module");
    assert_eq!(boundaries[2]["target"], "crate::domain");
    assert_eq!(boundaries[2]["crate"], "my-app");
    assert_eq!(boundaries[2]["forbidden"], "crate::http");
    assert_eq!(boundaries[2]["severity"], "warn");
}

#[test]
fn an_empty_constitution_projects_cleanly() {
    let constitution = Constitution::new("fresh");
    let text = constitution_text(&constitution);
    assert!(
        text.contains("Constitution: fresh  (0 boundaries)"),
        "{text}"
    );
    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(doc["boundaries"].as_array().unwrap().len(), 0);
}

#[test]
fn restrict_to_projects_its_allowlist() {
    let constitution = Constitution::new("p")
        .boundary(
            CrateBoundary::crate_("a")
                .restrict_dependencies_to(["serde", "types"])
                .because("a may depend on only serde and types"),
        )
        .boundary(
            CrateBoundary::crate_("b")
                .restrict_dependencies_to::<[&str; 0], &str>([])
                .because("b must depend on nothing"),
        );

    let text = constitution_text(&constitution);
    assert!(
        text.contains("restrict dependencies to: serde, types"),
        "{text}"
    );
    assert!(text.contains("restrict dependencies to nothing"), "{text}");

    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(doc["boundaries"][0]["rule"], "restrict dependencies to");
    // A distinct key (`only`, not deny-external's `allowed`) for the closed set.
    assert_eq!(doc["boundaries"][0]["only"][0], "serde");
    assert!(doc["boundaries"][0]["allowed"].is_null());
    // The empty allowlist is still emitted, as `[]`.
    assert_eq!(doc["boundaries"][1]["only"].as_array().unwrap().len(), 0);
}

// A synthesized `cargo metadata --no-deps` package mirroring the source-kind probe:
// a registry dep, a path dep, a plain git dep, an optional git dep, a renamed git dep
// (real name `serde`, local alias `mydep`), a `{ git, version }` dep, an inherited
// workspace git dep (cargo flattens the source into the member as `git+…`), and a git
// dev-dependency. Every `source` string is exactly what cargo emits (verified).
fn source_package() -> Value {
    serde_json::json!({
        "dependencies": [
            {
                "name": "crates_io",
                "source": "registry+https://github.com/rust-lang/crates.io-index",
                "kind": null
            },
            { "name": "localdep", "source": null, "kind": null },
            { "name": "gitdep", "source": "git+https://example.invalid/a.git", "kind": null },
            {
                "name": "optgit",
                "source": "git+https://example.invalid/b.git",
                "kind": null,
                "optional": true
            },
            {
                "name": "serde",
                "rename": "mydep",
                "source": "git+https://example.invalid/c.git",
                "kind": null
            },
            { "name": "gitver", "source": "git+https://example.invalid/d.git", "kind": null },
            {
                "name": "inherited",
                "source": "git+https://example.invalid/e.git",
                "kind": null
            },
            { "name": "devgit", "source": "git+https://example.invalid/f.git", "kind": "dev" },
        ]
    })
}

#[test]
fn source_rule_flags_every_git_source_outside_a_registry_or_path_allowlist() {
    let package = source_package();
    // Permit [Registry, Path]: every git-sourced normal dep is flagged — the plain
    // git dep, the OPTIONAL git dep (declared regardless of feature state), the
    // `{ git, version }` dep (a stated hygiene bound — it would publish, yet its
    // declared source is git), and the INHERITED workspace git dep (cargo flattens
    // the git source into the member). A RENAMED git dep is reported by its REAL
    // package name `serde`, not its alias `mydep`. The registry and path deps pass;
    // the git DEV-dep is not in the Normal-scoped surface.
    let rule = Rule::RestrictDependencySourcesTo {
        allowed: vec![SourceKind::Registry, SourceKind::Path],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec![
            "gitdep".to_string(),
            "gitver".to_string(),
            "inherited".to_string(),
            "optgit".to_string(),
            "serde".to_string(),
        ],
        "every declared git source is flagged (optional/version/inherited included), \
             by real package name, while registry+path pass and the dev git dep is unscoped",
    );
}

#[test]
fn source_rule_registry_only_flags_a_path_dependency() {
    // Permit only [Registry]: the path dep is now flagged too (alongside every git
    // dep), documenting that Path is a governed source, not a silent exemption.
    let package = source_package();
    let rule = Rule::RestrictDependencySourcesTo {
        allowed: vec![SourceKind::Registry],
    };
    let findings = rule.findings(&package, &[], DependencyKind::Normal);
    assert!(findings.contains(&"localdep".to_string()), "{findings:?}");
    assert!(!findings.contains(&"crates_io".to_string()), "{findings:?}");
}

#[test]
fn source_rule_is_clean_when_every_governed_source_is_allowed() {
    // A package whose only normal deps are registry + path, under [Registry, Path].
    let package = serde_json::json!({
        "dependencies": [
            { "name": "crates_io", "source": "registry+https://x", "kind": null },
            { "name": "localdep", "source": null, "kind": null },
        ]
    });
    let rule = Rule::RestrictDependencySourcesTo {
        allowed: vec![SourceKind::Registry, SourceKind::Path],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "all-registry-or-path is clean under a [Registry, Path] allowlist",
    );
}

#[test]
fn source_rule_does_not_observe_a_patch_redirect_declared_as_registry() {
    // The declared-vs-resolved bound: a registry dep that `[patch]` would redirect to
    // git still declares `source = registry+…` in `--no-deps` metadata, so it
    // classifies Registry and does NOT violate a [Registry] allowlist. Observing the
    // resolved git source is cargo-deny's `[sources]` lane, not a Tianheng capability.
    let package = serde_json::json!({
        "dependencies": [
            { "name": "patched", "source": "registry+https://x", "kind": null },
        ]
    });
    let rule = Rule::RestrictDependencySourcesTo {
        allowed: vec![SourceKind::Registry],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "the declared layer does not observe [patch]; correct — [patch] never blocks publish",
    );
}

#[test]
fn source_rule_scopes_to_the_dependency_kind() {
    // Only the git dev-dep exists; a Normal-scoped boundary does not observe it, a
    // Dev-scoped one does.
    let package = serde_json::json!({
        "dependencies": [
            { "name": "devgit", "source": "git+https://x", "kind": "dev" },
        ]
    });
    let rule = Rule::RestrictDependencySourcesTo {
        allowed: vec![SourceKind::Registry],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "a dev git dep is outside a Normal-scoped surface",
    );
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Dev),
        vec!["devgit (dev)".to_string()],
        "a Dev-scoped boundary governs the dev table",
    );
}

#[test]
fn source_rule_empty_allowlist_forbids_every_dependency_by_source() {
    let package = serde_json::json!({
        "dependencies": [
            { "name": "crates_io", "source": "registry+https://x", "kind": null },
            { "name": "localdep", "source": null, "kind": null },
            { "name": "gitdep", "source": "git+https://x", "kind": null },
        ]
    });
    let rule = Rule::RestrictDependencySourcesTo { allowed: vec![] };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec![
            "crates_io".to_string(),
            "gitdep".to_string(),
            "localdep".to_string(),
        ],
        "an empty source allowlist forbids every dependency regardless of source",
    );
}

#[test]
fn source_boundary_absent_target_is_a_constitution_error() {
    // Parity with the other crate rules: a boundary on a crate not in the workspace is
    // a constitution error (→ exit 2), never a silent pass.
    let metadata = serde_json::json!({ "packages": [{ "name": "present" }] });
    let boundary = CrateBoundary::crate_("absent")
        .restrict_dependency_sources_to([SourceKind::Registry])
        .because("absent must publish to crates.io");
    let mut violations = Vec::new();
    let result = check_crate_boundary(&metadata, &[], &boundary, &mut violations);
    assert!(
        result.is_err(),
        "an absent target crate must be a constitution error, not exit 0/1",
    );
}

#[test]
fn source_boundary_carries_its_severity_and_gates_against_the_baseline() {
    // A source violation folds into the shared report identity (target, rule,
    // finding) and honors severity + baseline exactly as the sibling rules do.
    let metadata = serde_json::json!({
        "packages": [{
            "name": "infra",
            "dependencies": [
                { "name": "gitdep", "source": "git+https://x", "kind": null },
            ],
        }]
    });
    // Warn severity: the violation is recorded but must not fail the reaction.
    let warn = CrateBoundary::crate_("infra")
        .restrict_dependency_sources_to([SourceKind::Registry, SourceKind::Path])
        .warn()
        .because("infra should publish; a git source is advisory here");
    let mut violations = Vec::new();
    check_crate_boundary(&metadata, &[], &warn, &mut violations).unwrap();
    assert_eq!(violations.len(), 1);
    assert_eq!(violations[0].severity, Severity::Warn);
    assert_eq!(violations[0].rule, "restrict dependency sources to");
    assert_eq!(violations[0].finding, "gitdep");
    assert!(
        violations[0].file.is_none(),
        "a source violation is a manifest relation, not a source line",
    );

    // Enforce + baseline parity: the same violation, once baselined, does not fail.
    let enforce = CrateBoundary::crate_("infra")
        .restrict_dependency_sources_to([SourceKind::Registry, SourceKind::Path])
        .because("infra must publish to crates.io, so no git source");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &enforce, &mut v).unwrap();
    let mut report = Report::new(v);
    let baseline = Baseline::of(&report);
    apply_baseline(&mut report, &baseline);
    assert_eq!(
        Outcome::Violations(report).exit_code(),
        0,
        "a fully baselined source violation does not fail the reaction",
    );
}

#[test]
fn source_boundary_projects_its_allowed_sources() {
    let constitution = Constitution::new("p")
        .boundary(
            CrateBoundary::crate_("infra")
                .restrict_dependency_sources_to([SourceKind::Registry, SourceKind::Path])
                .because("infra must publish to crates.io, so its manifest declares no git"),
        )
        .boundary(
            CrateBoundary::crate_("locked")
                .restrict_dependency_sources_to([])
                .because("locked must declare no dependencies at all"),
        );

    let text = constitution_text(&constitution);
    assert!(
        text.contains("restrict dependency sources to: registry, path"),
        "{text}"
    );
    assert!(
        text.contains("forbid all dependencies (by source)"),
        "{text}"
    );

    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(
        doc["boundaries"][0]["rule"],
        "restrict dependency sources to"
    );
    assert_eq!(doc["boundaries"][0]["allowed_sources"][0], "registry");
    assert_eq!(doc["boundaries"][0]["allowed_sources"][1], "path");
    // The empty allowlist is still emitted, as `[]`.
    assert_eq!(
        doc["boundaries"][1]["allowed_sources"]
            .as_array()
            .unwrap()
            .len(),
        0
    );
}

// ---- Feature-granularity crate rules (declared-not-resolved) --------------------------

// A `cargo metadata --no-deps` package declaring the dependency `C` under a variety of
// edges. Field names are exactly what cargo emits on a dependency edge: `features` (the
// authored list) and `uses_default_features` (the default toggle; absent ⇒ default-on).
fn feature_package() -> Value {
    serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "source": "registry+https://x",
                "kind": null,
                "features": ["extra"],
                "uses_default_features": true
            },
        ]
    })
}

#[test]
fn declared_feature_is_observed() {
    // WHEN the target declares C = { features = ["extra"] } → the declared set contains `extra`.
    let package = feature_package();
    assert!(
        declared_features(&package, "C", DependencyKind::Normal).contains(&"extra".to_string()),
        "an authored feature is observed",
    );
}

#[test]
fn default_features_are_the_default_pseudo_feature() {
    // WHEN C is declared without `default-features = false` (uses_default_features true, or
    // the field absent) → the declared set contains the `default` pseudo-feature.
    let with_flag = serde_json::json!({
        "dependencies": [
            { "name": "C", "kind": null, "uses_default_features": true },
        ]
    });
    let absent_flag = serde_json::json!({
        "dependencies": [
            { "name": "C", "kind": null },
        ]
    });
    assert!(
        declared_features(&with_flag, "C", DependencyKind::Normal).contains(&"default".to_string()),
        "uses_default_features=true ⇒ default is requested",
    );
    assert!(
        declared_features(&absent_flag, "C", DependencyKind::Normal)
            .contains(&"default".to_string()),
        "an absent uses_default_features field ⇒ default-on ⇒ default is requested",
    );
}

#[test]
fn disabling_default_features_drops_the_default_pseudo_feature() {
    // WHEN C = { default-features = false, features = ["extra"] } → declared set is
    // { extra }, without `default`.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["extra"],
                "uses_default_features": false
            },
        ]
    });
    assert_eq!(
        declared_features(&package, "C", DependencyKind::Normal),
        vec!["extra".to_string()],
        "default-features = false drops the default pseudo-feature",
    );
}

#[test]
fn transitive_enables_are_not_chased() {
    // A MEANINGFUL test of the rejected "expand through C's `[features]` graph" layer: the
    // metadata carries C's expansion evidence (a `resolve.nodes` entry for C where `full`
    // has resolved into `unstable`), yet the target declares only `full`. A `forbid C/unstable`
    // rule must stay clean and a `forbid C/full` rule must fire — proving the rule reads the
    // target's AUTHORED request, never C's expanded/resolved graph. If `findings` were changed
    // to fold in the transitive `unstable` (via C's graph or the resolve node), the first
    // assertion below would flip to a `C/unstable` finding and fail.
    let metadata = serde_json::json!({
        "packages": [{
            "name": "target",
            "dependencies": [
                {
                    "name": "C",
                    "source": "registry+https://x",
                    "kind": null,
                    "features": ["full"],
                    "uses_default_features": false
                },
            ],
        }],
        // The unified resolved graph: C's `full` has pulled in `unstable`. This is exactly the
        // contamination the declared-not-resolved model rejects; it must not reach the finding.
        "resolve": {
            "nodes": [
                { "id": "C 1.0.0", "features": ["full", "unstable"] },
            ]
        }
    });

    let forbid_unstable = CrateBoundary::crate_("target")
        .forbid_feature("C", "unstable")
        .because("C's unstable face is off-limits");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &forbid_unstable, &mut v).unwrap();
    assert!(
        v.is_empty(),
        "the transitively-enabled `unstable` (present in resolve.nodes) is not chased: {v:?}",
    );

    // The authored `full` IS observed and flagged, so the metadata is genuinely exercised
    // (the clean result above is not merely an unread fixture).
    let forbid_full = CrateBoundary::crate_("target")
        .forbid_feature("C", "full")
        .because("even the authored `full` is governed");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &forbid_full, &mut v).unwrap();
    assert_eq!(v.len(), 1, "{v:?}");
    assert_eq!(v[0].finding, "C/full");
}

#[test]
fn a_sibling_crates_enable_is_not_attributed_to_the_target() {
    // A MEANINGFUL test of the rejected `resolve.nodes` unification layer: the metadata has a
    // SIBLING workspace member enabling C's `unstable` AND a `resolve.nodes` entry for C whose
    // unified set contains `unstable`. The TARGET declares C with default-features = false and
    // no features. A `forbid C/unstable` rule on the target must stay clean — the declared set
    // is computed from the target's own edge, not the sibling's enable nor the unified node. If
    // `findings` read `resolve.nodes[C].features` (or scanned other packages' edges), this would
    // report `C/unstable` and fail.
    let metadata = serde_json::json!({
        "packages": [
            {
                "name": "target",
                "dependencies": [
                    {
                        "name": "C",
                        "source": "registry+https://x",
                        "kind": null,
                        "uses_default_features": false
                    },
                ],
            },
            {
                "name": "sibling",
                "dependencies": [
                    {
                        "name": "C",
                        "source": "registry+https://x",
                        "kind": null,
                        "features": ["unstable"],
                        "uses_default_features": false
                    },
                ],
            },
        ],
        // Feature unification folds the sibling's `unstable` into the one shared C node.
        "resolve": {
            "nodes": [
                { "id": "C 1.0.0", "features": ["unstable"] },
            ]
        }
    });

    let boundary = CrateBoundary::crate_("target")
        .forbid_feature("C", "unstable")
        .because("target must not author C's unstable");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &boundary, &mut v).unwrap();
    assert!(
        v.is_empty(),
        "a sibling's enable (and the unified resolve node) is not attributed to the target: {v:?}",
    );

    // Sanity that the harness IS reactive: the SIBLING, which authored `unstable`, is flagged
    // by the same rule — so the target's clean result reflects its own edge, not a dead fixture.
    let sibling_boundary = CrateBoundary::crate_("sibling")
        .forbid_feature("C", "unstable")
        .because("the sibling did author it");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &sibling_boundary, &mut v).unwrap();
    assert_eq!(v.len(), 1, "the sibling authored C/unstable: {v:?}");
    assert_eq!(v[0].finding, "C/unstable");
}

#[test]
fn declared_set_unions_across_multiple_edges() {
    // WHEN C is declared in [dependencies] with features=["a"] (defaults on) AND under
    // [target.'cfg(windows)'.dependencies] with default-features=false, features=["unstable"]
    // — both Normal-kind edges — the declared set is the union { a, default, unstable }.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["a"],
                "uses_default_features": true
            },
            {
                "name": "C",
                "kind": null,
                "target": "cfg(windows)",
                "features": ["unstable"],
                "uses_default_features": false
            },
        ]
    });
    assert_eq!(
        declared_features(&package, "C", DependencyKind::Normal),
        vec![
            "a".to_string(),
            "default".to_string(),
            "unstable".to_string()
        ],
        "the set unions across every matching edge; default from the plain edge",
    );
    // A rule forbidding `unstable` therefore emits a violation.
    let rule = Rule::ForbidFeaturesOf {
        crate_: "C".to_string(),
        forbidden: vec!["unstable".to_string()],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec!["C/unstable".to_string()],
    );
}

#[test]
fn a_dependency_is_matched_by_package_name_not_local_alias() {
    // WHEN the target declares myc = { package = "real-c", features = ["unstable"] } — cargo
    // reports name="real-c", rename="myc" — a rule against the package name `real-c` sees
    // `unstable`, while one against the local alias `myc` matches nothing.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "real-c",
                "rename": "myc",
                "kind": null,
                "features": ["unstable"],
                "uses_default_features": false
            },
        ]
    });
    assert_eq!(
        declared_features(&package, "real-c", DependencyKind::Normal),
        vec!["unstable".to_string()],
        "matched by resolved package name",
    );
    assert!(
        declared_features(&package, "myc", DependencyKind::Normal).is_empty(),
        "the local alias matches nothing",
    );
}

#[test]
fn restrict_features_flags_a_feature_outside_the_allowlist() {
    // WHEN the target declares C's `unstable` and the boundary restricts C to ["stable"]
    // → a violation for C/unstable.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["unstable"],
                "uses_default_features": false
            },
        ]
    });
    let rule = Rule::RestrictFeaturesOf {
        crate_: "C".to_string(),
        allowed: vec!["stable".to_string()],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec!["C/unstable".to_string()],
    );
}

#[test]
fn restrict_features_is_clean_when_every_declared_feature_is_allowed() {
    // WHEN the only declared feature is `stable`, with default-features = false, under a
    // restrict-to ["stable"] → clean.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["stable"],
                "uses_default_features": false
            },
        ]
    });
    let rule = Rule::RestrictFeaturesOf {
        crate_: "C".to_string(),
        allowed: vec!["stable".to_string()],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "an in-allowlist feature (with defaults off) is clean",
    );
}

#[test]
fn empty_allowlist_forbids_declaring_any_feature_including_default() {
    // WHEN the target leaves defaults on (or declares any feature) and the boundary restricts
    // C's features to [] → every declared feature, `default` included, is a violation.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["extra"],
                "uses_default_features": true
            },
        ]
    });
    let rule = Rule::RestrictFeaturesOf {
        crate_: "C".to_string(),
        allowed: vec![],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec!["C/default".to_string(), "C/extra".to_string()],
        "an empty allowlist forbids default and every explicit feature",
    );
}

#[test]
fn restrict_features_on_a_crate_not_depended_on_is_clean() {
    // WHEN the boundary restricts the features of a crate the target does not depend on in
    // the selected table → clean (there is no declared set to constrain; never exit 2 here).
    let package = serde_json::json!({
        "dependencies": [
            { "name": "other", "kind": null, "uses_default_features": true },
        ]
    });
    let rule = Rule::RestrictFeaturesOf {
        crate_: "C".to_string(),
        allowed: vec![],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "a feature rule on an undepended crate is clean",
    );
}

#[test]
fn forbid_feature_flags_a_declared_forbidden_feature() {
    // WHEN the target declares C's `unstable` and the boundary forbids C's `unstable`
    // → a violation for C/unstable.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["unstable"],
                "uses_default_features": false
            },
        ]
    });
    let rule = Rule::ForbidFeaturesOf {
        crate_: "C".to_string(),
        forbidden: vec!["unstable".to_string()],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec!["C/unstable".to_string()],
    );
}

#[test]
fn forbidding_default_requires_default_features_off() {
    // WHEN the boundary forbids C's `default` and the target declares C WITHOUT
    // default-features = false → a violation for C/default.
    let package = serde_json::json!({
        "dependencies": [
            { "name": "C", "kind": null, "uses_default_features": true },
        ]
    });
    let rule = Rule::ForbidFeaturesOf {
        crate_: "C".to_string(),
        forbidden: vec!["default".to_string()],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Normal),
        vec!["C/default".to_string()],
        "forbidding `default` ≡ requiring default-features = false",
    );
    // With default-features = false, the same rule is clean.
    let off = serde_json::json!({
        "dependencies": [
            { "name": "C", "kind": null, "uses_default_features": false },
        ]
    });
    assert!(
        rule.findings(&off, &[], DependencyKind::Normal).is_empty(),
        "with defaults off, forbidding `default` is satisfied",
    );
}

#[test]
fn a_forbidden_feature_the_target_does_not_declare_is_clean() {
    // WHEN the boundary forbids C's `unstable`, and the target declares only C's `full`
    // (which would transitively enable `unstable`, not chased) → clean.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["full"],
                "uses_default_features": false
            },
        ]
    });
    let rule = Rule::ForbidFeaturesOf {
        crate_: "C".to_string(),
        forbidden: vec!["unstable".to_string()],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "an undeclared forbidden feature is clean; transitive enables are not chased",
    );
}

#[test]
fn empty_forbidden_set_is_a_no_op() {
    // WHEN a boundary forbids an empty set of features of C → clean regardless of what the
    // target declares.
    let package = feature_package();
    let rule = Rule::ForbidFeaturesOf {
        crate_: "C".to_string(),
        forbidden: vec![],
    };
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "an empty forbidden set is a vacuous no-op",
    );
}

#[test]
fn feature_finding_carries_the_dependency_kind_suffix() {
    // A dev-table feature request carries the ` (dev)` suffix (the shared kind-qualify logic),
    // so C/unstable in [dependencies] and in [dev-dependencies] stay distinct findings.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": "dev",
                "features": ["unstable"],
                "uses_default_features": false
            },
        ]
    });
    let rule = Rule::ForbidFeaturesOf {
        crate_: "C".to_string(),
        forbidden: vec!["unstable".to_string()],
    };
    assert_eq!(
        rule.findings(&package, &[], DependencyKind::Dev),
        vec!["C/unstable (dev)".to_string()],
        "a dev-kind feature finding is `C/f (dev)`",
    );
    assert!(
        rule.findings(&package, &[], DependencyKind::Normal)
            .is_empty(),
        "the Normal surface does not observe a dev-table edge",
    );
}

#[test]
fn two_forbidden_features_of_the_same_crate_stay_distinct() {
    // The one forbidden bug for the feature family: C/unstable and C/nightly, both forbidden,
    // must not collapse — baselining C/unstable must not mask C/nightly.
    let package = serde_json::json!({
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["unstable", "nightly"],
                "uses_default_features": false
            },
        ]
    });
    let metadata = serde_json::json!({ "packages": [{
        "name": "target",
        "dependencies": package["dependencies"].clone(),
    }] });
    let boundary = CrateBoundary::crate_("target")
        .forbid_features_of("C", ["unstable", "nightly"])
        .because("no unstable/nightly features of C");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &boundary, &mut v).unwrap();
    assert_eq!(
        v.iter().map(|x| x.finding.as_str()).collect::<Vec<_>>(),
        vec!["C/nightly", "C/unstable"],
        "both features are distinct findings under the one rule",
    );

    // Baseline records ONLY C/unstable (a prior accepted state). Re-applying it must mark
    // C/unstable baselined while leaving C/nightly live — the finding, not the (target, rule)
    // pair, is the baseline key, so one feature's acceptance never masks another's.
    let mut report = Report::new(v);
    let baseline = Baseline::of(&Report::new(vec![Violation::new(
        BoundaryKind::Crate,
        test_id("target", "forbid features of", "C/unstable"),
        "no unstable/nightly features of C".to_string(),
        Severity::Enforce,
    )]));
    apply_baseline(&mut report, &baseline);

    let unstable = report
        .violations
        .iter()
        .find(|x| x.finding == "C/unstable")
        .expect("C/unstable present");
    let nightly = report
        .violations
        .iter()
        .find(|x| x.finding == "C/nightly")
        .expect("C/nightly present");
    assert!(unstable.baselined, "the baselined C/unstable is marked");
    assert!(
        !nightly.baselined,
        "C/nightly is NOT masked by the C/unstable baseline entry",
    );
    // The baseline entry for C/unstable is matched (not stale); C/nightly is not in it.
    assert!(
        baseline.stale(&report).is_empty(),
        "the C/unstable baseline entry matches a current violation, so it is not stale",
    );
    assert_eq!(
        Outcome::Violations(report).exit_code(),
        1,
        "the still-live C/nightly enforce violation fails the reaction",
    );
}

#[test]
fn the_two_feature_rule_labels_are_distinct_and_keep_identity_injective() {
    // A restrict and a forbid rule that both flag C/unstable on the same target stay distinct
    // triples, because their `rule` labels differ.
    assert_ne!(
        Rule::RestrictFeaturesOf {
            crate_: "C".to_string(),
            allowed: vec![],
        }
        .label(),
        Rule::ForbidFeaturesOf {
            crate_: "C".to_string(),
            forbidden: vec![],
        }
        .label(),
        "the two feature-rule labels must differ",
    );
    // And distinct from every crate rule label.
    let feature_labels = ["restrict features of", "forbid features of"];
    for other in [
        Rule::DenyExternalDependencies { allowed: vec![] }.label(),
        Rule::ForbidDependencyOn { crates: vec![] }.label(),
        Rule::RestrictDependenciesTo { allowed: vec![] }.label(),
        Rule::RestrictWorkspaceDependenciesTo { allowed: vec![] }.label(),
        Rule::RestrictDependencySourcesTo { allowed: vec![] }.label(),
    ] {
        assert!(
            !feature_labels.contains(&other),
            "feature labels must be distinct from crate-rule label {other}",
        );
    }

    // Concrete non-masking: a restrict rule (empty allowlist) and a forbid rule both flag the
    // SAME `C/unstable` on the SAME target. Because their `rule` labels differ, they are two
    // distinct `(target, rule, finding)` triples: baselining the restrict violation must NOT
    // mask the forbid violation.
    let metadata = serde_json::json!({ "packages": [{
        "name": "target",
        "dependencies": [
            {
                "name": "C",
                "source": "registry+https://x",
                "kind": null,
                "features": ["unstable"],
                "uses_default_features": false
            },
        ],
    }] });
    let restrict = CrateBoundary::crate_("target")
        .restrict_features_of("C", Vec::<String>::new())
        .because("C's feature surface is closed");
    let forbid = CrateBoundary::crate_("target")
        .forbid_feature("C", "unstable")
        .because("C's unstable is off-limits");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &restrict, &mut v).unwrap();
    check_crate_boundary(&metadata, &[], &forbid, &mut v).unwrap();
    // Same target + same finding, two different rule labels ⇒ two distinct violations.
    assert_eq!(v.len(), 2, "{v:?}");
    assert!(v.iter().all(|x| x.finding == "C/unstable"));
    let mut rules: Vec<&str> = v.iter().map(|x| x.rule.as_str()).collect();
    rules.sort_unstable();
    assert_eq!(rules, vec!["forbid features of", "restrict features of"]);

    // Baseline ONLY the restrict-rule C/unstable; the forbid-rule C/unstable must stay live.
    let mut report = Report::new(v);
    let baseline = Baseline::of(&Report::new(vec![Violation::new(
        BoundaryKind::Crate,
        test_id("target", "restrict features of", "C/unstable"),
        "C's feature surface is closed".to_string(),
        Severity::Enforce,
    )]));
    apply_baseline(&mut report, &baseline);
    let restrict_v = report
        .violations
        .iter()
        .find(|x| x.rule == "restrict features of")
        .unwrap();
    let forbid_v = report
        .violations
        .iter()
        .find(|x| x.rule == "forbid features of")
        .unwrap();
    assert!(restrict_v.baselined, "the restrict C/unstable is baselined");
    assert!(
        !forbid_v.baselined,
        "the forbid C/unstable is a distinct triple, not masked by the restrict baseline",
    );
    assert_eq!(
        Outcome::Violations(report).exit_code(),
        1,
        "the still-live forbid C/unstable fails the reaction",
    );
}

#[test]
fn feature_report_names_target_rule_finding_and_reason() {
    // WHEN a feature rule on C is violated by the declared `unstable` → the report names the
    // target, the feature rule, the finding C/unstable, and the reason; the reaction fails.
    let metadata = serde_json::json!({ "packages": [{
        "name": "app",
        "dependencies": [
            {
                "name": "C",
                "kind": null,
                "features": ["unstable"],
                "uses_default_features": false
            },
        ],
    }] });
    let boundary = CrateBoundary::crate_("app")
        .forbid_feature("C", "unstable")
        .because("C's unstable API face is off-limits");
    let mut v = Vec::new();
    check_crate_boundary(&metadata, &[], &boundary, &mut v).unwrap();
    assert_eq!(v.len(), 1);
    assert_eq!(v[0].target, "app");
    assert_eq!(v[0].rule, "forbid features of");
    assert_eq!(v[0].finding, "C/unstable");
    assert_eq!(v[0].reason, "C's unstable API face is off-limits");
    assert!(
        v[0].file.is_none(),
        "a feature violation is a manifest relation, not a source line",
    );
    assert_eq!(
        Outcome::Violations(Report::new(v)).exit_code(),
        1,
        "an enforce feature violation fails the reaction",
    );
}

#[test]
fn a_feature_boundary_on_an_absent_target_is_a_constitution_error() {
    // Parity with the other crate rules: a feature boundary on a crate not in the workspace
    // is a constitution error (→ exit 2), never a silent pass. (`C` is never resolved, but the
    // TARGET must be a workspace member.)
    let metadata = serde_json::json!({ "packages": [{ "name": "present" }] });
    let boundary = CrateBoundary::crate_("absent")
        .restrict_features_of("C", ["stable"])
        .because("absent may use only C's stable face");
    let mut v = Vec::new();
    assert!(
        check_crate_boundary(&metadata, &[], &boundary, &mut v).is_err(),
        "an absent target crate must be a constitution error",
    );
}

#[test]
fn feature_boundary_defaults_to_enforce_normal_kind() {
    // The builders finish through Enforce severity / Normal kind, like restrict_dependencies_to.
    let restrict = CrateBoundary::crate_("app")
        .restrict_features_of("C", ["stable"])
        .because("r");
    assert_eq!(restrict.severity(), Severity::Enforce);
    assert_eq!(restrict.dependency_kind(), DependencyKind::Normal);
    let forbid = CrateBoundary::crate_("app")
        .forbid_feature("C", "default")
        .because("f");
    assert_eq!(forbid.severity(), Severity::Enforce);
    assert_eq!(forbid.dependency_kind(), DependencyKind::Normal);
    // forbid_feature is the singular convenience over forbid_features_of.
    assert_eq!(
        forbid.rule(),
        &Rule::ForbidFeaturesOf {
            crate_: "C".to_string(),
            forbidden: vec!["default".to_string()],
        },
    );
}

#[test]
fn feature_rules_project_to_text_and_json() {
    let constitution = Constitution::new("p")
        .boundary(
            CrateBoundary::crate_("app")
                .restrict_features_of("tokio", ["rt", "macros"])
                .because("app may use only tokio's rt and macros"),
        )
        .boundary(
            CrateBoundary::crate_("lib")
                .restrict_features_of::<&str, [&str; 0], &str>("tokio", [])
                .because("lib must declare no tokio feature at all"),
        )
        .boundary(
            CrateBoundary::crate_("worker")
                .forbid_features_of("tokio", ["unstable"])
                .dependency_kind(DependencyKind::Build)
                .because("no unstable tokio in the build script"),
        )
        .boundary(
            CrateBoundary::crate_("edge")
                .forbid_features_of::<&str, [&str; 0], &str>("serde", [])
                .because("vacuous"),
        );

    let text = constitution_text(&constitution);
    assert!(
        text.contains("restrict features of tokio to: rt, macros"),
        "{text}"
    );
    assert!(
        text.contains("restrict features of tokio to nothing"),
        "{text}"
    );
    assert!(
        text.contains("forbid features of tokio: unstable (build dependencies)"),
        "{text}"
    );
    assert!(text.contains("forbid no features of serde"), "{text}");

    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(doc["boundaries"][0]["rule"], "restrict features of");
    assert_eq!(doc["boundaries"][0]["crate"], "tokio");
    assert_eq!(doc["boundaries"][0]["only_features"][0], "rt");
    assert_eq!(doc["boundaries"][0]["only_features"][1], "macros");
    // The empty allowlist is still emitted, as `[]`.
    assert_eq!(
        doc["boundaries"][1]["only_features"]
            .as_array()
            .unwrap()
            .len(),
        0
    );
    assert_eq!(doc["boundaries"][2]["rule"], "forbid features of");
    assert_eq!(doc["boundaries"][2]["crate"], "tokio");
    assert_eq!(doc["boundaries"][2]["forbidden_features"][0], "unstable");
    // Non-Normal kind is disclosed in the projection.
    assert_eq!(doc["boundaries"][2]["dependency_kind"], "build");
    // Distinct keys per polarity: restrict uses only_features, forbid uses forbidden_features.
    assert!(doc["boundaries"][0]["forbidden_features"].is_null());
    assert!(doc["boundaries"][2]["only_features"].is_null());
}

#[test]
fn module_restrict_imports_to_projects_its_allowlist() {
    let constitution = Constitution::new("p")
        .boundary(
            ModuleBoundary::in_crate("app")
                .module("crate::kernel")
                .restrict_imports_to(["crate::types"])
                .because("the kernel may import only types"),
        )
        .boundary(
            ModuleBoundary::in_crate("app")
                .module("crate::leaf")
                .restrict_imports_to::<[&str; 0], &str>([])
                .because("the leaf may import only its own subtree"),
        );

    let text = constitution_text(&constitution);
    assert!(text.contains("restrict imports to: crate::types"), "{text}");
    assert!(text.contains("restrict imports to nothing"), "{text}");

    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(doc["boundaries"][0]["rule"], "restrict imports to");
    assert_eq!(doc["boundaries"][0]["kind"], "module");
    assert_eq!(doc["boundaries"][0]["target"], "crate::kernel");
    // The closed set uses `only` (the crate-level vocabulary), never `forbidden`.
    assert_eq!(doc["boundaries"][0]["only"][0], "crate::types");
    assert!(doc["boundaries"][0]["forbidden"].is_null());
    // The empty allowlist is still emitted, as `[]`.
    assert_eq!(doc["boundaries"][1]["only"].as_array().unwrap().len(), 0);
}

#[test]
fn an_unreadable_utf8_governed_source_file_is_a_scan_error() {
    // Deterministic on every platform and euid (unlike the permission-based tests,
    // which skip under a privileged user): invalid UTF-8 makes `read_to_string` fail,
    // so a reachable governed-crate source file that cannot be read is a scan error
    // (exit 2), never a silent skip — the core-contract "cannot judge" rule.
    let dir = std::env::temp_dir().join(format!("guibiao-utf8-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let src = dir.join("src");
    std::fs::create_dir_all(&src).expect("create temp src");
    std::fs::write(src.join("lib.rs"), "pub mod kernel;\n").expect("write lib.rs");
    // 0xFF / 0xFE are not valid UTF-8; read_to_string returns Err on all platforms.
    std::fs::write(src.join("kernel.rs"), [0xFF, 0xFE, 0x00, 0x80]).expect("write kernel.rs");

    let manifest = dir.join("Cargo.toml");
    let metadata = serde_json::json!({
        "packages": [{
            "name": "x",
            "manifest_path": manifest.to_string_lossy().into_owned(),
            "dependencies": [],
        }]
    });
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate::kernel")
        .must_not_import("crate::forbidden")
        .because("kernel must not import forbidden");
    let mut violations = Vec::new();
    let result = check_module_boundary(&metadata, &boundary, &mut violations);
    let _ = std::fs::remove_dir_all(&dir);
    assert!(
        result.is_err(),
        "an unreadable (invalid-UTF-8) governed source file must be a scan error"
    );
}

#[test]
fn dependency_kind_appears_in_the_projection() {
    let constitution = Constitution::new("p")
        .boundary(
            CrateBoundary::crate_("a")
                .deny_external_dependencies()
                .dependency_kind(DependencyKind::Dev)
                .because("a's dev dependencies stay light"),
        )
        .boundary(
            CrateBoundary::crate_("b")
                .deny_external_dependencies()
                .because("b stays light"),
        );
    let text = constitution_text(&constitution);
    assert!(text.contains("(dev dependencies)"), "{text}");
    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(doc["boundaries"][0]["dependency_kind"], "dev");
    // A Normal-kind boundary omits the field entirely (the common projection).
    assert!(doc["boundaries"][1]["dependency_kind"].is_null(), "{doc}");
}

#[test]
fn restrict_workspace_dependencies_to_projects_only_workspace() {
    let constitution = Constitution::new("p")
        .boundary(
            CrateBoundary::crate_("a")
                .restrict_workspace_dependencies_to(["b"])
                .because("a may depend on only workspace member b"),
        )
        .boundary(
            CrateBoundary::crate_("c")
                .forbid_all_workspace_dependencies()
                .because("c must not depend on any workspace member"),
        );
    let text = constitution_text(&constitution);
    assert!(
        text.contains("restrict workspace dependencies to: b"),
        "{text}"
    );
    assert!(text.contains("forbid all workspace dependencies"), "{text}");
    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(
        doc["boundaries"][0]["rule"],
        "restrict workspace dependencies to"
    );
    // The distinct key (`only_workspace`, not `only`) says which dependency surface
    // is governed — the self-describing distinction with no coverage before now.
    assert_eq!(doc["boundaries"][0]["only_workspace"][0], "b");
    assert!(doc["boundaries"][0]["only"].is_null());
    // The empty allowlist (forbid-all) still emits `only_workspace: []`.
    assert_eq!(
        doc["boundaries"][1]["only_workspace"]
            .as_array()
            .unwrap()
            .len(),
        0
    );
}

/// A boundary's `.with_anchor(...)` rides through the reaction onto the produced violation and
/// into its JSON — the durable governance pointer reaches the CI-consumable surface.
#[test]
fn an_anchored_boundary_stamps_its_violations_with_the_anchor() {
    let (result, violations) = run_module_check(
        "anchored",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::secret")
            .because("the kernel must not import a secret")
            .with_anchor("ADR-014"),
    );
    result.expect("a valid module boundary");
    assert!(!violations.is_empty(), "the forbidden import must react");
    assert_eq!(violations[0].anchor.as_deref(), Some("ADR-014"));
    assert_eq!(violations[0].to_json()["anchor"], "ADR-014");
}

/// The mirror: a boundary that declares no anchor produces `None` on its violations — the anchor
/// is opt-in and never fabricated.
#[test]
fn an_anchorless_boundary_leaves_its_violations_unanchored() {
    let (result, violations) = run_module_check(
        "unanchored",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::secret")
            .because("the kernel must not import a secret"),
    );
    result.expect("a valid module boundary");
    assert!(!violations.is_empty());
    assert_eq!(violations[0].anchor, None);
}

/// The reaction stamps a module violation with the rule's repair-direction polarity: a deny rule
/// (`must_not_import`) → `DenyBreach`, an allowlist rule (`restrict_imports_to`) → `AllowlistGap`.
#[test]
fn a_module_violation_carries_its_rule_repair_polarity() {
    let (_r, deny) = run_module_check(
        "polarity-deny",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::secret::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .must_not_import("crate::secret")
            .because("deny"),
    );
    assert_eq!(deny[0].polarity, Some(Polarity::DenyBreach));

    let (_r, allow) = run_module_check(
        "polarity-allow",
        &[
            ("lib.rs", "pub mod kernel;\n"),
            ("kernel.rs", "use crate::infra::Thing;\n"),
        ],
        ModuleBoundary::in_crate("x")
            .module("crate::kernel")
            .restrict_imports_to(["crate::types"])
            .because("allow"),
    );
    assert_eq!(allow[0].polarity, Some(Polarity::AllowlistGap));
}

/// The rule → polarity classification, incl. the deliberate call that `deny_external_dependencies`
/// is `AllowlistGap` (its `allow_external` is an in-boundary declaration path — by repair direction,
/// not rule name), while `forbid_dependency_on` names a specific forbidden crate → `DenyBreach`.
#[test]
fn crate_rule_polarity_classifies_by_repair_direction() {
    let deny_external = CrateBoundary::crate_("x")
        .deny_external_dependencies()
        .because("r");
    assert_eq!(deny_external.rule().polarity(), Polarity::AllowlistGap);

    let forbid = CrateBoundary::crate_("x")
        .forbid_dependency_on(["openssl"])
        .because("r");
    assert_eq!(forbid.rule().polarity(), Polarity::DenyBreach);

    let restrict = CrateBoundary::crate_("x")
        .restrict_dependencies_to(["serde"])
        .because("r");
    assert_eq!(restrict.rule().polarity(), Polarity::AllowlistGap);
}

/// The constitution projection surfaces a boundary's anchor **only when set**, so an anchor-less
/// boundary keeps byte-identical JSON (the Some-only discipline that protects the self-law
/// projection's staleness byte-check).
#[test]
fn constitution_json_emits_anchor_only_when_set() {
    let constitution = Constitution::new("anchors")
        .boundary(
            CrateBoundary::crate_("a")
                .forbid_all_workspace_dependencies()
                .because("anchored")
                .with_anchor("ADR-014"),
        )
        .boundary(
            CrateBoundary::crate_("b")
                .forbid_all_workspace_dependencies()
                .because("unanchored"),
        );
    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(doc["boundaries"][0]["anchor"], "ADR-014");
    assert!(
        doc["boundaries"][1].get("anchor").is_none(),
        "an anchor-less boundary must emit no `anchor` key"
    );
}

// --- must_only_be_imported_by (the inbound closed allowlist) ----------------

fn only_importers(allowed: &[&str]) -> ModuleBoundary {
    ModuleBoundary::in_crate("x")
        .module("crate::internal")
        .must_only_be_imported_by(allowed.iter().copied())
        .because("internal is imported only through its facade")
}

#[test]
fn must_only_be_imported_by_flags_an_importer_outside_the_allowlist() {
    let (result, violations) = run_module_check(
        "only-basic",
        &[
            (
                "lib.rs",
                "pub mod internal;\npub mod facade;\npub mod consumer;\n",
            ),
            ("internal.rs", "// protected\n"),
            ("facade.rs", "use crate::internal::Secret;\n"),
            ("consumer.rs", "use crate::internal::Secret;\n"),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    // facade is allowlisted (clean); consumer is not (violates).
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "crate::internal");
    assert_eq!(violations[0].finding, "crate::consumer");
    assert_eq!(violations[0].rule, "module may only be imported by");
}

#[test]
fn must_only_be_imported_by_authorizes_an_allowed_inline_importer() {
    // `crate::facade` is an INLINE module and IS allow-listed. Its import is attributed
    // to `crate::facade` (not the file's `crate`), so it is correctly authorized. Testing the file
    // module `crate` against the allowlist would wrongly flag the allowed inline importer.
    let (result, violations) = run_module_check(
        "only-inline-allowed",
        &[
            (
                "lib.rs",
                "pub mod internal;\nmod facade { use crate::internal::Secret; }\n",
            ),
            ("internal.rs", "// protected\n"),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "an allow-listed inline importer must not be flagged: {violations:?}"
    );
}

#[test]
fn must_only_be_imported_by_flags_a_disallowed_inline_importer_by_its_true_identity() {
    // A disallowed INLINE importer is flagged with its true identity `crate::rogue` (not the file's
    // `crate`), so the finding — and thus the baseline identity `(target, rule, finding)` — is
    // correct rather than shifted onto the file module.
    let (result, violations) = run_module_check(
        "only-inline-disallowed",
        &[
            (
                "lib.rs",
                "pub mod internal;\npub mod facade;\nmod rogue { use crate::internal::Secret; }\n",
            ),
            ("internal.rs", "// protected\n"),
            (
                "facade.rs",
                "// the allow-listed importer declares no import here\n",
            ),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::rogue");
}

#[test]
fn must_only_be_imported_by_admits_the_allowlisted_importer_subtree() {
    let (result, violations) = run_module_check(
        "only-subtree",
        &[
            ("lib.rs", "pub mod internal;\npub mod facade;\n"),
            ("internal.rs", "// protected\n"),
            ("facade.rs", "pub mod v1;\n"),
            ("facade/v1.rs", "use crate::internal::Secret;\n"),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "crate::facade::v1 is beneath the allowlisted importer: {violations:?}"
    );
}

#[test]
fn must_only_be_imported_by_does_not_admit_a_prefix_colliding_sibling() {
    let (result, violations) = run_module_check(
        "only-prefix",
        &[
            ("lib.rs", "pub mod internal;\npub mod facadex;\n"),
            ("internal.rs", "// protected\n"),
            ("facadex.rs", "use crate::internal::Secret;\n"),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(
        violations[0].finding, "crate::facadex",
        "a sibling of the allowlisted importer is not admitted"
    );
}

#[test]
fn must_only_be_imported_by_never_flags_the_protected_subtree() {
    let (result, violations) = run_module_check(
        "only-own-subtree",
        &[
            ("lib.rs", "pub mod internal;\n"),
            ("internal.rs", "pub mod deep;\n"),
            ("internal/deep.rs", "use crate::internal::Secret;\n"),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a module within the protected subtree is not an inbound importer: {violations:?}"
    );
}

#[test]
fn must_only_be_imported_by_empty_allowlist_forbids_every_outside_importer() {
    let (result, violations) = run_module_check(
        "only-empty",
        &[
            ("lib.rs", "pub mod internal;\npub mod consumer;\n"),
            ("internal.rs", "// protected\n"),
            ("consumer.rs", "use crate::internal::Secret;\n"),
        ],
        only_importers(&[]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::consumer");
}

#[test]
fn must_only_be_imported_by_admits_multiple_allowlisted_importers() {
    let (result, violations) = run_module_check(
        "only-multiple",
        &[
            (
                "lib.rs",
                "pub mod internal;\npub mod facade;\npub mod api;\npub mod consumer;\n",
            ),
            ("internal.rs", "// protected\n"),
            ("facade.rs", "use crate::internal::Secret;\n"),
            ("api.rs", "use crate::internal::Secret;\n"),
            ("consumer.rs", "use crate::internal::Secret;\n"),
        ],
        only_importers(&["crate::facade", "crate::api"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::consumer");
}

#[test]
fn must_only_be_imported_by_ignores_external_imports() {
    let (result, violations) = run_module_check(
        "only-external",
        &[
            ("lib.rs", "pub mod internal;\npub mod consumer;\n"),
            ("internal.rs", "// protected\n"),
            ("consumer.rs", "use serde::Deserialize;\n"),
        ],
        only_importers(&["crate::facade"]),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "an external import is out of scope: {violations:?}"
    );
}

#[test]
fn must_only_be_imported_by_on_the_crate_root_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "only-m-crate",
        &[("lib.rs", "pub mod http;\n"), ("http.rs", "// nothing\n")],
        ModuleBoundary::in_crate("x")
            .module("crate")
            .must_only_be_imported_by(["crate::facade"])
            .because("the crate root cannot be protected this way"),
    );
    let err = result.expect_err("protecting `crate` must be a constitution error");
    assert_eq!(err, must_only_be_imported_by_on_crate_error("x"));
}

#[test]
fn must_only_be_imported_by_rule_text_and_json_params() {
    // Projection surface: distinct label/text and the surface-qualified `only_importers` key.
    let rule = ModuleRule::MustOnlyBeImportedBy {
        allowed: vec!["crate::facade".to_string()],
    };
    assert_eq!(rule.label(), "module may only be imported by");
    assert_eq!(rule.polarity(), Polarity::AllowlistGap);
    assert_eq!(rule.text(), "may only be imported by: crate::facade");
    assert_eq!(
        rule.json_params(),
        vec![("only_importers", serde_json::json!(["crate::facade"]))]
    );
    let empty = ModuleRule::MustOnlyBeImportedBy { allowed: vec![] };
    assert_eq!(empty.text(), "may only be imported by nothing");
}

// --- external-crate confinement (`confine_external_crate`) ------------------------------

fn confine(governed: &str, crate_name: &str) -> ModuleBoundary {
    ModuleBoundary::in_crate("x")
        .module(governed)
        .confine_external_crate(crate_name)
        .because("the platform vocabulary stays behind the ffi module")
}

#[test]
fn confine_flags_an_external_import_outside_the_subtree() {
    // The confined crate is the target; the offending importer module is the finding.
    let (result, violations) = run_module_check(
        "confine-outside",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use libc::c_int;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].target, "libc");
    assert_eq!(violations[0].finding, "crate::service");
    let file = violations[0].file.as_deref().expect("carries its file");
    assert!(file.ends_with("service.rs"), "names the offender: {file}");
}

#[test]
fn confine_is_clean_within_the_subtree() {
    let (result, violations) = run_module_check(
        "confine-within",
        &[
            ("lib.rs", "pub mod ffi;\n"),
            ("ffi.rs", "use libc::c_int;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "within the subtree is clean: {violations:?}"
    );
}

#[test]
fn confine_allows_beneath_the_subtree() {
    let (result, violations) = run_module_check(
        "confine-beneath",
        &[
            ("lib.rs", "pub mod ffi;\n"),
            ("ffi.rs", "pub mod raw;\n"),
            ("ffi/raw.rs", "use libc::c_int;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a module beneath the permitted subtree is clean: {violations:?}"
    );
}

#[test]
fn confine_flags_a_prefix_colliding_sibling_of_the_subtree() {
    // `crate::ffi_utils` is neither `crate::ffi` nor beneath `crate::ffi::` (`::`-delimited).
    let (result, violations) = run_module_check(
        "confine-sibling",
        &[
            ("lib.rs", "pub mod ffi;\npub mod ffi_utils;\n"),
            ("ffi.rs", "\n"),
            ("ffi_utils.rs", "use libc::c_int;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].finding, "crate::ffi_utils");
}

#[test]
fn confine_observes_a_glob_and_a_bare_import() {
    let (result, violations) = run_module_check(
        "confine-glob",
        &[
            ("lib.rs", "pub mod ffi;\npub mod a;\npub mod b;\n"),
            ("ffi.rs", "\n"),
            ("a.rs", "use libc::*;\n"),
            ("b.rs", "use libc;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    let findings: Vec<&str> = violations.iter().map(|v| v.finding.as_str()).collect();
    assert_eq!(violations.len(), 2, "{violations:?}");
    assert!(
        findings.contains(&"crate::a") && findings.contains(&"crate::b"),
        "{findings:?}"
    );
}

#[test]
fn confine_ignores_a_different_external_crate() {
    let (result, violations) = run_module_check(
        "confine-other-crate",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use serde::Deserialize;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "the rule observes only the confined crate: {violations:?}"
    );
}

#[test]
fn confine_of_an_unimported_crate_is_clean_with_no_error() {
    // No cargo-metadata cross-check: confining a crate the target never imports is clean,
    // exactly as forbidding a crate you do not depend on is clean — never a constitution error.
    let (result, violations) = run_module_check(
        "confine-unimported",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use serde::Deserialize;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(
        result.is_ok(),
        "no error for an unimported confined crate: {result:?}"
    );
    assert!(violations.is_empty(), "{violations:?}");
}

#[test]
fn confine_resolves_a_shadowing_root_module_as_internal_no_false_positive() {
    // A crate-root `mod libc;` shadows the extern prelude, so a root-file bare `use libc::…`
    // is the INTERNAL `crate::libc`, not the external crate — the external scan must not
    // observe it, or the rule would false-positive against the crate's own module.
    let (result, violations) = run_module_check(
        "confine-shadow",
        &[
            ("lib.rs", "pub mod libc;\npub mod ffi;\nuse libc::helper;\n"),
            ("libc.rs", "pub fn helper() {}\n"),
            ("ffi.rs", "\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a shadowing root module resolves internal, not as the confined external crate: {violations:?}"
    );
}

#[test]
fn confine_observes_submodule_bare_and_leading_colon_forms() {
    let (result, violations) = run_module_check(
        "confine-forms",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\npub mod other;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use libc::c_int;\n"),
            ("other.rs", "use ::libc::c_void;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    let findings: Vec<&str> = violations.iter().map(|v| v.finding.as_str()).collect();
    assert_eq!(violations.len(), 2, "{violations:?}");
    assert!(
        findings.contains(&"crate::service") && findings.contains(&"crate::other"),
        "both a submodule-bare and a leading-`::` external import are observed: {findings:?}"
    );
}

#[test]
fn confine_ignores_a_use_inside_a_string_literal() {
    let (result, violations) = run_module_check(
        "confine-string",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            (
                "service.rs",
                "pub fn f() { let _s = \"use libc::c_int;\"; }\n",
            ),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert!(
        violations.is_empty(),
        "a use inside a string literal is stripped before scanning: {violations:?}"
    );
}

#[test]
fn confine_dedups_multiple_imports_from_one_importer() {
    let (result, violations) = run_module_check(
        "confine-dedup",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use libc::c_int;\nuse libc::c_void;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "one importer importing the confined crate twice yields one violation: {violations:?}"
    );
}

#[test]
fn confine_identity_is_injective_across_confined_crates() {
    // The highest-risk invariant: two confinements of different crates on the same subtree,
    // breached by the same importer, must NOT collapse — baselining one must not mask the
    // other. Injectivity comes from the target being the confined crate.
    let files = [
        ("lib.rs", "pub mod ffi;\npub mod service;\n"),
        ("ffi.rs", "\n"),
        ("service.rs", "use libc::c_int;\nuse winapi::HANDLE;\n"),
    ];
    let (r1, libc_v) = run_module_check("confine-inj-libc", &files, confine("crate::ffi", "libc"));
    let (r2, winapi_v) = run_module_check(
        "confine-inj-winapi",
        &files,
        confine("crate::ffi", "winapi"),
    );
    assert!(r1.is_ok() && r2.is_ok(), "{r1:?} {r2:?}");
    assert_eq!(libc_v.len(), 1, "{libc_v:?}");
    assert_eq!(winapi_v.len(), 1, "{winapi_v:?}");
    assert_eq!(libc_v[0].target, "libc");
    assert_eq!(winapi_v[0].target, "winapi");
    assert_eq!(
        libc_v[0].finding, winapi_v[0].finding,
        "same offending importer — only the target (confined crate) differs"
    );
    // Baseline only the libc violation; the winapi violation must still react.
    let baseline = Baseline::of(&Report::new(libc_v.clone()));
    let mut both = Report::new(vec![libc_v[0].clone(), winapi_v[0].clone()]);
    apply_baseline(&mut both, &baseline);
    assert!(both.violations[0].baselined, "libc is baselined");
    assert!(
        !both.violations[1].baselined,
        "winapi is NOT masked by libc's baseline — distinct target keeps identity injective"
    );
    assert_eq!(
        Outcome::Violations(both).exit_code(),
        1,
        "the new winapi violation still fails"
    );
}

#[test]
fn confine_canonicalizes_a_raw_identifier_crate_name() {
    // The confined crate name and the observed head canonicalize (`r#name` -> `name`), so a
    // boundary written with either form matches an import written with either form.
    let (result, violations) = run_module_check(
        "confine-raw-id",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use r#async::spawn;\n"),
        ],
        confine("crate::ffi", "async"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "raw and plain crate-name forms are one identity: {violations:?}"
    );
    assert_eq!(violations[0].target, "async");
}

#[test]
fn confine_on_the_crate_root_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "confine-on-crate",
        &[("lib.rs", "use libc::c_int;\n")],
        confine("crate", "libc"),
    );
    let err = result.expect_err("confining to the crate root is a constitution error");
    assert_eq!(err, confine_external_crate_on_crate_error("x"));
}

#[test]
fn confine_unknown_subtree_is_a_constitution_error() {
    let (result, _violations) = run_module_check(
        "confine-unknown",
        &[("lib.rs", "pub mod ffi;\n"), ("ffi.rs", "\n")],
        confine("crate::nope", "libc"),
    );
    let err = result.expect_err("an unreachable permitted subtree is a constitution error");
    assert_eq!(err, unknown_module_error("crate::nope", "x"));
}

#[test]
fn confine_honors_warn_severity() {
    let boundary = ModuleBoundary::in_crate("x")
        .module("crate::ffi")
        .confine_external_crate("libc")
        .warn()
        .because("advisory during adoption");
    let (result, violations) = run_module_check(
        "confine-warn",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use libc::c_int;\n"),
        ],
        boundary,
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(violations.len(), 1, "{violations:?}");
    assert_eq!(violations[0].severity, Severity::Warn);
    assert_eq!(
        Outcome::Violations(Report::new(violations)).exit_code(),
        0,
        "a warn-only confinement does not fail CI"
    );
}

#[test]
fn confine_external_crate_rule_text_and_json_params() {
    let rule = ModuleRule::ConfineExternalCrate {
        crate_name: "libc".to_string(),
    };
    assert_eq!(rule.label(), "external crate confined to module");
    assert_eq!(rule.polarity(), Polarity::AllowlistGap);
    assert_eq!(
        rule.text(),
        "confines external crate libc to this module's subtree"
    );
    assert_eq!(
        rule.json_params(),
        vec![("external_crate", serde_json::json!("libc"))]
    );
}

#[test]
fn confine_external_crate_projects_its_crate_and_subtree() {
    // The full constitution projection (not just the rule params): the declared module
    // subtree and the confined crate must both be legible without reading the rule label.
    let constitution = Constitution::new("p").boundary(
        ModuleBoundary::in_crate("app")
            .module("crate::ffi")
            .confine_external_crate("libc")
            .because("the raw libc surface stays behind the ffi module"),
    );

    let text = constitution_text(&constitution);
    assert!(
        text.contains("crate::ffi"),
        "the declared subtree is named: {text}"
    );
    assert!(
        text.contains("confines external crate libc"),
        "the confined crate is named: {text}"
    );

    let doc: serde_json::Value = serde_json::from_str(&constitution_json(&constitution)).unwrap();
    assert_eq!(
        doc["boundaries"][0]["rule"],
        "external crate confined to module"
    );
    // The declared module subtree is the boundary target (declaration view); the confined
    // crate projects under the self-describing `external_crate` key.
    assert_eq!(doc["boundaries"][0]["target"], "crate::ffi");
    assert_eq!(doc["boundaries"][0]["external_crate"], "libc");
    assert!(doc["boundaries"][0]["forbidden"].is_null());
    assert!(doc["boundaries"][0]["only"].is_null());
}

#[test]
fn confine_matches_a_hyphenated_package_name_against_its_underscore_identifier() {
    // A package with a `-` (e.g. `windows-sys`) is imported through its `_` identifier
    // (`use windows_sys::…`) — a `use` path cannot contain `-`. The confined name is written in
    // package form yet must match the identifier the scanner observes, or the rule would silently
    // never react for exactly the hyphenated FFI/platform crates it targets (a false negative).
    let (result, violations) = run_module_check(
        "confine-hyphen",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            (
                "service.rs",
                "use windows_sys::Win32::Foundation::HANDLE;\n",
            ),
        ],
        confine("crate::ffi", "windows-sys"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a hyphenated package name matches its underscore import identifier: {violations:?}"
    );
    assert_eq!(violations[0].target, "windows_sys");
    assert_eq!(violations[0].finding, "crate::service");
}

#[test]
fn confine_observes_an_aliased_import_of_the_confined_crate() {
    // `use libc as c;` still imports libc; the alias is dropped at expansion, so the confined
    // crate's head is observed regardless of a local rename.
    let (result, violations) = run_module_check(
        "confine-alias",
        &[
            ("lib.rs", "pub mod ffi;\npub mod service;\n"),
            ("ffi.rs", "\n"),
            ("service.rs", "use libc as c;\n"),
        ],
        confine("crate::ffi", "libc"),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "an aliased import is still observed: {violations:?}"
    );
    assert_eq!(violations[0].target, "libc");
    assert_eq!(violations[0].finding, "crate::service");
}

// --- inline-symbol-path confinement (`must_not_call_inline`) ----------------------------

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")
}

#[test]
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]
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]
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]
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]
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 core;\n"),
            (
                "core.rs",
                "use std::time::{self_utc as clk, Duration};\nfn f() { let _ = clk::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a self-prefixed group alias resolves and reacts: {violations:?}"
    );
    assert!(
        violations[0].finding.contains("std::time::self_utc::now"),
        "{violations:?}"
    );
}

#[test]
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]
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]
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]
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::time::SystemTime`) — a silent miss of the confined clock (a false negative).
    let (result, violations) = run_module_check(
        "inline-defaulted-generic-alias",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "type Clock<Tz = LocalTz> = std::time::SystemTime;\nfn f() { let _ = Clock::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "the alias resolves past the defaulted generic param to its real target: {violations:?}"
    );
}

#[test]
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]
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]
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]
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]
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]
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]
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]
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]
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]
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]
fn inline_scans_a_macro_body() {
    let (result, violations) = run_module_check(
        "inline-macro",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "fn 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]
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"));
}

#[test]
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"));
}

#[test]
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).
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]
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]
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]
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 (rung iii at depth), NOT the crate-root shadow.
    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]
fn inline_strict_external_local_fn_definition_stays_clean() {
    // 4.4 FP safety — a local `fn` named like the dependency wins by local precedence (rung iv).
    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]
fn inline_strict_external_local_alias_stays_clean() {
    // 4.5 FP safety — a local `use crate::clock as time;` alias resolves through the use-map
    // (rung i, which precedes the 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 local: {violations:?}"
    );
}

#[test]
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 resolves local and does not react: {violations:?}"
    );
}

#[test]
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]
fn inline_strict_external_extern_crate_rename_is_a_stated_bound() {
    // 4.8 `extern crate chrono as chr; chr::Utc::now()` does NOT react (stated bound — the use-map
    // reads `use` only), while the bare `chrono::Utc::now()` in the same subtree does.
    let (result, violations) = confine_chrono_strict(
        "inline-strict-ext-extern",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "extern crate chrono as chr;\nfn a() { let _ = chr::Utc::now(); }\nfn b() { let _ = chrono::Utc::now(); }\n",
            ),
        ],
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "only the real-name call reacts; the extern-crate-as rename is a bound: {violations:?}"
    );
    assert!(
        violations[0].finding.contains("chrono::Utc::now"),
        "{violations:?}"
    );
}

#[test]
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]
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 label()/target/finding.
    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 identity label is unchanged by the flag"
    );
}

#[test]
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")
    );
    // 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"));
}

#[test]
fn inline_strict_external_cross_module_local_item_does_not_mask() {
    // Apply-review finding 1 (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]
fn inline_strict_external_block_local_item_does_not_mask() {
    // Apply-review finding 1 residual: 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 colliding *method*/nested `fn log` is instead a stated over-reaction bound — its definition
    // site `log(` reads as a call under a single-segment prefix — so this uses a non-call-shaped
    // `const` to isolate the depth-exclusion behaviour.)
    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]
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]
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]
fn inline_reacts_on_a_two_hop_use_realias() {
    // `use std::time::SystemTime; use self::SystemTime as Clock;` — the second use-hop
    // must chase through the file's own use-map, not only the crate-wide def closure.
    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:?}"
    );
}

#[test]
fn inline_reacts_through_a_mid_path_turbofish() {
    // `Clock::<Utc>::now()` — the mid-path turbofish must not break the path, and the
    // terminal `now` call must still react (via the resolved `std::time::SystemTime::now`).
    let (result, violations) = run_module_check(
        "inline-turbofish",
        &[
            ("lib.rs", "pub mod core;\n"),
            (
                "core.rs",
                "type Clock = std::time::SystemTime;\nfn f() { let _ = Clock::<u8>::now(); }\n",
            ),
        ],
        confine_core_clock(),
    );
    assert!(result.is_ok(), "{result:?}");
    assert_eq!(
        violations.len(),
        1,
        "a mid-path turbofish call reacts: {violations:?}"
    );
}

#[test]
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]
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(); }\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]
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]
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]
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]
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]
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]
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"));
}

#[test]
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(),
        );
        // Either clean or a violation, but it must complete (no panic / no hang) and not error out.
        assert!(
            result.is_ok(),
            "odd input must not error: {body:?} -> {result:?}"
        );
    }
}

#[test]
fn inline_in_macro_body_alias_is_a_bound() {
    // Stated bound: an alias DEFINED INSIDE a macro body is not in the enclosing use-map, 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",
                "fn 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]
fn inline_strict_external_inline_submodule_call_is_not_masked() {
    // Cardinal false-negative guard (apply-review finding 1): 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]
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]
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]
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]
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:?}"
    );
}