cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
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
//! Dependency-hygiene, Fast Tier (see todo.md §3.B, §14.2 P1
//! "Dependency-Nutzung pro Cargo-Target und `cfg` sammeln; nur eindeutige
//! `misplaced-dependency-kind`-Vorschläge erzeugen, Feature-only-Nutzung als
//! Evidenz erhalten"). This module implements `misplaced-dependency-kind`'s
//! two unambiguous cases:
//!
//! a. A `normal` dependency whose code identifier is referenced only from
//!    `Dev`-domain files (`tests/`, `examples/`, `benches/`), never from
//!    `Normal`-domain files — it probably belongs in `[dev-dependencies]`.
//! b. A `build` dependency whose code identifier is never referenced from
//!    `build.rs` — it appears unused by the build script.
//!
//! The third case from todo.md §3.B's table — "a target dependency could be
//! declared more narrowly" — is intentionally *not* implemented here: it
//! needs correlating usage sites with the specific `cfg(...)` predicate
//! guarding them, which is Deep-Tier-grade semantic analysis, not something a
//! directory-convention heuristic can support without false positives.
//!
//! It also implements two usage-based rules built on top of the same
//! per-crate usage evidence (todo.md §B): `unused-dev-dependency` (a
//! `[dev-dependencies]` entry with no usage found in any `Dev`-domain file or
//! `#[cfg(test)]` module) and `heavy-dependency` (a dependency whose resolved
//! transitive footprint is large relative to how many distinct items of it
//! the crate actually references).
//!
//! `dep-without-repo` (todo.md §F) shares `heavy-dependency`'s single full
//! (non `--no-deps`) `cargo_metadata` resolve (see [`resolve_full_metadata`],
//! [`analyze_full_metadata_dependencies`]) rather than resolving again: it
//! flags a declared dependency whose own manifest has no (or an empty)
//! `repository` field. A missing `repository` field is not itself a defect —
//! private/internal crates legitimately omit it — so this is reported as
//! `Severity::Info`, the same hygiene-signal precedent as `heavy-dependency`.
//!
//! ## Usage-domain classification
//!
//! Source files are classified into a [`UsageDomain`] purely by path
//! convention relative to the crate root — `tests/`, `examples/`, `benches/`
//! → `Dev`; `build.rs` → `Build`; everything else → `Normal`. This is a
//! heuristic, not module-graph resolution (see todo.md §2.1 "heuristisch,
//! false positives möglich"): a file could in principle be wired into the
//! build in an unconventional way that this classification misses.
//!
//! ## Feature-only evidence
//!
//! A dependency that is never referenced by identifier *anywhere* but that
//! declares a non-empty `features` list is deliberately **not** turned into a
//! misplaced-kind finding — judge cannot see which code path a feature
//! enables, so asserting a kind mismatch there would be an unbacked claim.
//! Such dependencies are still recorded in `feature_only_candidates`, and
//! also drive two further findings built on that same zero-usage evidence
//! (todo.md §B) — never on knowledge of a specific dependency's feature
//! vocabulary:
//!
//! - **`unused-feature-flag`**: one finding per declared feature name, for a
//!   dependency with zero usage found anywhere (the case above). Deliberately
//!   does *not* cover prominent "bundle" features with a well-known naming
//!   convention (e.g. `tokio = { features = ["full"] }`), even when the
//!   dependency itself *is* used — recognizing those needs a hardcoded
//!   feature vocabulary per dependency, which judge does not maintain.
//! - **`default-features-unused`**: a dependency whose manifest entry
//!   explicitly sets `default-features = true` — the raw TOML text says so
//!   (see [`manifest_explicitly_enables_default_features`]), not just
//!   Cargo's own implicit default — and that has the same zero-usage
//!   evidence as above. Deliberately does *not* cover "used, but only
//!   non-default features": telling default from non-default items apart
//!   needs per-dependency feature-to-symbol knowledge judge does not have.
//!
//! ## `unused-feature` (todo.md §A)
//!
//! A different direction from the two rules above: not a *dependency's*
//! feature, but a feature *this crate itself* declares in its own
//! `[features]` table (read from the same already-parsed manifest
//! [`read_manifest_toml`] gives `default-features-unused`) with no
//! `#[cfg(feature = "...")]`/`#[cfg_attr(..., feature = "...")]`/
//! `cfg!(feature = "...")` reference to it found anywhere in the crate's own
//! authored source (see [`feature_is_referenced`]) — a plain substring scan
//! for the two common spacing variants (`feature = "x"`/`feature="x"`), not
//! a `syn`/token-tree parse of the `cfg` predicate: both attribute and macro
//! forms use identical text for the part this rule cares about, so a full
//! parse would add complexity without changing what's detected.
//!
//! Two features are always out of scope, not just filtered by evidence: the
//! well-known `default` (its entire purpose is enabling *other* features, so
//! not being individually `cfg`-tested is normal, not a defect), and any
//! feature whose own declared value list is *non-empty* (see
//! [`declared_features_without_implications`]) — such a feature enables
//! other features/optional dependencies by existing at all, which is a real
//! effect even if no code ever tests for it directly with `cfg`; treating
//! that as "unused" would be a real false-positive class (umbrella/bundle
//! features like `full = ["foo", "bar"]` are a common, legitimate pattern).
//! ## Importing rustc's `unused_crate_dependencies` lint
//!
//! [`analyze_rustc_unused_dependencies`] runs `cargo check --workspace
//! --all-targets` with rustc's stable, allow-by-default
//! `unused_crate_dependencies` lint turned on (`-W unused_crate_dependencies`
//! — a stable rustc lint, not nightly-only; do not confuse it with Cargo's
//! separate, narrower, nightly-only `unused_workspace_dependencies` lint,
//! which only checks `[workspace.dependencies]` inheritance). It is opt-in
//! (`cargo judge deps --check-rustc-lints`) — a full `cargo check` is a
//! different order of cost than the rest of this module's instant syntactic
//! passes, so it never runs as part of [`analyze_workspace`], bare `cargo
//! judge`/`audit`, or `cargo judge deps` without the flag.
//!
//! The raw lint runs once per compiled unit (Cargo target: `lib`, each
//! `[[test]]`/`[[example]]`/`[[bench]]`, ...), each with its own `--extern`
//! set, and is documented to false-positive on multi-target packages: a
//! dependency used only by one target (e.g. a normal dependency referenced
//! solely from an integration test) is reported "unused" by every *other*
//! target's compilation. judge closes that gap by only turning a dependency
//! into a finding when it is reported unused in *every* target compiled for
//! its package — the intersection over all target runs, never a union (see
//! [`analyze_rustc_unused_dependencies`]). Restricted to `normal`
//! dependencies: `dev`/`build` dependencies are out of scope here
//! (`dev-dependencies` already has its own `unused-dev-dependency` detector
//! above, built on judge's own usage scan rather than an imported lint).
//!
//! ## `cargo judge deps --why <crate>` (GitHub issue #22)
//!
//! [`why`] is a query view over the same per-crate usage evidence
//! `analyze_workspace` already computes, not a new detector: it emits no
//! findings. [`collect_crate_usage`]'s `code_identifier -> domains observed`
//! map (what every rule above needs) collapses each usage down to a
//! [`UsageDomain`] set; `why` instead keeps every usage's file:line location,
//! via a fresh, narrower per-dependency parse ([`collect_usage_sites`]) —
//! `--why` is opt-in and scoped to one dependency, so re-parsing the crate's
//! source files once more for it is cheap and keeps `analyze_workspace`'s
//! hot path unchanged. It also resolves the dependency graph path(s) from
//! this workspace's own crate(s) to the named dependency
//! ([`resolve_graph_paths`]) via a second, plain `cargo metadata` resolve —
//! [`resolve_full_metadata`]'s own resolve discards its adjacency map once
//! each node's reachable-set *size* is computed, so it isn't reused here.
//!
//! Public API exposure (does this dependency's type appear in this crate's
//! own `pub fn`/`pub struct` signatures?) is reported as an explicit
//! analysis limitation rather than computed. `judge::rules::api_surface_deep`
//! does resolve exactly this question (`leaked_dependency_type`), but only
//! via a full `ra_ap_hir` semantic database — Deep Tier, `--features deep`,
//! its own expensive setup. Running that as a side effect of a Fast-Tier
//! query command would be a different order of cost than everything else
//! `--why` reports, and a real architecture decision of its own — left as a
//! stated limitation rather than guessed at here (see `cargo judge
//! api-surface`, built with `--features deep`, for that check instead).

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::{Path, PathBuf};

use serde::Serialize;
use syn::visit::{self, Visit};
use syn::{ItemUse, UseTree};

use crate::finding::{EvidenceClass, Finding, Location, OneBasedLine, Origin, Severity};
use crate::functions::read_and_parse_source;
use crate::ingest::{CrateInfo, DependencyKind, Workspace};

/// Rule id used for misplaced-dependency-kind findings (see todo.md §3.B).
pub const MISPLACED_DEPENDENCY_KIND_RULE: &str = "misplaced-dependency-kind";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const MISPLACED_DEPENDENCY_KIND_RULE_REVISION: u32 = 1;

/// Rule id used for unused-dev-dependency findings (see todo.md §B).
pub const UNUSED_DEV_DEPENDENCY_RULE: &str = "unused-dev-dependency";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const UNUSED_DEV_DEPENDENCY_RULE_REVISION: u32 = 1;

/// Rule id used for heavy-dependency findings (see todo.md §B).
pub const HEAVY_DEPENDENCY_RULE: &str = "heavy-dependency";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const HEAVY_DEPENDENCY_RULE_REVISION: u32 = 1;

/// Rule id used for unused-feature-flag findings (see todo.md §B, module
/// docs "Feature-only evidence").
pub const UNUSED_FEATURE_FLAG_RULE: &str = "unused-feature-flag";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const UNUSED_FEATURE_FLAG_RULE_REVISION: u32 = 1;

/// Rule id used for default-features-unused findings (see todo.md §B, module
/// docs "Feature-only evidence").
pub const DEFAULT_FEATURES_UNUSED_RULE: &str = "default-features-unused";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const DEFAULT_FEATURES_UNUSED_RULE_REVISION: u32 = 1;

/// Rule id used for unused-feature findings (see todo.md §A, module docs
/// "`unused-feature`").
pub const UNUSED_FEATURE_RULE: &str = "unused-feature";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const UNUSED_FEATURE_RULE_REVISION: u32 = 1;

/// Rule id used for unused-dependency findings — imports rustc's stable
/// `unused_crate_dependencies` lint (see module docs "Importing rustc's
/// `unused_crate_dependencies` lint", todo.md §B).
pub const UNUSED_DEPENDENCY_RULE: &str = "unused-dependency";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const UNUSED_DEPENDENCY_RULE_REVISION: u32 = 1;

/// Rule id used for dep-without-repo findings (see todo.md §F): a dependency
/// whose own manifest declares no `repository` field, read from the same
/// full `cargo_metadata` resolve as `heavy-dependency` (see
/// [`resolve_full_metadata`]).
pub const DEP_WITHOUT_REPO_RULE: &str = "dep-without-repo";
/// Bump when the rule's logic changes (see todo.md §5 "Regelversions-Schutz").
pub const DEP_WITHOUT_REPO_RULE_REVISION: u32 = 1;

/// Above this many transitive dependencies (from a full, non `--no-deps`
/// resolve — see [`resolve_full_metadata`]), combined with
/// fewer than [`HEAVY_DEPENDENCY_USED_ITEMS_THRESHOLD`] distinct items used
/// from it, a dependency is flagged as heavy for its usage footprint (see
/// `is_heavy_dependency`).
const HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD: usize = 20;
/// See [`HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD`].
const HEAVY_DEPENDENCY_USED_ITEMS_THRESHOLD: usize = 3;

/// Above this many declared features, judge doesn't assert that a `normal`
/// dependency used only in `Dev`-domain files should move to
/// `dev-dependencies`: a longer feature list is itself weak evidence that the
/// dependency does more than identifier scanning can see (the same concern
/// that motivates the feature-only-evidence bucket for zero-usage
/// dependencies, just short of zero usage here).
const SHORT_FEATURE_LIST_MAX: usize = 1;

/// Where a source file sits, classified purely by path convention relative
/// to its crate root (Fast Tier, directory-convention heuristic — not exact
/// module-graph resolution, see todo.md §2.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UsageDomain {
    Normal,
    Dev,
    Build,
}

impl UsageDomain {
    /// The short, lowercase label used in `cargo judge deps --why`'s TTY
    /// output (see [`why`], GitHub issue #22) — mirrors
    /// [`DependencyKind::label`]'s precedent rather than a bare `{:?}`.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Dev => "dev",
            Self::Build => "build",
        }
    }
}

/// Classifies `relative` (a source file path relative to its crate root).
pub(crate) fn classify_domain(relative: &Path) -> UsageDomain {
    if relative == Path::new("build.rs") {
        return UsageDomain::Build;
    }
    let is_dev_dir = matches!(
        relative.components().next(),
        Some(std::path::Component::Normal(name))
            if name == "tests" || name == "examples" || name == "benches"
    );
    if is_dev_dir {
        UsageDomain::Dev
    } else {
        UsageDomain::Normal
    }
}

#[derive(Debug)]
pub enum DepsError {
    Io(PathBuf, std::io::Error),
    Parse(PathBuf, syn::Error),
    /// A full (non `--no-deps`) `cargo metadata` resolve failed — only
    /// produced by `heavy-dependency`'s transitive-count lookup and
    /// `dep-without-repo`'s repository-field lookup, which share one resolve
    /// (see [`resolve_full_metadata`]).
    Metadata(cargo_metadata::Error),
    /// A crate's manifest failed to parse as TOML — only produced by
    /// `default-features-unused`'s manifest lookup (see
    /// `manifest_explicitly_enables_default_features`), which reads the raw
    /// manifest text directly rather than trusting `cargo_metadata`.
    ManifestParse(PathBuf, toml::de::Error),
    /// The `cargo check` run behind `unused-dependency`'s rustc-lint import
    /// (see [`analyze_rustc_unused_dependencies`]) did not complete: either
    /// the `cargo` binary failed to spawn, or `cargo check --workspace
    /// --all-targets` exited unsuccessfully (e.g. the workspace does not
    /// currently compile). Collected as a report error, never a panic or a
    /// finding — judge cannot assert anything about dependency usage from a
    /// build it could not observe (todo.md §B "Graceful Degradation").
    RustcCheck(String),
}

impl std::fmt::Display for DepsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(path, err) => write!(f, "{}: failed to read file: {err}", path.display()),
            Self::Parse(path, err) => write!(f, "{}: failed to parse: {err}", path.display()),
            Self::Metadata(err) => write!(f, "failed to resolve full dependency graph: {err}"),
            Self::ManifestParse(path, err) => {
                write!(f, "{}: failed to parse: {err}", path.display())
            }
            Self::RustcCheck(msg) => write!(f, "{msg}"),
        }
    }
}

impl std::error::Error for DepsError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(_, err) => Some(err),
            Self::Parse(_, err) => Some(err),
            Self::Metadata(err) => Some(err),
            Self::ManifestParse(_, err) => Some(err),
            Self::RustcCheck(_) => None,
        }
    }
}

/// Aggregated dependency-hygiene results across a workspace.
#[derive(Debug, Default)]
pub struct WorkspaceDeps {
    pub findings: Vec<Finding>,
    /// Dependencies with zero identifier usages found anywhere, but a
    /// non-empty `features` list (see module docs "Feature-only evidence").
    /// Kept alongside the `unused-feature-flag` findings derived from the
    /// same evidence, for a human to skim the affected dependency names at a
    /// glance.
    pub feature_only_candidates: Vec<String>,
    pub errors: Vec<DepsError>,
}

/// Runs the `misplaced-dependency-kind` detector over every crate in
/// `workspace`.
///
/// Unlike [`crate::rules::complexity::analyze_workspace`] and
/// [`crate::rules::duplication::analyze_workspace`], which take a flat iterator of
/// `&SourceFile`, this detector needs a crate's declared dependencies *and*
/// its source files together to correlate usage — it is fundamentally
/// per-crate. Flattening to a cross-crate iterator of source files first
/// would throw away exactly the grouping this rule depends on, so this takes
/// the whole [`Workspace`] instead.
pub fn analyze_workspace(workspace: &Workspace) -> WorkspaceDeps {
    let mut findings = Vec::new();
    let mut feature_only_candidates = Vec::new();
    let mut errors = Vec::new();

    for krate in &workspace.crates {
        let (usage, failed_domains, crate_errors) = collect_crate_usage(krate);
        errors.extend(crate_errors);
        let manifest = read_manifest_toml(&krate.manifest_path, &mut errors);

        for dep in &krate.dependencies {
            let domains = usage.get(&dep.code_identifier);
            let has_normal = domains.is_some_and(|d| d.contains(&UsageDomain::Normal));
            let has_dev = domains.is_some_and(|d| d.contains(&UsageDomain::Dev));
            let has_build = domains.is_some_and(|d| d.contains(&UsageDomain::Build));
            let used_anywhere = domains.is_some_and(|d| !d.is_empty());
            let zero_usage = !used_anywhere && failed_domains.is_empty();

            if zero_usage && !dep.features.is_empty() {
                feature_only_candidates.push(dep.name.clone());
                findings.extend(unused_feature_flag_findings(krate, dep));
            }

            if zero_usage
                && manifest.as_ref().is_some_and(|manifest| {
                    manifest_explicitly_enables_default_features(manifest, &dep.name)
                })
            {
                findings.push(default_features_unused_finding(krate, dep));
            }

            if zero_usage && !dep.features.is_empty() {
                continue;
            }

            if dep.kind == DependencyKind::Development
                && !has_dev
                && failed_domains.is_empty()
                && !krate.dependencies.iter().any(|other| {
                    other.name == dep.name && other.kind != DependencyKind::Development
                })
            {
                findings.push(unused_dev_dependency_finding(krate, dep));
            }

            let flagged = match dep.kind {
                DependencyKind::Normal => {
                    has_dev
                        && !has_normal
                        && dep.features.len() <= SHORT_FEATURE_LIST_MAX
                        && !failed_domains.contains(&UsageDomain::Normal)
                }
                DependencyKind::Build => {
                    !has_build && !failed_domains.contains(&UsageDomain::Build)
                }
                DependencyKind::Development => false,
            };

            if flagged {
                findings.push(misplaced_finding(krate, dep));
            }
        }

        if let Some(manifest) = &manifest {
            for feature_name in declared_features_without_implications(manifest) {
                if !feature_is_referenced(krate, &feature_name) {
                    findings.push(unused_feature_finding(krate, &feature_name));
                }
            }
        }
    }

    let (metadata_findings, metadata_errors) = analyze_full_metadata_dependencies(workspace);
    findings.extend(metadata_findings);
    errors.extend(metadata_errors);

    WorkspaceDeps {
        findings,
        feature_only_candidates,
        errors,
    }
}

/// Stated once and reused by both [`why`]'s TTY and JSON rendering (via the
/// `--why` CLI command) — the honest answer to "does this dependency's type
/// appear in this crate's own public API surface" is a fixed limitation
/// statement, not a computed value (see module docs "`cargo judge deps --why
/// <crate>`").
const PUBLIC_API_EXPOSURE_LIMITATION: &str = "not determined \u{2014} public API exposure requires Deep-Tier semantic analysis (see `cargo judge api-surface`, built with `--features deep`); this Fast-Tier query cannot resolve whether this dependency's types appear in this crate's own public API surface";

/// One location where a dependency's `code_identifier` was found referenced
/// in source — the evidence [`why`] shows for "source usages" (GitHub issue
/// #22). Unlike [`collect_crate_usage`]'s aggregated `code_identifier ->
/// domains observed` map (all of `analyze_workspace`'s rules need only
/// that), this keeps the file:line, collected by [`collect_usage_sites`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DependencyUsageSite {
    pub file: PathBuf,
    pub line: OneBasedLine,
    pub domain: UsageDomain,
}

/// One workspace crate's declaration of the dependency named in a [`why`]
/// query, plus every usage site [`collect_usage_sites`] found for it in that
/// crate's own source files.
#[derive(Debug, Serialize)]
pub struct DependencyDeclaration {
    pub crate_name: String,
    pub kind: DependencyKind,
    pub features: Vec<String>,
    /// Whether the manifest explicitly sets `default-features = true` (see
    /// [`manifest_explicitly_enables_default_features`]) — `false` also
    /// covers "the manifest's `default-features` key is simply absent", the
    /// same ambiguity that function's own doc comment explains.
    pub default_features_explicit: bool,
    pub target: Option<String>,
    pub usages: Vec<DependencyUsageSite>,
}

/// [`why`]'s full result — `cargo judge deps --why <crate>` (GitHub issue
/// #22). Not a [`WorkspaceDeps`]: a query view produces no findings and
/// affects no verdict.
#[derive(Debug)]
pub struct DependencyWhyReport {
    pub dependency_name: String,
    /// Whether `dependency_name` was found anywhere: as a dependency
    /// declared by any workspace crate, or as a package anywhere in the
    /// resolved dependency graph (see [`resolve_graph_paths`]). `false` is
    /// the CLI's "not found" case.
    pub found: bool,
    pub declared_by: Vec<DependencyDeclaration>,
    /// Per workspace crate name, the shortest resolved-graph path from that
    /// crate to `dependency_name` (see [`resolve_graph_paths`]) — package
    /// names from the first hop (exclusive of the crate itself) to
    /// `dependency_name` (inclusive). An empty `Vec` means no path was found
    /// from that crate (including the crate declaring it directly, which
    /// still has a one-element path).
    pub graph_paths: HashMap<String, Vec<String>>,
    pub public_api_exposure: &'static str,
    pub errors: Vec<DepsError>,
}

/// Runs `cargo judge deps --why <crate>` (GitHub issue #22, see module docs
/// "`cargo judge deps --why <crate>`"): every workspace crate's declaration
/// of `dependency_name` (kind, features, `default-features = true`?, and
/// every source location its code identifier is referenced from), plus the
/// resolved dependency-graph path(s) reaching it. A query view, not a new
/// detector — it never produces [`Finding`]s.
pub fn why(workspace: &Workspace, dependency_name: &str) -> DependencyWhyReport {
    let mut errors = Vec::new();
    let mut declared_by = Vec::new();

    for krate in &workspace.crates {
        for dep in &krate.dependencies {
            if dep.name != dependency_name {
                continue;
            }
            let manifest = read_manifest_toml(&krate.manifest_path, &mut errors);
            let default_features_explicit = manifest.as_ref().is_some_and(|manifest| {
                manifest_explicitly_enables_default_features(manifest, &dep.name)
            });
            let (usages, usage_errors) = collect_usage_sites(krate, &dep.code_identifier);
            errors.extend(usage_errors);
            declared_by.push(DependencyDeclaration {
                crate_name: krate.name.clone(),
                kind: dep.kind,
                features: dep.features.clone(),
                default_features_explicit,
                target: dep.target.clone(),
                usages,
            });
        }
    }

    let manifest_path = workspace.root.join("Cargo.toml");
    let (found_in_graph, graph_paths) = match resolve_graph_paths(&manifest_path, dependency_name) {
        Ok(result) => result,
        Err(err) => {
            errors.push(DepsError::Metadata(err));
            (false, HashMap::new())
        }
    };

    DependencyWhyReport {
        dependency_name: dependency_name.to_string(),
        found: found_in_graph || !declared_by.is_empty(),
        declared_by,
        graph_paths,
        public_api_exposure: PUBLIC_API_EXPOSURE_LIMITATION,
        errors,
    }
}

/// Every location in `krate`'s own source files where `target` (a
/// dependency's `code_identifier`) is referenced by identifier — the
/// evidence behind [`why`]'s "source usages". Parses each source file fresh
/// via [`WhySiteCollector`] rather than sharing [`collect_crate_usage`]'s
/// aggregated pass (see [`DependencyUsageSite`]'s doc comment for why). A
/// file that fails to read or parse contributes a [`DepsError`] rather than
/// being silently skipped: `--why`'s acceptance criterion is to identify
/// every usage with a location or state its analysis limitation, so a gap in
/// what it could examine has to surface, not pass silently as "no more
/// usages found".
fn collect_usage_sites(
    krate: &CrateInfo,
    target: &str,
) -> (Vec<DependencyUsageSite>, Vec<DepsError>) {
    let mut sites = Vec::new();
    let mut errors = Vec::new();

    for file in &krate.source_files {
        let relative = file
            .path
            .strip_prefix(&krate.root)
            .unwrap_or(file.path.as_path());
        let domain = classify_domain(relative);

        match read_and_parse_source(
            &file.path,
            |err| DepsError::Io(file.path.clone(), err),
            |err| DepsError::Parse(file.path.clone(), err),
        ) {
            Ok((_, ast)) => {
                let mut collector = WhySiteCollector {
                    target,
                    file: &file.path,
                    domain,
                    sites: Vec::new(),
                };
                collector.visit_file(&ast);
                sites.extend(collector.sites);
            }
            Err(err) => errors.push(err),
        }
    }

    sites.sort_by(|a, b| a.file.cmp(&b.file).then(a.line.cmp(&b.line)));
    sites.dedup();
    (sites, errors)
}

/// Records every span where `target` appears as the first segment of a
/// referenced path or `use` tree — the same walk [`PathIdentCollector`] does
/// for [`collect_crate_usage`], narrowed to one identifier and keeping the
/// span (via `syn::Ident::span`) instead of only recording "this identifier
/// was seen somewhere".
struct WhySiteCollector<'a> {
    target: &'a str,
    file: &'a Path,
    domain: UsageDomain,
    sites: Vec<DependencyUsageSite>,
}

impl WhySiteCollector<'_> {
    fn record(&mut self, ident: &proc_macro2::Ident) {
        if *ident != self.target {
            return;
        }
        if let Some(line) = OneBasedLine::new(ident.span().start().line) {
            self.sites.push(DependencyUsageSite {
                file: self.file.to_path_buf(),
                line,
                domain: self.domain,
            });
        }
    }

    /// Mirrors [`PathIdentCollector::walk_use_tree`]: `UseTree` has no
    /// `syn::Path` node, so `visit_path` never sees `use` items.
    fn walk_use_tree(&mut self, tree: &UseTree) {
        match tree {
            UseTree::Path(use_path) => self.record(&use_path.ident),
            UseTree::Name(use_name) => self.record(&use_name.ident),
            UseTree::Rename(use_rename) => self.record(&use_rename.ident),
            UseTree::Glob(_) => {}
            UseTree::Group(group) => {
                for item in &group.items {
                    self.walk_use_tree(item);
                }
            }
        }
    }
}

impl<'ast> Visit<'ast> for WhySiteCollector<'_> {
    fn visit_item_use(&mut self, node: &'ast ItemUse) {
        self.walk_use_tree(&node.tree);
    }

    fn visit_path(&mut self, node: &'ast syn::Path) {
        if let Some(first) = node.segments.first() {
            self.record(&first.ident);
        }
        visit::visit_path(self, node);
    }
}

/// Resolved dependency-graph paths from every workspace crate to
/// `dependency_name`, via a plain full (non `--no-deps`) `cargo metadata`
/// resolve. Not shared with [`resolve_full_metadata`]: that resolve needs
/// the same graph shape, but discards its `adjacency` map once each node's
/// reachable-set *size* is computed, while this needs the edges themselves.
/// Returns `(found, paths)`: `found` is whether any package in the resolved
/// graph is named `dependency_name` at all (independent of reachability from
/// a workspace crate); `paths` maps each workspace crate's own name to the
/// *shortest* resolved-graph path (breadth-first, so at most one path per
/// workspace crate — an example route, not an exhaustive enumeration of
/// every path) from that crate to `dependency_name`.
fn resolve_graph_paths(
    manifest_path: &Path,
    dependency_name: &str,
) -> Result<(bool, HashMap<String, Vec<String>>), cargo_metadata::Error> {
    let metadata = cargo_metadata::MetadataCommand::new()
        .manifest_path(manifest_path)
        .exec()?;

    let found = metadata
        .packages
        .iter()
        .any(|package| package.name.as_str() == dependency_name);

    let Some(resolve) = metadata.resolve else {
        return Ok((found, HashMap::new()));
    };

    let adjacency: HashMap<&cargo_metadata::PackageId, &[cargo_metadata::PackageId]> = resolve
        .nodes
        .iter()
        .map(|node| (&node.id, node.dependencies.as_slice()))
        .collect();
    let id_to_name: HashMap<&cargo_metadata::PackageId, &str> = metadata
        .packages
        .iter()
        .map(|package| (&package.id, package.name.as_str()))
        .collect();

    let mut paths: HashMap<String, Vec<String>> = HashMap::new();
    for member_id in &metadata.workspace_members {
        let Some(&member_name) = id_to_name.get(member_id) else {
            continue;
        };
        let path = shortest_graph_path(&adjacency, &id_to_name, member_id, dependency_name);
        paths.insert(member_name.to_string(), path);
    }

    Ok((found, paths))
}

/// Breadth-first shortest path from `start` to the first node named
/// `target_name`, over `adjacency` (see [`resolve_graph_paths`]) — package
/// names from the first hop (exclusive of `start`) to the target
/// (inclusive), or an empty `Vec` if no such node is reachable from `start`.
fn shortest_graph_path(
    adjacency: &HashMap<&cargo_metadata::PackageId, &[cargo_metadata::PackageId]>,
    id_to_name: &HashMap<&cargo_metadata::PackageId, &str>,
    start: &cargo_metadata::PackageId,
    target_name: &str,
) -> Vec<String> {
    let mut visited: HashSet<&cargo_metadata::PackageId> = HashSet::new();
    visited.insert(start);
    let mut queue: VecDeque<(&cargo_metadata::PackageId, Vec<String>)> = VecDeque::new();
    queue.push_back((start, Vec::new()));

    while let Some((current, path)) = queue.pop_front() {
        let Some(children) = adjacency.get(current) else {
            continue;
        };
        for child in children.iter() {
            if !visited.insert(child) {
                continue;
            }
            let Some(&child_name) = id_to_name.get(child) else {
                continue;
            };
            let mut next_path = path.clone();
            next_path.push(child_name.to_string());
            if child_name == target_name {
                return next_path;
            }
            queue.push_back((child, next_path));
        }
    }
    Vec::new()
}

/// Reads `manifest_path`'s raw text and parses it as TOML, mapping either
/// failure through `io_err`/`parse_err` into the caller's own error type —
/// shared by [`read_manifest_toml`] and `crate::rules::dep_graph::msrv_drift`, which
/// both need to read a manifest's raw TOML directly (bypassing
/// `cargo_metadata`) but tag failures with their own module's error enum.
pub(crate) fn read_manifest_toml_typed<E>(
    manifest_path: &Path,
    io_err: impl FnOnce(PathBuf, std::io::Error) -> E,
    parse_err: impl FnOnce(PathBuf, toml::de::Error) -> E,
) -> Result<toml::Value, E> {
    let text = std::fs::read_to_string(manifest_path)
        .map_err(|err| io_err(manifest_path.to_path_buf(), err))?;
    toml::from_str(&text).map_err(|err| parse_err(manifest_path.to_path_buf(), err))
}

/// Reads and parses `manifest_path` as TOML, once per crate — needed only by
/// `default-features-unused`'s manifest lookup (see
/// [`manifest_explicitly_enables_default_features`]): `cargo_metadata`'s
/// resolved `Dependency` doesn't distinguish an explicit `default-features =
/// true` from Cargo's own implicit default, so that rule reads the manifest
/// text directly instead. A read or parse failure is pushed to `errors` and
/// `None` is returned — the rule is then silently skipped for this crate
/// rather than asserting an unbacked claim.
fn read_manifest_toml(manifest_path: &Path, errors: &mut Vec<DepsError>) -> Option<toml::Value> {
    match read_manifest_toml_typed(manifest_path, DepsError::Io, DepsError::ManifestParse) {
        Ok(manifest) => Some(manifest),
        Err(err) => {
            errors.push(err);
            None
        }
    }
}

/// Whether `manifest`'s raw TOML text explicitly sets `default-features =
/// true` for the dependency named `dep_name`, in `[dependencies]`,
/// `[dev-dependencies]`, `[build-dependencies]`, or their per-platform
/// `[target.'cfg(...)'.*]` equivalents. Deliberately reads the manifest text
/// rather than `cargo_metadata::Dependency::uses_default_features`: that
/// field is `true` both when the manifest says so explicitly and when the
/// key is simply absent (Cargo's own default), and only the manifest text
/// itself can tell those two apart (see module docs "Feature-only
/// evidence").
fn manifest_explicitly_enables_default_features(manifest: &toml::Value, dep_name: &str) -> bool {
    const DEPENDENCY_TABLE_KEYS: [&str; 3] =
        ["dependencies", "dev-dependencies", "build-dependencies"];

    fn table_sets_default_features_true(table: &toml::Value, dep_name: &str) -> bool {
        table
            .get(dep_name)
            .and_then(|dep| dep.get("default-features"))
            .and_then(toml::Value::as_bool)
            == Some(true)
    }

    let found_at_top_level = DEPENDENCY_TABLE_KEYS.iter().any(|key| {
        manifest
            .get(key)
            .is_some_and(|table| table_sets_default_features_true(table, dep_name))
    });
    if found_at_top_level {
        return true;
    }

    manifest
        .get("target")
        .and_then(toml::Value::as_table)
        .is_some_and(|platforms| {
            platforms.values().any(|platform| {
                DEPENDENCY_TABLE_KEYS.iter().any(|key| {
                    platform
                        .get(key)
                        .is_some_and(|table| table_sets_default_features_true(table, dep_name))
                })
            })
        })
}

/// Every finding in this module is reported at the crate's manifest (line 1)
/// with the affected item name (a dependency name, or — for `unused-feature`
/// — this crate's own feature name) as `item_path`: the "location" of a
/// dependency-hygiene concern is `Cargo.toml`, not a source file. Shared by
/// every `*_finding` renderer below rather than repeating the same
/// three-field [`Location`] literal in each — also reused by
/// `crate::rules::slopsquat`'s own `*_finding` renderers, which report the same
/// convention.
pub(crate) fn dep_location(krate: &CrateInfo, item_path: impl Into<String>) -> Location {
    Location {
        file: krate.manifest_path.clone(),
        line: OneBasedLine::FIRST,
        item_path: item_path.into(),
    }
}

/// Renders a misplaced-dependency-kind finding. Its evidence class is
/// `heuristic` (todo.md §17.3: a wrong dependency kind is an
/// interpretation): usage-domain classification is a directory-convention
/// heuristic, not full module-graph resolution (see todo.md §2.1), so this
/// is suggestive rather than proven. `location.file` is the crate's manifest
/// path — the "location" of a dependency-kind mismatch is `Cargo.toml`, not
/// a source file — and `location.item_path` is the dependency name.
fn misplaced_finding(krate: &CrateInfo, dep: &crate::ingest::DeclaredDependency) -> Finding {
    Finding::new(
        format!(
            "{MISPLACED_DEPENDENCY_KIND_RULE}:{}:{}",
            krate.name, dep.name
        ),
        MISPLACED_DEPENDENCY_KIND_RULE,
        Severity::Warn,
        dep_location(krate, dep.name.clone()),
        EvidenceClass::Heuristic,
        Origin::Code,
        None,
    )
}

/// Renders an `unused-dev-dependency` finding. Its evidence class is
/// `bounded_semantic` (todo.md §17.3: "no reference found ... for the
/// searched crates/entry points") — the search is bounded to `Dev`-domain
/// files (`tests/`, `examples/`, `benches/`) and `#[cfg(test)]` modules in
/// `Normal`-domain files, and doctests are never scanned (a known gap). The
/// message and severity stay honest about that bound: `Warn`, "no use found
/// in the examined view", never an absolute "unused" claim (todo.md §17
/// language discipline). Same `location` convention as [`misplaced_finding`].
fn unused_dev_dependency_finding(
    krate: &CrateInfo,
    dep: &crate::ingest::DeclaredDependency,
) -> Finding {
    Finding::new(
        format!("{UNUSED_DEV_DEPENDENCY_RULE}:{}:{}", krate.name, dep.name),
        UNUSED_DEV_DEPENDENCY_RULE,
        Severity::Warn,
        dep_location(krate, dep.name.clone()),
        EvidenceClass::BoundedSemantic,
        Origin::Code,
        Some(serde_json::json!({
            "searched": ["tests/", "examples/", "benches/", "#[cfg(test)] modules in src/"],
            "reason": "no use found in the examined view (tests/examples/benches of this \
                package, and #[cfg(test)] modules in its src files; doctests are not scanned)",
        })),
    )
}

/// Renders one `unused-feature-flag` finding per feature name declared by
/// `dep`, for a dependency with zero identifier usages found anywhere (see
/// module docs "Feature-only evidence") — the only feature-related claim
/// judge can back without knowing what a feature enables: that the feature
/// is turned on for a dependency nothing in the examined view references at
/// all. Its evidence class is `derived_fact`: both halves of the claim (the
/// feature is declared; no usage was found) are read directly from the
/// declared inputs. Same `location` convention as [`misplaced_finding`].
fn unused_feature_flag_findings(
    krate: &CrateInfo,
    dep: &crate::ingest::DeclaredDependency,
) -> Vec<Finding> {
    dep.features
        .iter()
        .map(|feature| {
            Finding::new(
                format!(
                    "{UNUSED_FEATURE_FLAG_RULE}:{}:{}:{feature}",
                    krate.name, dep.name
                ),
                UNUSED_FEATURE_FLAG_RULE,
                Severity::Warn,
                dep_location(krate, dep.name.clone()),
                EvidenceClass::DerivedFact,
                Origin::Code,
                Some(serde_json::json!({
                    "feature": feature,
                    "reason": "no other usage of this dependency was found in the examined view",
                })),
            )
        })
        .collect()
}

/// Renders a `default-features-unused` finding: `dep`'s manifest entry
/// explicitly sets `default-features = true` (see
/// [`manifest_explicitly_enables_default_features`]) and has zero identifier
/// usages found anywhere (see module docs "Feature-only evidence"). Its
/// evidence class is `derived_fact` for the same reason as
/// [`unused_feature_flag_findings`]: both halves are read directly from the
/// declared inputs, not interpreted. Same `location` convention as
/// [`misplaced_finding`].
fn default_features_unused_finding(
    krate: &CrateInfo,
    dep: &crate::ingest::DeclaredDependency,
) -> Finding {
    Finding::new(
        format!("{DEFAULT_FEATURES_UNUSED_RULE}:{}:{}", krate.name, dep.name),
        DEFAULT_FEATURES_UNUSED_RULE,
        Severity::Warn,
        dep_location(krate, dep.name.clone()),
        EvidenceClass::DerivedFact,
        Origin::Code,
        Some(serde_json::json!({
            "reason": "no other usage of this dependency was found in the examined view, and \
                the manifest explicitly sets default-features = true",
        })),
    )
}

/// This crate's own declared `[features]` names (see module docs
/// `unused-feature`), excluding `default` and any feature whose own value
/// list is non-empty (an umbrella/bundle feature — see module docs for why
/// those are out of scope entirely, not just filtered by usage evidence).
fn declared_features_without_implications(manifest: &toml::Value) -> Vec<String> {
    let Some(table) = manifest.get("features").and_then(toml::Value::as_table) else {
        return Vec::new();
    };
    table
        .iter()
        .filter(|(name, _)| name.as_str() != "default")
        .filter(|(_, value)| {
            value
                .as_array()
                .is_some_and(|implications| implications.is_empty())
        })
        .map(|(name, _)| name.clone())
        .collect()
}

/// Whether any of `krate`'s own authored source files textually references
/// `feature_name` the way `#[cfg(feature = "...")]`/`#[cfg_attr(...,
/// feature = "...")]`/`cfg!(feature = "...")` all write it — see module docs
/// `unused-feature` for why this is a substring scan, not a `syn` parse.
/// Generated files are skipped, matching this module's other rules'
/// `Authored`-only usage scanning.
fn feature_is_referenced(krate: &CrateInfo, feature_name: &str) -> bool {
    let spaced = format!("feature = \"{feature_name}\"");
    let tight = format!("feature=\"{feature_name}\"");
    krate
        .source_files
        .iter()
        .filter(|file| file.kind.is_locally_reportable())
        .any(|file| {
            std::fs::read_to_string(&file.path)
                .is_ok_and(|text| text.contains(&spaced) || text.contains(&tight))
        })
}

/// Renders an `unused-feature` finding. Its evidence class is `derived_fact`
/// for the same reason as [`unused_feature_flag_findings`]/
/// [`default_features_unused_finding`]: the feature's declaration, its empty
/// implication list, and the absence of a textual reference in the examined
/// source are all read directly from the declared inputs, not interpreted.
fn unused_feature_finding(krate: &CrateInfo, feature_name: &str) -> Finding {
    Finding::new(
        format!("{UNUSED_FEATURE_RULE}:{}:{feature_name}", krate.name),
        UNUSED_FEATURE_RULE,
        Severity::Warn,
        dep_location(krate, feature_name.to_string()),
        EvidenceClass::DerivedFact,
        Origin::Code,
        Some(serde_json::json!({
            "feature": feature_name,
            "reason": "no `cfg(feature = \"...\")`/`cfg!(feature = \"...\")` reference to this \
                declared feature was found anywhere in the crate's own authored source",
        })),
    )
}

/// Whether a dependency counts as heavy: more than
/// [`HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD`] transitive dependencies while
/// fewer than [`HEAVY_DEPENDENCY_USED_ITEMS_THRESHOLD`] distinct items are
/// used from it. Pure and side-effect free so the threshold logic is
/// unit-testable without a `cargo metadata` resolve.
fn is_heavy_dependency(transitive_deps: usize, used_items: usize) -> bool {
    transitive_deps > HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD
        && used_items < HEAVY_DEPENDENCY_USED_ITEMS_THRESHOLD
}

/// Runs both `heavy-dependency` and `dep-without-repo` (todo.md §B, §F) over
/// every crate in `workspace`, sharing the single full (non `--no-deps`)
/// `cargo metadata` resolve both need (see [`resolve_full_metadata`]) rather
/// than running it twice. `heavy-dependency` is always `heuristic` (todo.md
/// §17.3, `evidence_class_for_rule`'s catch-all — no explicit arm for this
/// rule): the transitive count depends on feature unification and
/// platform/target resolution this Fast Tier pass doesn't fully model, and
/// "used items" is a path-segment approximation (see [`collect_used_items`]),
/// not resolved item usage. `dep-without-repo` is `derived_fact`: the
/// dependency's own `repository` field is read directly from the resolve.
fn analyze_full_metadata_dependencies(workspace: &Workspace) -> (Vec<Finding>, Vec<DepsError>) {
    let mut findings = Vec::new();
    let mut errors = Vec::new();

    let manifest_path = workspace.root.join("Cargo.toml");
    let metadata = match resolve_full_metadata(&manifest_path) {
        Ok(metadata) => metadata,
        Err(err) => {
            errors.push(DepsError::Metadata(err));
            return (findings, errors);
        }
    };

    for krate in &workspace.crates {
        for dep in &krate.dependencies {
            if let Some(&transitive_deps) = metadata.transitive_deps.get(&dep.name) {
                let used_items = collect_used_items(krate, &dep.code_identifier);
                if is_heavy_dependency(transitive_deps, used_items.len()) {
                    findings.push(heavy_dependency_finding(
                        krate,
                        dep,
                        transitive_deps,
                        &used_items,
                    ));
                }
            }

            if let Some(repository) = metadata.repository.get(&dep.name)
                && repository_is_missing(repository)
            {
                findings.push(dep_without_repo_finding(krate, dep));
            }
        }
    }

    (findings, errors)
}

/// Whether a dependency's own `repository` field counts as missing for
/// `dep-without-repo`: either the manifest omits the field entirely
/// (`None`), or it is present but blank.
fn repository_is_missing(repository: &Option<String>) -> bool {
    match repository {
        None => true,
        Some(text) => text.trim().is_empty(),
    }
}

/// Renders a `heavy-dependency` finding. Same `location` convention as
/// [`misplaced_finding`]; `evidence.examples` is a small, sorted sample of
/// the distinct used-item names, for a human to sanity-check the count.
fn heavy_dependency_finding(
    krate: &CrateInfo,
    dep: &crate::ingest::DeclaredDependency,
    transitive_deps: usize,
    used_items: &HashSet<String>,
) -> Finding {
    let mut examples: Vec<&String> = used_items.iter().collect();
    examples.sort();
    examples.truncate(5);

    Finding::new(
        format!("{HEAVY_DEPENDENCY_RULE}:{}:{}", krate.name, dep.name),
        HEAVY_DEPENDENCY_RULE,
        Severity::Info,
        dep_location(krate, dep.name.clone()),
        EvidenceClass::Heuristic,
        Origin::Code,
        Some(serde_json::json!({
            "transitive_deps": transitive_deps,
            "used_items": used_items.len(),
            "examples": examples,
        })),
    )
}

/// Renders a `dep-without-repo` finding (todo.md §F). `Severity::Info`,
/// mirroring `heavy-dependency`'s hygiene-signal precedent above: a missing
/// `repository` field is not inherently a defect — private/internal crates
/// legitimately omit it. Same `location` convention as [`misplaced_finding`].
fn dep_without_repo_finding(krate: &CrateInfo, dep: &crate::ingest::DeclaredDependency) -> Finding {
    Finding::new(
        format!("{DEP_WITHOUT_REPO_RULE}:{}:{}", krate.name, dep.name),
        DEP_WITHOUT_REPO_RULE,
        Severity::Info,
        dep_location(krate, dep.name.clone()),
        EvidenceClass::DerivedFact,
        Origin::Code,
        Some(serde_json::json!({
            "reason": "no `repository` field found in this dependency's own manifest",
        })),
    )
}

/// Package metadata read from a single full (non `--no-deps`)
/// `cargo_metadata` resolve, shared by [`analyze_full_metadata_dependencies`]
/// — needed for `heavy-dependency`/`dep-without-repo`, which
/// [`crate::ingest::load`]'s deliberately `--no-deps` ingest (todo.md §14.2
/// P1) cannot answer either half of.
#[derive(Debug, Default)]
struct FullMetadataResolve {
    /// Package name -> count of distinct transitive dependencies (see
    /// [`is_heavy_dependency`]).
    transitive_deps: HashMap<String, usize>,
    /// Package name -> its own manifest's `repository` field, exactly as
    /// `cargo_metadata` read it (`None` when the manifest omits the field
    /// entirely — see [`repository_is_missing`]).
    repository: HashMap<String, Option<String>>,
}

/// Runs a full (non `--no-deps`) `cargo metadata` resolve and reads both
/// pieces of package metadata `heavy-dependency` and `dep-without-repo` need
/// from it (see [`FullMetadataResolve`]) — one resolve, not two. Runs its own
/// metadata command rather than reusing another module's resolve: a parallel
/// `dep_graph.rs` effort resolves a full graph too, for its own manifest/graph
/// rules; consolidating the two runs into one is left as follow-up work.
fn resolve_full_metadata(
    manifest_path: &Path,
) -> Result<FullMetadataResolve, cargo_metadata::Error> {
    let metadata = cargo_metadata::MetadataCommand::new()
        .manifest_path(manifest_path)
        .exec()?;
    let repository: HashMap<String, Option<String>> = metadata
        .packages
        .iter()
        .map(|package| (package.name.to_string(), package.repository.clone()))
        .collect();
    let Some(resolve) = metadata.resolve else {
        return Ok(FullMetadataResolve {
            transitive_deps: HashMap::new(),
            repository,
        });
    };

    let adjacency: HashMap<&cargo_metadata::PackageId, &[cargo_metadata::PackageId]> = resolve
        .nodes
        .iter()
        .map(|node| (&node.id, node.dependencies.as_slice()))
        .collect();
    let id_to_name: HashMap<&cargo_metadata::PackageId, String> = metadata
        .packages
        .iter()
        .map(|package| (&package.id, package.name.to_string()))
        .collect();

    let mut transitive_deps: HashMap<String, usize> = HashMap::new();
    for node in &resolve.nodes {
        let mut visited: HashSet<&cargo_metadata::PackageId> = HashSet::new();
        let mut stack: Vec<&cargo_metadata::PackageId> = node.dependencies.iter().collect();
        while let Some(dep_id) = stack.pop() {
            if visited.insert(dep_id)
                && let Some(children) = adjacency.get(dep_id)
            {
                stack.extend(children.iter());
            }
        }
        if let Some(name) = id_to_name.get(&node.id) {
            transitive_deps.entry(name.clone()).or_insert(visited.len());
        }
    }
    Ok(FullMetadataResolve {
        transitive_deps,
        repository,
    })
}

/// Result of [`analyze_rustc_unused_dependencies`] — kept separate from
/// [`WorkspaceDeps`] since this detector is opt-in and invoked by its own
/// caller (`cargo judge deps --check-rustc-lints`), never folded into
/// [`analyze_workspace`]'s always-on pass.
#[derive(Debug, Default)]
pub struct RustcLintDeps {
    pub findings: Vec<Finding>,
    pub errors: Vec<DepsError>,
}

/// Runs `cargo check --workspace --all-targets` with rustc's stable,
/// allow-by-default `unused_crate_dependencies` lint turned on and turns its
/// diagnostics into `unused-dependency` findings (see module docs "Importing
/// rustc's `unused_crate_dependencies` lint", todo.md §B). Opt-in only
/// (`cargo judge deps --check-rustc-lints`) — unlike every other detector in
/// this module, this one runs a full `cargo check`, not an instant syntactic
/// pass, so it is never part of [`analyze_workspace`] or bare `cargo judge`.
pub fn analyze_rustc_unused_dependencies(workspace: &Workspace) -> RustcLintDeps {
    let mut findings = Vec::new();
    let mut errors = Vec::new();

    let manifest_path = workspace.root.join("Cargo.toml");
    let metadata = match cargo_metadata::MetadataCommand::new()
        .manifest_path(&manifest_path)
        .no_deps()
        .exec()
    {
        Ok(metadata) => metadata,
        Err(err) => {
            errors.push(DepsError::Metadata(err));
            return RustcLintDeps { findings, errors };
        }
    };

    let workspace_members: HashSet<cargo_metadata::PackageId> =
        metadata.workspace_members.iter().cloned().collect();
    let name_to_id: HashMap<&str, cargo_metadata::PackageId> = metadata
        .packages
        .iter()
        .filter(|package| workspace_members.contains(&package.id))
        .map(|package| (package.name.as_str(), package.id.clone()))
        .collect();

    let messages = match run_cargo_check_with_unused_crate_dependencies_lint(&manifest_path) {
        Ok(messages) => messages,
        Err(err) => {
            errors.push(err);
            return RustcLintDeps { findings, errors };
        }
    };

    // Per package, every distinct target compiled (see `target_identity`) —
    // the universe the intersection below runs over.
    let mut targets_seen: HashMap<cargo_metadata::PackageId, HashSet<String>> = HashMap::new();
    // Per (package, target), the dependency identifiers rustc reported
    // unused for that one compiled unit.
    let mut unused_per_target: HashMap<(cargo_metadata::PackageId, String), HashSet<String>> =
        HashMap::new();

    for message in messages {
        match message {
            cargo_metadata::Message::CompilerArtifact(artifact) => {
                if !workspace_members.contains(&artifact.package_id) {
                    continue;
                }
                targets_seen
                    .entry(artifact.package_id)
                    .or_default()
                    .insert(target_identity(&artifact.target));
            }
            cargo_metadata::Message::CompilerMessage(compiler_message) => {
                if !workspace_members.contains(&compiler_message.package_id) {
                    continue;
                }
                let is_unused_crate_dependency = compiler_message
                    .message
                    .code
                    .as_ref()
                    .is_some_and(|code| code.code == "unused_crate_dependencies");
                if !is_unused_crate_dependency {
                    continue;
                }
                let Some(dep_identifier) =
                    extract_unused_crate_name(&compiler_message.message.message)
                else {
                    continue;
                };
                unused_per_target
                    .entry((
                        compiler_message.package_id,
                        target_identity(&compiler_message.target),
                    ))
                    .or_default()
                    .insert(dep_identifier);
            }
            _ => {}
        }
    }

    for krate in &workspace.crates {
        let Some(package_id) = name_to_id.get(krate.name.as_str()) else {
            continue;
        };
        let Some(all_targets) = targets_seen.get(package_id) else {
            continue;
        };
        if all_targets.is_empty() {
            continue;
        }

        // Multi-target false-positive gap (see module docs): only a
        // dependency reported unused in *every* target run of this package
        // is finding-worthy — the intersection, not the union.
        let mut always_unused: Option<HashSet<String>> = None;
        for target in all_targets {
            let unused_here = unused_per_target
                .get(&(package_id.clone(), target.clone()))
                .cloned()
                .unwrap_or_default();
            always_unused = Some(match always_unused {
                None => unused_here,
                Some(acc) => acc.intersection(&unused_here).cloned().collect(),
            });
        }
        let Some(always_unused) = always_unused else {
            continue;
        };

        let mut targets_checked: Vec<&String> = all_targets.iter().collect();
        targets_checked.sort();

        for dep_identifier in &always_unused {
            let Some(dep) = krate.dependencies.iter().find(|dep| {
                dep.kind == DependencyKind::Normal && dep.code_identifier == *dep_identifier
            }) else {
                continue;
            };
            findings.push(unused_dependency_finding(krate, dep, &targets_checked));
        }
    }

    RustcLintDeps { findings, errors }
}

/// A target's identity for the purposes of the multi-target intersection in
/// [`analyze_rustc_unused_dependencies`]: its Cargo target kind(s) (`lib`,
/// `test`, `example`, `bench`, ...) and name, e.g. `"lib:mycrate"` or
/// `"test:it"`. Deliberately not further split by the `profile.test` build
/// variant — the crate's own unit-test compile of `lib`/`bin` shares this
/// same identity with its non-test compile, since both compile the same
/// source file and "target" here means what `Cargo.toml` itself calls a
/// target, not each individual rustc invocation.
fn target_identity(target: &cargo_metadata::Target) -> String {
    let kinds = target
        .kind
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>()
        .join(",");
    format!("{kinds}:{}", target.name)
}

/// Extracts the unused crate's code identifier from an
/// `unused_crate_dependencies` diagnostic's short message, e.g. "extern
/// crate `depcrate` is unused in crate `fixture`" → `Some("depcrate")`. The
/// message text is rustc's own and not otherwise structured in the JSON
/// diagnostic, so this parses the one stable landmark: the first
/// backtick-quoted name.
fn extract_unused_crate_name(message: &str) -> Option<String> {
    if !message.contains("is unused in crate") {
        return None;
    }
    message.split('`').nth(1).map(str::to_string)
}

/// Runs `cargo check --workspace --all-targets --message-format=json` with
/// `-W unused_crate_dependencies` added to `RUSTFLAGS` (preserving any
/// `RUSTFLAGS` already set in the environment) and parses the resulting
/// message stream via `cargo_metadata::Message::parse_stream`. A spawn
/// failure or a non-zero exit status (e.g. the workspace doesn't currently
/// compile) is returned as a [`DepsError::RustcCheck`] rather than treated
/// as a finding source — see module docs "Importing rustc's
/// `unused_crate_dependencies` lint".
fn run_cargo_check_with_unused_crate_dependencies_lint(
    manifest_path: &Path,
) -> Result<Vec<cargo_metadata::Message>, DepsError> {
    let mut rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
    if !rustflags.is_empty() {
        rustflags.push(' ');
    }
    rustflags.push_str("-W unused_crate_dependencies");

    let output = std::process::Command::new("cargo")
        .arg("check")
        .arg("--workspace")
        .arg("--all-targets")
        .arg("--message-format=json")
        .arg("--manifest-path")
        .arg(manifest_path)
        .env("RUSTFLAGS", rustflags)
        .output()
        .map_err(|err| DepsError::RustcCheck(format!("failed to run `cargo check`: {err}")))?;

    if !output.status.success() {
        return Err(DepsError::RustcCheck(format!(
            "`cargo check --workspace --all-targets` exited with {}: {}",
            output.status,
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }

    Ok(
        cargo_metadata::Message::parse_stream(output.stdout.as_slice())
            .filter_map(Result::ok)
            .collect(),
    )
}

/// Renders an `unused-dependency` finding — rustc's own
/// `unused_crate_dependencies` lint result, narrowed to the packages this
/// workspace actually owns and to the multi-target intersection described in
/// the module docs. Its evidence class is `bounded_semantic` (todo.md
/// §17.3): the claim is scoped to "no use found across the targets this run
/// checked", not an absolute "unused". Same `location` convention as
/// [`misplaced_finding`].
fn unused_dependency_finding(
    krate: &CrateInfo,
    dep: &crate::ingest::DeclaredDependency,
    targets_checked: &[&String],
) -> Finding {
    Finding::new(
        format!("{UNUSED_DEPENDENCY_RULE}:{}:{}", krate.name, dep.name),
        UNUSED_DEPENDENCY_RULE,
        Severity::Warn,
        dep_location(krate, dep.name.clone()),
        EvidenceClass::BoundedSemantic,
        Origin::Code,
        Some(serde_json::json!({
            "source": "rustc:unused_crate_dependencies",
            "targets_checked": targets_checked,
            "package": krate.name,
            "reason": "no use found by rustc's unused_crate_dependencies lint \
                across all targets of this package",
        })),
    )
}

/// Distinct next-level path segments referenced under `target` (a
/// dependency's `code_identifier`) across every source file in `krate`,
/// regardless of usage domain — `heavy-dependency` cares about total usage
/// footprint, not where it is used. `use dep::{Foo, bar::Baz}` records `Foo`
/// and `bar`; `dep::foo::bar()` records `foo`. An approximation of "how many
/// distinct items of this dependency does the crate use", not exact item
/// resolution. Files that fail to read or parse are silently skipped: this is
/// advisory (`heuristic`) evidence, not a completeness claim like
/// `unused-dev-dependency`'s.
fn collect_used_items(krate: &CrateInfo, target: &str) -> HashSet<String> {
    let mut items = HashSet::new();
    for file in &krate.source_files {
        let Ok(source) = std::fs::read_to_string(&file.path) else {
            continue;
        };
        let Ok(ast) = syn::parse_file(&source) else {
            continue;
        };
        let mut collector = DepItemCollector {
            target,
            items: HashSet::new(),
        };
        collector.visit_file(&ast);
        items.extend(collector.items);
    }
    items
}

struct DepItemCollector<'a> {
    target: &'a str,
    items: HashSet<String>,
}

impl DepItemCollector<'_> {
    /// Mirrors [`PathIdentCollector::walk_use_tree`]'s hand-rolled walk (`use`
    /// trees have no `syn::Path` node), but one level deeper: `matched` tracks
    /// whether the segment just consumed was `target`, so the *next* segment
    /// is the item to record.
    fn walk_use_tree(&mut self, tree: &UseTree, matched: bool) {
        match tree {
            UseTree::Path(use_path) => {
                let ident = use_path.ident.to_string();
                if matched {
                    self.items.insert(ident);
                    self.walk_use_tree(&use_path.tree, false);
                } else {
                    self.walk_use_tree(&use_path.tree, ident == self.target);
                }
            }
            UseTree::Name(use_name) => {
                if matched {
                    self.items.insert(use_name.ident.to_string());
                }
            }
            UseTree::Rename(use_rename) => {
                if matched {
                    self.items.insert(use_rename.ident.to_string());
                }
            }
            UseTree::Glob(_) => {}
            UseTree::Group(group) => {
                for item in &group.items {
                    self.walk_use_tree(item, matched);
                }
            }
        }
    }
}

impl<'ast> Visit<'ast> for DepItemCollector<'_> {
    fn visit_item_use(&mut self, node: &'ast ItemUse) {
        self.walk_use_tree(&node.tree, false);
    }

    fn visit_path(&mut self, node: &'ast syn::Path) {
        if node.segments.len() >= 2 && node.segments[0].ident == self.target {
            self.items.insert(node.segments[1].ident.to_string());
        }
        visit::visit_path(self, node);
    }
}

/// Builds the `code_identifier -> domains observed` map for one crate, by
/// classifying each source file's domain and parsing it for referenced path
/// identifiers.
fn collect_crate_usage(
    krate: &CrateInfo,
) -> (
    HashMap<String, HashSet<UsageDomain>>,
    HashSet<UsageDomain>,
    Vec<DepsError>,
) {
    let mut usage: HashMap<String, HashSet<UsageDomain>> = HashMap::new();
    let mut failed_domains = HashSet::new();
    let mut errors = Vec::new();

    for file in &krate.source_files {
        let relative = file
            .path
            .strip_prefix(&krate.root)
            .unwrap_or(file.path.as_path());
        let domain = classify_domain(relative);

        match collect_identifiers(&file.path) {
            Ok((idents, cfg_test_idents)) => {
                for ident in idents {
                    usage.entry(ident).or_default().insert(domain);
                }
                // A `#[cfg(test)]` module in an otherwise `Normal`-domain
                // file (e.g. `mod tests` at the bottom of `src/lib.rs`) is
                // Dev-domain usage in spirit, even though the file it lives
                // in isn't — see `unused-dev-dependency` (todo.md §B). This
                // is additive: identifiers found there already counted
                // towards the file's own domain above (whole-file
                // classification is unchanged); this just also credits
                // `Dev`.
                for ident in cfg_test_idents {
                    usage.entry(ident).or_default().insert(UsageDomain::Dev);
                }
            }
            Err(err) => {
                failed_domains.insert(domain);
                errors.push(err);
            }
        }
    }

    (usage, failed_domains, errors)
}

/// Parses `path` and collects two identifier sets from a single parse: the
/// first-segment identifier of every referenced path — `use` trees,
/// expression paths, type paths, and macro-invocation paths — that isn't
/// `self`/`super`/`crate`/`Self` (each such identifier is a candidate
/// reference to an external crate's `code_identifier`); and the same, scoped
/// to identifiers referenced only inside `#[cfg(test)]`-attributed modules
/// (see [`CfgTestIdentCollector`]).
fn collect_identifiers(path: &Path) -> Result<(HashSet<String>, HashSet<String>), DepsError> {
    let (_, ast) = read_and_parse_source(
        path,
        |err| DepsError::Io(path.to_path_buf(), err),
        |err| DepsError::Parse(path.to_path_buf(), err),
    )?;

    let mut collector = PathIdentCollector::default();
    collector.visit_file(&ast);

    let mut cfg_test_collector = CfgTestIdentCollector::default();
    cfg_test_collector.visit_file(&ast);

    Ok((collector.idents, cfg_test_collector.idents))
}

/// Whether `attrs` contains a `#[cfg(...)]` attribute whose predicate
/// mentions `test` as a whole word (`#[cfg(test)]`, `#[cfg(any(test, ...))]`,
/// `#[cfg(all(test, ...))]`) — a crude but conservative parse of the
/// attribute's raw tokens, not a full `cfg` predicate evaluator.
pub(crate) fn attrs_have_cfg_test(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("cfg") {
            return false;
        }
        let syn::Meta::List(list) = &attr.meta else {
            return false;
        };
        list.tokens
            .to_string()
            .split(|c: char| !c.is_alphanumeric() && c != '_')
            .any(|word| word == "test")
    })
}

/// Collects identifiers referenced inside `#[cfg(test)]`-attributed modules
/// (see [`attrs_have_cfg_test`]) — the common `#[cfg(test)] mod tests { ... }`
/// pattern in an otherwise non-test source file. Deliberately narrower than
/// "any cfg(test)-gated item": individual `#[cfg(test)] fn`s outside such a
/// module aren't recognized, matching todo.md §B's scope ("`#[cfg(test)]`-
/// Module in normalen src-Dateien zählen als Dev-Nutzung").
#[derive(Default)]
struct CfgTestIdentCollector {
    idents: HashSet<String>,
}

impl<'ast> Visit<'ast> for CfgTestIdentCollector {
    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
        if attrs_have_cfg_test(&node.attrs) {
            let mut inner = PathIdentCollector::default();
            inner.visit_item_mod(node);
            self.idents.extend(inner.idents);
        } else {
            visit::visit_item_mod(self, node);
        }
    }
}

#[derive(Default)]
struct PathIdentCollector {
    idents: HashSet<String>,
}

impl PathIdentCollector {
    fn record(&mut self, ident: &str) {
        if !matches!(ident, "self" | "super" | "crate" | "Self") {
            self.idents.insert(ident.to_string());
        }
    }

    /// `UseTree` doesn't contain `syn::Path` nodes, so `visit_path` never
    /// sees `use` items — walk the tree by hand instead, recording only the
    /// first segment of each `Path`/`Name`/`Rename` chain (the rest of the
    /// tree doesn't add new *external* identifiers to record).
    fn walk_use_tree(&mut self, tree: &UseTree) {
        match tree {
            UseTree::Path(use_path) => self.record(&use_path.ident.to_string()),
            UseTree::Name(use_name) => self.record(&use_name.ident.to_string()),
            UseTree::Rename(use_rename) => self.record(&use_rename.ident.to_string()),
            UseTree::Glob(_) => {}
            UseTree::Group(group) => {
                for item in &group.items {
                    self.walk_use_tree(item);
                }
            }
        }
    }
}

impl<'ast> Visit<'ast> for PathIdentCollector {
    fn visit_item_use(&mut self, node: &'ast ItemUse) {
        self.walk_use_tree(&node.tree);
    }

    fn visit_path(&mut self, node: &'ast syn::Path) {
        if let Some(first) = node.segments.first() {
            self.record(&first.ident.to_string());
        }
        visit::visit_path(self, node);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::TempDir;

    /// Writes a two-crate fixture: `main` depends on a path dependency named
    /// `dep_crate_name` (or a renamed alias, if `rename` is given), declared
    /// in `dependency_section` (e.g. `"[dependencies]"` or
    /// `"[build-dependencies]"`). Path dependencies keep these tests fully
    /// offline — no registry/network access needed (verified against a real
    /// `cargo metadata --no-deps` run). The vendored dependency declares a
    /// `repository` field so these otherwise-unrelated fixtures don't also
    /// pick up a `dep-without-repo` finding from the full-resolve pass that
    /// `analyze_workspace` always runs alongside `heavy-dependency`.
    fn write_fixture(
        dir: &TempDir,
        dependency_section: &str,
        dep_crate_name: &str,
        rename: Option<&str>,
        features: &[&str],
        main_files: &[(&str, &str)],
    ) -> PathBuf {
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();

        let dep_line = match rename {
            Some(alias) => format!(
                "{alias} = {{ package = \"{dep_crate_name}\", path = \"../dep_crate\"{} }}",
                features_toml(features)
            ),
            None => format!(
                "{dep_crate_name} = {{ path = \"../dep_crate\"{} }}",
                features_toml(features)
            ),
        };
        std::fs::write(
            dir.join("main/Cargo.toml"),
            format!(
                r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

{dependency_section}
{dep_line}
"#
            ),
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();
        for (relative, content) in main_files {
            let file_path = dir.join("main").join(relative);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(file_path, content).unwrap();
        }

        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            format!(
                r#"
[package]
name = "{dep_crate_name}"
version = "0.1.0"
edition = "2021"
repository = "https://example.com/{dep_crate_name}"
"#
            ),
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        dir.join("main/Cargo.toml")
    }

    fn features_toml(features: &[&str]) -> String {
        if features.is_empty() {
            String::new()
        } else {
            let joined = features
                .iter()
                .map(|f| format!("\"{f}\""))
                .collect::<Vec<_>>()
                .join(", ");
            format!(", features = [{joined}]")
        }
    }

    #[test]
    fn a_normal_dependency_used_only_from_tests_is_flagged_as_dev() {
        let dir = TempDir::new("deps-dev-only");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[("tests/it.rs", "fn t() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].location.item_path, "depcrate");
        assert!(report.feature_only_candidates.is_empty());
    }

    #[test]
    fn a_normal_dependency_used_only_inside_a_platform_cfg_gate_is_not_misclassified_as_dev_only() {
        // The dependency is referenced only inside a
        // `#[cfg(target_os = "windows")]`-gated module in src/lib.rs -- code
        // that will never actually compile on most developer/CI machines.
        // Usage-domain classification is purely path-based (see module
        // docs "Usage-domain classification"), and `collect_identifiers`'s
        // syn-based scan doesn't evaluate `cfg` predicates at all -- it just
        // records the path reference inside a file that isn't under
        // tests/examples/benches. So this still counts as `Normal`-domain
        // usage: the todo.md §17.5 hypothesis (fast-tier usage detection
        // mis-attributing cfg-gated usage as "only from tests/examples")
        // does not hold here. Documents the actual (correct, non-buggy)
        // behavior.
        let dir = TempDir::new("deps-platform-cfg-gate");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[(
                "src/lib.rs",
                "#[cfg(target_os = \"windows\")]\nmod windows {\n    pub fn go() { depcrate::noop(); }\n}\n",
            )],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == MISPLACED_DEPENDENCY_KIND_RULE),
            "a cfg-gated normal-domain usage must not be misclassified as dev-only: {:?}",
            report.findings
        );
    }

    #[test]
    fn a_normal_dependency_used_from_src_and_tests_is_not_flagged() {
        let dir = TempDir::new("deps-src-and-tests");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[
                ("src/lib.rs", "pub fn hello() { depcrate::noop(); }\n"),
                ("tests/it.rs", "fn t() { depcrate::noop(); }\n"),
            ],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(report.findings.is_empty());
    }

    #[test]
    fn a_build_dependency_never_referenced_in_build_rs_is_flagged_as_unused() {
        let dir = TempDir::new("deps-build-unused");
        let manifest = write_fixture(
            &dir,
            "[build-dependencies]",
            "depcrate",
            None,
            &[],
            &[("build.rs", "fn main() {}\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].location.item_path, "depcrate");
    }

    #[test]
    fn a_build_dependency_referenced_in_build_rs_is_not_flagged() {
        let dir = TempDir::new("deps-build-used");
        let manifest = write_fixture(
            &dir,
            "[build-dependencies]",
            "depcrate",
            None,
            &[],
            &[("build.rs", "fn main() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(report.findings.is_empty());
    }

    #[test]
    fn a_parse_error_in_build_rs_does_not_claim_the_dependency_is_unused() {
        let dir = TempDir::new("deps-build-parse-error");
        let manifest = write_fixture(
            &dir,
            "[build-dependencies]",
            "depcrate",
            None,
            &[],
            &[("build.rs", "fn main( { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert_eq!(report.errors.len(), 1);
        assert!(report.findings.is_empty());
    }

    #[test]
    fn a_dependency_with_zero_usage_and_features_is_flagged_per_feature() {
        let dir = TempDir::new("deps-feature-only");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &["some-feature", "other-feature"],
            &[],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert_eq!(report.feature_only_candidates, vec!["depcrate".to_string()]);

        let flagged: Vec<&Finding> = report
            .findings
            .iter()
            .filter(|f| f.rule == UNUSED_FEATURE_FLAG_RULE)
            .collect();
        assert_eq!(flagged.len(), 2);
        for finding in &flagged {
            assert_eq!(finding.severity, Severity::Warn);
            assert_eq!(finding.evidence_class, EvidenceClass::DerivedFact);
            assert_eq!(finding.location.item_path, "depcrate");
        }
        let features: Vec<&str> = flagged
            .iter()
            .map(|f| f.evidence.as_ref().unwrap()["feature"].as_str().unwrap())
            .collect();
        assert!(features.contains(&"some-feature"));
        assert!(features.contains(&"other-feature"));
    }

    #[test]
    fn a_dependency_used_anywhere_has_no_unused_feature_flag_finding_despite_many_features() {
        let dir = TempDir::new("deps-feature-used");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &["some-feature", "other-feature"],
            &[("src/lib.rs", "pub fn hello() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_FEATURE_FLAG_RULE)
        );
        assert!(report.feature_only_candidates.is_empty());
    }

    /// Writes a fixture like [`write_fixture`], but with a caller-supplied
    /// dependency line — needed for `default-features-unused` tests, which
    /// must control whether `default-features = true` is present in the
    /// manifest text verbatim (something [`write_fixture`]'s `features`-only
    /// knobs can't express).
    fn write_fixture_with_dep_line(
        dir: &TempDir,
        dep_line: &str,
        main_files: &[(&str, &str)],
    ) -> PathBuf {
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();

        std::fs::write(
            dir.join("main/Cargo.toml"),
            format!(
                r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
{dep_line}
"#
            ),
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();
        for (relative, content) in main_files {
            let file_path = dir.join("main").join(relative);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(file_path, content).unwrap();
        }

        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            r#"
[package]
name = "depcrate"
version = "0.1.0"
edition = "2021"
repository = "https://example.com/depcrate"
"#,
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        dir.join("main/Cargo.toml")
    }

    #[test]
    fn explicit_default_features_true_and_zero_usage_is_flagged() {
        let dir = TempDir::new("deps-default-features-unused");
        let manifest = write_fixture_with_dep_line(
            &dir,
            r#"depcrate = { path = "../dep_crate", default-features = true }"#,
            &[],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        let finding = report
            .findings
            .iter()
            .find(|f| f.rule == DEFAULT_FEATURES_UNUSED_RULE)
            .expect("expected a default-features-unused finding");
        assert_eq!(finding.severity, Severity::Warn);
        assert_eq!(finding.evidence_class, EvidenceClass::DerivedFact);
        assert_eq!(finding.location.item_path, "depcrate");
    }

    #[test]
    fn explicit_default_features_true_but_used_is_not_flagged() {
        let dir = TempDir::new("deps-default-features-used");
        let manifest = write_fixture_with_dep_line(
            &dir,
            r#"depcrate = { path = "../dep_crate", default-features = true }"#,
            &[("src/lib.rs", "pub fn hello() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == DEFAULT_FEATURES_UNUSED_RULE)
        );
    }

    #[test]
    fn no_explicit_default_features_and_zero_usage_is_not_flagged() {
        let dir = TempDir::new("deps-default-features-implicit");
        let manifest =
            write_fixture_with_dep_line(&dir, r#"depcrate = { path = "../dep_crate" }"#, &[]);

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == DEFAULT_FEATURES_UNUSED_RULE)
        );
    }

    #[test]
    fn a_renamed_dependency_is_matched_by_its_local_alias() {
        let dir = TempDir::new("deps-renamed");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "real-name",
            Some("some_dep"),
            &[],
            &[("tests/it.rs", "fn t() { some_dep::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        // Matched via `some_dep::`, not `real_name::` — proves code_identifier
        // (the rename) is what's used for matching, not the registry name.
        assert_eq!(report.findings.len(), 1);
        assert_eq!(report.findings[0].location.item_path, "real-name");
    }

    #[test]
    fn why_finds_a_known_usage_location_and_the_direct_graph_path() {
        let dir = TempDir::new("deps-why-usage");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[("src/lib.rs", "pub fn hello() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = why(&workspace, "depcrate");

        assert!(report.found);
        assert!(report.errors.is_empty(), "{:?}", report.errors);
        assert_eq!(report.declared_by.len(), 1);
        let declaration = &report.declared_by[0];
        assert_eq!(declaration.crate_name, "fixture");
        assert_eq!(declaration.kind, DependencyKind::Normal);
        assert!(declaration.features.is_empty());
        assert_eq!(declaration.usages.len(), 1);
        let usage = &declaration.usages[0];
        assert!(usage.file.ends_with("src/lib.rs"), "{:?}", usage.file);
        assert_eq!(usage.line.get(), 1);
        assert_eq!(usage.domain, UsageDomain::Normal);

        assert_eq!(
            report.graph_paths.get("fixture"),
            Some(&vec!["depcrate".to_string()])
        );
    }

    #[test]
    fn why_reports_not_found_for_an_unknown_dependency() {
        let dir = TempDir::new("deps-why-not-found");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[("src/lib.rs", "pub fn hello() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = why(&workspace, "does-not-exist");

        assert!(!report.found);
        assert!(report.declared_by.is_empty());
    }

    #[test]
    fn finding_shape_matches_the_documented_contract() {
        let dir = TempDir::new("deps-finding-shape");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[("tests/it.rs", "fn t() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert_eq!(report.findings.len(), 1);
        let finding = &report.findings[0];
        assert_eq!(finding.rule, MISPLACED_DEPENDENCY_KIND_RULE);
        assert_eq!(finding.severity, Severity::Warn);
        assert_eq!(finding.origin, Origin::Code);
        assert_eq!(finding.evidence_class, EvidenceClass::Heuristic);
        assert_eq!(finding.location.file, workspace.crates[0].manifest_path);
    }

    #[test]
    fn classify_domain_recognizes_dev_directories_and_build_rs() {
        assert_eq!(classify_domain(Path::new("build.rs")), UsageDomain::Build);
        assert_eq!(classify_domain(Path::new("tests/it.rs")), UsageDomain::Dev);
        assert_eq!(
            classify_domain(Path::new("examples/demo.rs")),
            UsageDomain::Dev
        );
        assert_eq!(
            classify_domain(Path::new("benches/bench.rs")),
            UsageDomain::Dev
        );
        assert_eq!(
            classify_domain(Path::new("src/lib.rs")),
            UsageDomain::Normal
        );
    }

    #[test]
    fn deps_error_source_preserves_the_underlying_error() {
        let err = DepsError::Io(PathBuf::from("src/lib.rs"), std::io::Error::other("boom"));
        let source = std::error::Error::source(&err).expect("Io must carry a source");
        assert!(source.downcast_ref::<std::io::Error>().is_some());
        assert_eq!(err.to_string(), "src/lib.rs: failed to read file: boom");
    }

    #[test]
    fn a_dev_dependency_used_only_from_tests_is_not_flagged_as_unused() {
        let dir = TempDir::new("deps-dev-used-in-tests");
        let manifest = write_fixture(
            &dir,
            "[dev-dependencies]",
            "depcrate",
            None,
            &[],
            &[("tests/it.rs", "fn t() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_DEV_DEPENDENCY_RULE)
        );
    }

    #[test]
    fn a_dev_dependency_never_used_is_flagged_with_a_hedged_message() {
        let dir = TempDir::new("deps-dev-unused");
        let manifest = write_fixture(&dir, "[dev-dependencies]", "depcrate", None, &[], &[]);

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        let finding = report
            .findings
            .iter()
            .find(|f| f.rule == UNUSED_DEV_DEPENDENCY_RULE)
            .expect("expected an unused-dev-dependency finding");
        assert_eq!(finding.severity, Severity::Warn);
        assert_eq!(finding.evidence_class, EvidenceClass::BoundedSemantic);
        assert_eq!(finding.location.item_path, "depcrate");
        let reason = finding.evidence.as_ref().unwrap()["reason"]
            .as_str()
            .unwrap();
        assert!(reason.contains("no use found in the examined view"));
        assert!(!reason.contains("is unused"));
    }

    #[test]
    fn a_dev_dependency_used_only_in_a_cfg_test_module_in_src_is_not_flagged() {
        let dir = TempDir::new("deps-dev-cfg-test");
        let manifest = write_fixture(
            &dir,
            "[dev-dependencies]",
            "depcrate",
            None,
            &[],
            &[(
                "src/lib.rs",
                "pub fn hello() {}\n\n#[cfg(test)]\nmod tests {\n    #[test]\n    fn t() { depcrate::noop(); }\n}\n",
            )],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_DEV_DEPENDENCY_RULE)
        );
    }

    #[test]
    fn a_dev_dependency_also_declared_as_a_normal_dependency_is_not_flagged() {
        let dir = TempDir::new("deps-dev-also-normal");
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();
        std::fs::write(
            dir.join("main/Cargo.toml"),
            r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
depcrate = { path = "../dep_crate" }

[dev-dependencies]
depcrate = { path = "../dep_crate" }
"#,
        )
        .unwrap();
        std::fs::write(
            dir.join("main/src/lib.rs"),
            "pub fn hello() { depcrate::noop(); }\n",
        )
        .unwrap();
        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            r#"
[package]
name = "depcrate"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        let workspace = crate::ingest::load(Some(&dir.join("main/Cargo.toml"))).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_DEV_DEPENDENCY_RULE)
        );
    }

    #[test]
    fn collect_used_items_records_next_level_path_segments() {
        let dir = TempDir::new("deps-used-items");
        std::fs::create_dir_all(dir.join("src")).unwrap();
        let file_path = dir.join("src/lib.rs");
        std::fs::write(
            &file_path,
            "use depcrate::{Foo, bar::Baz};\nfn use_it() { depcrate::other::thing(); }\n",
        )
        .unwrap();

        let krate = CrateInfo {
            name: "fixture".to_string(),
            version: "0.1.0".to_string(),
            manifest_path: dir.join("Cargo.toml"),
            root: dir.to_path_buf(),
            source_files: vec![crate::ingest::SourceFile {
                path: file_path,
                kind: crate::ingest::SourceKind::Authored,
            }],
            entry_points: Vec::new(),
            dependencies: Vec::new(),
        };

        let mut items: Vec<String> = collect_used_items(&krate, "depcrate").into_iter().collect();
        items.sort();
        assert_eq!(items, vec!["Foo", "bar", "other"]);
    }

    #[test]
    fn is_heavy_dependency_requires_both_thresholds_to_be_crossed() {
        assert!(!is_heavy_dependency(
            HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD,
            0
        ));
        assert!(!is_heavy_dependency(
            HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD + 1,
            HEAVY_DEPENDENCY_USED_ITEMS_THRESHOLD
        ));
        assert!(is_heavy_dependency(
            HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD + 1,
            HEAVY_DEPENDENCY_USED_ITEMS_THRESHOLD - 1
        ));
    }

    #[test]
    fn heavy_dependency_finding_is_advisory_only() {
        let krate = CrateInfo {
            name: "fixture".to_string(),
            version: "0.1.0".to_string(),
            manifest_path: PathBuf::from("fixture/Cargo.toml"),
            root: PathBuf::from("fixture"),
            source_files: Vec::new(),
            entry_points: Vec::new(),
            dependencies: Vec::new(),
        };
        let dep = crate::ingest::DeclaredDependency {
            name: "heavy_crate".to_string(),
            kind: DependencyKind::Normal,
            code_identifier: "heavy_crate".to_string(),
            target: None,
            features: Vec::new(),
            version_req: "*".to_string(),
        };
        let used_items: HashSet<String> = HashSet::new();
        let finding = heavy_dependency_finding(&krate, &dep, 42, &used_items);

        assert_eq!(finding.rule, HEAVY_DEPENDENCY_RULE);
        assert_eq!(finding.severity, Severity::Info);
        assert_eq!(finding.evidence_class, EvidenceClass::Heuristic);
        assert!(!finding.is_gating());
        assert_eq!(finding.evidence.unwrap()["transitive_deps"], 42);
    }

    #[test]
    fn repository_is_missing_treats_absent_and_blank_as_missing() {
        assert!(repository_is_missing(&None));
        assert!(repository_is_missing(&Some(String::new())));
        assert!(repository_is_missing(&Some("   ".to_string())));
        assert!(!repository_is_missing(&Some(
            "https://example.com/repo".to_string()
        )));
    }

    #[test]
    fn dep_without_repo_finding_is_gating_info() {
        let krate = CrateInfo {
            name: "fixture".to_string(),
            version: "0.1.0".to_string(),
            manifest_path: PathBuf::from("fixture/Cargo.toml"),
            root: PathBuf::from("fixture"),
            source_files: Vec::new(),
            entry_points: Vec::new(),
            dependencies: Vec::new(),
        };
        let dep = crate::ingest::DeclaredDependency {
            name: "norepo_crate".to_string(),
            kind: DependencyKind::Normal,
            code_identifier: "norepo_crate".to_string(),
            target: None,
            features: Vec::new(),
            version_req: "*".to_string(),
        };
        let finding = dep_without_repo_finding(&krate, &dep);

        assert_eq!(finding.rule, DEP_WITHOUT_REPO_RULE);
        assert_eq!(finding.severity, Severity::Info);
        assert_eq!(finding.evidence_class, EvidenceClass::DerivedFact);
        assert!(finding.is_gating());
        assert_eq!(finding.location.item_path, "norepo_crate");
    }

    /// End-to-end: a real (non `--no-deps`) `cargo metadata` resolve over a
    /// vendored path dependency whose manifest has no `repository` field —
    /// proves [`resolve_full_metadata`]/`analyze_workspace` wire the field
    /// through, not just the pure `dep_without_repo_finding` builder above.
    #[test]
    fn a_dependency_without_a_repository_field_is_flagged_end_to_end() {
        let dir = TempDir::new("deps-dep-without-repo");
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();
        std::fs::write(
            dir.join("main/Cargo.toml"),
            r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
norepo = { path = "../dep_crate" }
"#,
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            r#"
[package]
name = "norepo"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        let workspace = crate::ingest::load(Some(&dir.join("main/Cargo.toml"))).unwrap();
        let report = analyze_workspace(&workspace);

        let finding = report
            .findings
            .iter()
            .find(|f| f.rule == DEP_WITHOUT_REPO_RULE)
            .expect("expected a dep-without-repo finding");
        assert_eq!(finding.severity, Severity::Info);
        assert_eq!(finding.evidence_class, EvidenceClass::DerivedFact);
        assert_eq!(finding.location.item_path, "norepo");
    }

    #[test]
    fn a_dependency_with_a_repository_field_is_not_flagged_end_to_end() {
        let dir = TempDir::new("deps-dep-with-repo");
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();
        std::fs::write(
            dir.join("main/Cargo.toml"),
            r#"
[package]
name = "fixture"
version = "0.1.0"
edition = "2021"

[dependencies]
hasrepo = { path = "../dep_crate" }
"#,
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            r#"
[package]
name = "hasrepo"
version = "0.1.0"
edition = "2021"
repository = "https://example.com/hasrepo"
"#,
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        let workspace = crate::ingest::load(Some(&dir.join("main/Cargo.toml"))).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == DEP_WITHOUT_REPO_RULE)
        );
    }

    #[test]
    fn extract_unused_crate_name_parses_the_first_backtick_quoted_name() {
        assert_eq!(
            extract_unused_crate_name("extern crate `depcrate` is unused in crate `fixture`"),
            Some("depcrate".to_string())
        );
        assert_eq!(extract_unused_crate_name("some unrelated warning"), None);
    }

    #[test]
    fn target_identity_joins_kind_and_name() {
        let json = serde_json::json!({
            "name": "it",
            "kind": ["test"],
            "crate_types": ["bin"],
            "required-features": [],
            "src_path": "tests/it.rs",
            "edition": "2021",
            "doc": false,
            "doctest": false,
            "test": true,
        });
        let target: cargo_metadata::Target = serde_json::from_value(json).unwrap();
        assert_eq!(target_identity(&target), "test:it");
    }

    // The following three tests drive a real `cargo check --workspace
    // --all-targets` subprocess (see `run_cargo_check_with_unused_crate_dependencies_lint`)
    // against a path-dependency-only fixture — offline, but genuinely slow
    // compared to every other test in this file (a fraction of a second per
    // fixture, verified against a real run rather than mocked, see todo.md
    // §B). They are the proof that `analyze_rustc_unused_dependencies`'s
    // whole pipeline — spawn, JSON parse, multi-target intersection — works
    // end to end, not just its pure helpers above.

    #[test]
    fn rustc_lint_import_flags_a_normal_dependency_never_referenced_anywhere() {
        let dir = TempDir::new("deps-rustc-lint-unused");
        let manifest = write_fixture(&dir, "[dependencies]", "depcrate", None, &[], &[]);

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_rustc_unused_dependencies(&workspace);

        assert!(
            report.errors.is_empty(),
            "unexpected errors: {:?}",
            report.errors
        );
        let finding = report
            .findings
            .iter()
            .find(|f| f.rule == UNUSED_DEPENDENCY_RULE)
            .expect("expected an unused-dependency finding");
        assert_eq!(finding.severity, Severity::Warn);
        assert_eq!(finding.evidence_class, EvidenceClass::BoundedSemantic);
        assert_eq!(finding.location.item_path, "depcrate");
        let evidence = finding.evidence.as_ref().unwrap();
        assert_eq!(evidence["source"], "rustc:unused_crate_dependencies");
        assert_eq!(evidence["package"], "fixture");
        assert!(
            evidence["reason"]
                .as_str()
                .unwrap()
                .contains("unused_crate_dependencies")
        );
    }

    #[test]
    fn rustc_lint_import_does_not_flag_a_dependency_used_in_every_target() {
        let dir = TempDir::new("deps-rustc-lint-used-everywhere");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[
                ("src/lib.rs", "pub fn hello() { depcrate::noop(); }\n"),
                ("tests/it.rs", "fn t() { depcrate::noop(); }\n"),
            ],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_rustc_unused_dependencies(&workspace);

        assert!(
            report.errors.is_empty(),
            "unexpected errors: {:?}",
            report.errors
        );
        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_DEPENDENCY_RULE)
        );
    }

    #[test]
    fn rustc_lint_import_does_not_flag_a_dependency_used_by_only_one_target() {
        // `depcrate` is referenced only from the integration test target,
        // never from `lib` — rustc's raw per-target lint would report it
        // unused for the `lib` compile alone, the documented multi-target
        // false positive this detector's intersection logic is meant to
        // avoid (see module docs "Importing rustc's
        // `unused_crate_dependencies` lint").
        let dir = TempDir::new("deps-rustc-lint-single-target");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[("tests/it.rs", "fn t() { depcrate::noop(); }\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_rustc_unused_dependencies(&workspace);

        assert!(
            report.errors.is_empty(),
            "unexpected errors: {:?}",
            report.errors
        );
        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_DEPENDENCY_RULE)
        );
    }

    #[test]
    fn a_genuine_compile_error_surfaces_as_a_report_error_not_as_zero_findings() {
        // If `cargo check --workspace --all-targets` fails because the
        // workspace doesn't compile at all (a real syntax error here,
        // unrelated to the lint), that must not be silently read as "the
        // lint ran and found zero unused dependencies" -- those two outcomes
        // look identical as an empty `findings` vec, but mean very different
        // things. It has to surface as a `DepsError::RustcCheck` instead, so
        // the caller can tell "checked, nothing unused" apart from "could not
        // check at all".
        let dir = TempDir::new("deps-rustc-lint-compile-error");
        let manifest = write_fixture(
            &dir,
            "[dependencies]",
            "depcrate",
            None,
            &[],
            &[("src/lib.rs", "this is not valid rust syntax {{{\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_rustc_unused_dependencies(&workspace);

        assert!(
            report.findings.is_empty(),
            "unexpected findings from an unbuildable workspace: {:?}",
            report.findings
        );
        assert_eq!(report.errors.len(), 1);
        assert!(matches!(report.errors[0], DepsError::RustcCheck(_)));
    }

    // -- unused-feature --

    /// A single, dependency-free crate — `unused-feature` is entirely about
    /// a crate's own `[features]` table, so unlike [`write_fixture`] above,
    /// no path dependency is needed to exercise it.
    fn write_crate_with_features(
        dir: &TempDir,
        features_block: &str,
        files: &[(&str, &str)],
    ) -> PathBuf {
        std::fs::create_dir_all(dir.join("src")).unwrap();
        std::fs::write(
            dir.join("Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n{features_block}\n"
            ),
        )
        .unwrap();
        std::fs::write(dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();
        for (relative, content) in files {
            let file_path = dir.join(relative);
            if let Some(parent) = file_path.parent() {
                std::fs::create_dir_all(parent).unwrap();
            }
            std::fs::write(file_path, content).unwrap();
        }
        dir.join("Cargo.toml")
    }

    #[test]
    fn unused_feature_fires_for_a_declared_feature_with_no_cfg_reference() {
        let dir = TempDir::new("deps-unused-feature-fires");
        let manifest = write_crate_with_features(
            &dir,
            "[features]\nfancy = []\n",
            &[("src/lib.rs", "pub fn hello() {}\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == UNUSED_FEATURE_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].location.item_path, "fancy");
        assert_eq!(hits[0].severity, Severity::Warn);
        assert_eq!(hits[0].evidence_class, EvidenceClass::DerivedFact);
        assert!(hits[0].is_gating());
    }

    #[test]
    fn unused_feature_does_not_fire_when_a_cfg_attribute_references_it() {
        let dir = TempDir::new("deps-unused-feature-cfg-attr");
        let manifest = write_crate_with_features(
            &dir,
            "[features]\nfancy = []\n",
            &[(
                "src/lib.rs",
                "#[cfg(feature = \"fancy\")]\npub fn fancy_hello() {}\n",
            )],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_FEATURE_RULE),
            "unexpected findings: {:?}",
            report.findings
        );
    }

    #[test]
    fn unused_feature_does_not_fire_when_a_cfg_macro_call_references_it() {
        let dir = TempDir::new("deps-unused-feature-cfg-macro");
        let manifest = write_crate_with_features(
            &dir,
            "[features]\nfancy = []\n",
            &[(
                "src/lib.rs",
                "pub fn hello() {\n    if cfg!(feature = \"fancy\") {}\n}\n",
            )],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_FEATURE_RULE)
        );
    }

    #[test]
    fn unused_feature_never_fires_for_default() {
        let dir = TempDir::new("deps-unused-feature-default");
        let manifest = write_crate_with_features(
            &dir,
            "[features]\ndefault = []\n",
            &[("src/lib.rs", "pub fn hello() {}\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_FEATURE_RULE)
        );
    }

    #[test]
    fn unused_feature_does_not_fire_for_an_umbrella_feature_with_implications() {
        let dir = TempDir::new("deps-unused-feature-umbrella");
        let manifest = write_crate_with_features(
            &dir,
            "[features]\nfancy = []\nfull = [\"fancy\"]\n",
            &[("src/lib.rs", "#[cfg(feature = \"fancy\")]\npub fn f() {}\n")],
        );

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        // "fancy" is referenced, and "full" is an umbrella (non-empty
        // implication list) — neither should fire.
        assert!(
            !report
                .findings
                .iter()
                .any(|f| f.rule == UNUSED_FEATURE_RULE)
        );
    }

    #[test]
    fn declared_features_without_implications_excludes_default_and_umbrella_features() {
        let manifest: toml::Value =
            toml::from_str("[features]\ndefault = []\nfancy = []\nfull = [\"fancy\"]\n").unwrap();

        let names = declared_features_without_implications(&manifest);

        assert_eq!(names, vec!["fancy".to_string()]);
    }

    #[test]
    fn declared_features_without_implications_is_empty_without_a_features_table() {
        let manifest: toml::Value =
            toml::from_str("[package]\nname = \"fixture\"\nversion = \"0.1.0\"\n").unwrap();

        assert!(declared_features_without_implications(&manifest).is_empty());
    }

    // -- registry example drift guards --
    //
    // Each test below reads the curated `example.before` for its rule
    // straight out of `rule_registry::RULE_REGISTRY` (never a second copy of
    // the literal) and rebuilds just enough of a fixture around it to prove
    // the snippet still triggers the rule -- see
    // `.claude/skills/curate-rule-example/SKILL.md`.

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn misplaced_dependency_kind_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(MISPLACED_DEPENDENCY_KIND_RULE)
            .expect("misplaced-dependency-kind has a registry entry")
            .example
            .expect("misplaced-dependency-kind has a curated example")
            .before;
        let manifest: toml::Value = toml::from_str(example).unwrap();
        let dep_name = manifest
            .get("dependencies")
            .and_then(toml::Value::as_table)
            .and_then(|table| table.keys().next())
            .expect("example declares a dependency")
            .clone();
        let code_identifier = dep_name.replace('-', "_");

        let dir = TempDir::new("deps-misplaced-dependency-kind-registry-example");
        let usage = format!("fn t() {{ {code_identifier}::noop(); }}\n");
        let manifest_path = write_fixture(
            &dir,
            "[dependencies]",
            &dep_name,
            None,
            &[],
            &[("tests/it.rs", usage.as_str())],
        );

        let workspace = crate::ingest::load(Some(&manifest_path)).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == MISPLACED_DEPENDENCY_KIND_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn unused_dev_dependency_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(UNUSED_DEV_DEPENDENCY_RULE)
            .expect("unused-dev-dependency has a registry entry")
            .example
            .expect("unused-dev-dependency has a curated example")
            .before;
        let manifest: toml::Value = toml::from_str(example).unwrap();
        let dep_name = manifest
            .get("dev-dependencies")
            .and_then(toml::Value::as_table)
            .and_then(|table| table.keys().next())
            .expect("example declares a dev-dependency")
            .clone();

        let dir = TempDir::new("deps-unused-dev-dependency-registry-example");
        let manifest_path = write_fixture(&dir, "[dev-dependencies]", &dep_name, None, &[], &[]);

        let workspace = crate::ingest::load(Some(&manifest_path)).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == UNUSED_DEV_DEPENDENCY_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags. `heavy-dependency`
    /// needs a real dependency with more than
    /// [`HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD`] transitive dependencies of
    /// its own, so this builds the curated dependency name as a small crate
    /// with that many local, no-op leaf path-dependencies -- fully offline.
    #[test]
    fn heavy_dependency_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(HEAVY_DEPENDENCY_RULE)
            .expect("heavy-dependency has a registry entry")
            .example
            .expect("heavy-dependency has a curated example")
            .before;
        let manifest: toml::Value = toml::from_str(example).unwrap();
        let dep_name = manifest
            .get("dependencies")
            .and_then(toml::Value::as_table)
            .and_then(|table| table.keys().next())
            .expect("example declares a dependency")
            .clone();

        let dir = TempDir::new("deps-heavy-dependency-registry-example");
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::write(
            dir.join("main/Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{dep_name} = {{ path = \"../{dep_name}\" }}\n"
            ),
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();

        let leaf_count = HEAVY_DEPENDENCY_TRANSITIVE_THRESHOLD + 1;
        let mut leaf_deps_toml = String::new();
        for i in 0..leaf_count {
            let leaf_name = format!("{dep_name}-leaf-{i}");
            std::fs::create_dir_all(dir.join(&leaf_name).join("src")).unwrap();
            std::fs::write(
                dir.join(&leaf_name).join("Cargo.toml"),
                format!(
                    "[package]\nname = \"{leaf_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"
                ),
            )
            .unwrap();
            std::fs::write(
                dir.join(&leaf_name).join("src/lib.rs"),
                "pub fn noop() {}\n",
            )
            .unwrap();
            leaf_deps_toml.push_str(&format!("{leaf_name} = {{ path = \"../{leaf_name}\" }}\n"));
        }
        std::fs::create_dir_all(dir.join(&dep_name).join("src")).unwrap();
        std::fs::write(
            dir.join(&dep_name).join("Cargo.toml"),
            format!(
                "[package]\nname = \"{dep_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{leaf_deps_toml}"
            ),
        )
        .unwrap();
        std::fs::write(dir.join(&dep_name).join("src/lib.rs"), "pub fn noop() {}\n").unwrap();

        let workspace = crate::ingest::load(Some(&dir.join("main/Cargo.toml"))).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == HEAVY_DEPENDENCY_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn unused_feature_flag_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(UNUSED_FEATURE_FLAG_RULE)
            .expect("unused-feature-flag has a registry entry")
            .example
            .expect("unused-feature-flag has a curated example")
            .before;
        let manifest: toml::Value = toml::from_str(example).unwrap();
        let deps_table = manifest
            .get("dependencies")
            .and_then(toml::Value::as_table)
            .expect("example declares a dependencies table");
        let (dep_name, dep_value) = deps_table
            .iter()
            .next()
            .expect("example declares a dependency");
        let feature = dep_value
            .get("features")
            .and_then(toml::Value::as_array)
            .and_then(|features| features.first())
            .and_then(toml::Value::as_str)
            .expect("example declares a feature")
            .to_string();

        let dir = TempDir::new("deps-unused-feature-flag-registry-example");
        let manifest_path = write_fixture(&dir, "[dependencies]", dep_name, None, &[&feature], &[]);

        let workspace = crate::ingest::load(Some(&manifest_path)).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == UNUSED_FEATURE_FLAG_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn default_features_unused_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(DEFAULT_FEATURES_UNUSED_RULE)
            .expect("default-features-unused has a registry entry")
            .example
            .expect("default-features-unused has a curated example")
            .before;
        let manifest: toml::Value = toml::from_str(example).unwrap();
        let dep_name = manifest
            .get("dependencies")
            .and_then(toml::Value::as_table)
            .and_then(|table| table.keys().next())
            .expect("example declares a dependency")
            .clone();

        let dir = TempDir::new("deps-default-features-unused-registry-example");
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();
        std::fs::write(
            dir.join("main/Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{dep_name} = {{ path = \"../dep_crate\", default-features = true }}\n"
            ),
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            format!("[package]\nname = \"{dep_name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        let workspace = crate::ingest::load(Some(&dir.join("main/Cargo.toml"))).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == DEFAULT_FEATURES_UNUSED_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn unused_feature_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(UNUSED_FEATURE_RULE)
            .expect("unused-feature has a registry entry")
            .example
            .expect("unused-feature has a curated example")
            .before;

        let dir = TempDir::new("deps-unused-feature-registry-example");
        let manifest =
            write_crate_with_features(&dir, example, &[("src/lib.rs", "pub fn hello() {}\n")]);

        let workspace = crate::ingest::load(Some(&manifest)).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == UNUSED_FEATURE_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }

    /// The registry's curated `example.before` for this rule (see
    /// `rule_registry::RULE_REGISTRY`) must itself still trigger the rule —
    /// this is what keeps a landing-page-facing example from silently
    /// drifting away from what judge actually flags.
    #[test]
    fn dep_without_repo_registry_example_still_triggers_the_rule() {
        let example = crate::rule_registry::lookup(DEP_WITHOUT_REPO_RULE)
            .expect("dep-without-repo has a registry entry")
            .example
            .expect("dep-without-repo has a curated example")
            .before;
        let manifest: toml::Value = toml::from_str(example).unwrap();
        let dep_name = manifest
            .get("package")
            .and_then(|package| package.get("name"))
            .and_then(toml::Value::as_str)
            .expect("example declares a package name")
            .to_string();

        let dir = TempDir::new("deps-dep-without-repo-registry-example");
        std::fs::create_dir_all(dir.join("main/src")).unwrap();
        std::fs::create_dir_all(dir.join("dep_crate/src")).unwrap();
        std::fs::write(
            dir.join("main/Cargo.toml"),
            format!(
                "[package]\nname = \"fixture\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n{dep_name} = {{ path = \"../dep_crate\" }}\n"
            ),
        )
        .unwrap();
        std::fs::write(dir.join("main/src/lib.rs"), "pub fn hello() {}\n").unwrap();
        std::fs::write(
            dir.join("dep_crate/Cargo.toml"),
            format!("{example}edition = \"2021\"\n"),
        )
        .unwrap();
        std::fs::write(dir.join("dep_crate/src/lib.rs"), "pub fn noop() {}\n").unwrap();

        let workspace = crate::ingest::load(Some(&dir.join("main/Cargo.toml"))).unwrap();
        let report = analyze_workspace(&workspace);

        let hits: Vec<_> = report
            .findings
            .iter()
            .filter(|f| f.rule == DEP_WITHOUT_REPO_RULE)
            .collect();
        assert_eq!(hits.len(), 1);
    }
}