fallow-types 3.28.0

Shared types and serde paths for fallow codebase intelligence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
//! Typed envelope wrappers for the simple 1:1 dead-code findings whose
//! actions are entirely determined by the wrapper type (no per-instance
//! discriminants beyond what the bare finding already exposes).
//!
//! Each wrapper flattens the bare finding via `#[serde(flatten)]` so the
//! wire shape matches the previous `actions`-grafted output byte-for-byte.
//! `actions` is populated at construction time via each wrapper's
//! `with_actions` constructor and replaces the per-finding `inject_actions`
//! post-pass in `crates/cli/src/report/json.rs`. `introduced` carries the optional audit
//! breadcrumb that `crates/cli/src/audit.rs::annotate_issue_array` inserts
//! into the JSON object via `map.insert`; the wrapper-level field stays
//! `None` when serialized directly from Rust and is set by the audit pass
//! only when the issue was introduced relative to the merge-base.
//!
//! All nine wrappers ship with `IssueAction` arrays today; they pay the
//! `serde_json` dependency cost because `IssueAction` transitively
//! references `AddToConfigValue::RuleObject(serde_json::Map<...>)`. The
//! variants the wrappers actually emit (`Fix`, `SuppressLine`,
//! `SuppressFile`, `AddToConfig`) are small, but reusing the existing enum
//! keeps the wire-shape contract identical to the legacy post-pass.
//!
//! `introduced` is typed as `Option<AuditIntroduced>` (transparent newtype
//! over `bool`) so the regenerated schema renders the field via
//! `$ref: #/definitions/AuditIntroduced`, matching the reference the prior
//! post-pass augmentation graft used. The audit pass continues to inject a
//! bare bool via `map.insert("introduced", ...)`; serde reads it back into
//! `AuditIntroduced` transparently. The field stays absent at the wire when
//! `None` (`skip_serializing_if`).

use serde::{Deserialize, Serialize};
use std::path::Path;

use crate::envelope::AuditIntroduced;
use crate::output::{
    AddToConfigAction, AddToConfigKind, AddToConfigValue, FixAction, FixActionType,
    IgnoreExportsRule, IssueAction, SuppressFileAction, SuppressFileKind, SuppressLineAction,
    SuppressLineKind, SuppressLineScope,
};
use crate::results::{
    BoundaryCallViolation, BoundaryCoverageViolation, BoundaryViolation, CircularDependency,
    DependencyOverrideSource, DevDependencyInProduction, DuplicateExport, DuplicatePropShape,
    DynamicSegmentNameConflict, EmptyCatalogGroup, InvalidClientExport,
    MisconfiguredDependencyOverride, MisplacedDirective, MixedClientServerBarrel, PolicyViolation,
    PrivateTypeLeak, PropDrillingChain, ReExportCycle, ReExportCycleKind, RouteCollision,
    TestOnlyDependency, ThinWrapper, TypeOnlyDependency, UnlistedDependency, UnprovidedInject,
    UnrenderedComponent, UnresolvedCatalogReference, UnresolvedImport, UnusedCatalogEntry,
    UnusedComponentEmit, UnusedComponentInput, UnusedComponentOutput, UnusedComponentProp,
    UnusedDependency, UnusedDependencyOverride, UnusedExport, UnusedFile, UnusedLoadDataKey,
    UnusedMember, UnusedServerAction, UnusedSvelteEvent,
};
use crate::semantic::{
    SemanticCandidateDecision, SemanticCandidateDecisionKind, SemanticCompleteness,
};

/// Shared note for the `duplicate-exports` fix action. Mirrors the const used
/// by the human report (see `crates/cli/src/report/shared.rs`); kept here so
/// the wire-format builder reads from the same source of truth.
pub const NAMESPACE_BARREL_HINT: &str = "If every location is the sole `index.*` of its directory, this is likely an intentional namespace-barrel API. Prefer adding these files to `ignoreExports` over removing exports.";

/// JSON Schema fragment URL for the `add-to-config` `ignoreExports` action's
/// `value` payload. Pinned to the main branch so users browsing the action
/// value can navigate directly to the rule shape.
const IGNORE_EXPORTS_VALUE_SCHEMA: &str =
    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreExports";

/// JSON Schema fragment URL for the `ignoreCatalogReferences` rule items
/// referenced by `add-to-config` actions on `unresolved-catalog-references`.
const IGNORE_CATALOG_REFERENCES_VALUE_SCHEMA: &str = "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreCatalogReferences/items";

/// JSON Schema fragment URL for the `ignoreDependencyOverrides` rule items
/// referenced by `add-to-config` actions on both the unused- and
/// misconfigured-override findings.
const IGNORE_DEPENDENCY_OVERRIDES_VALUE_SCHEMA: &str = "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreDependencyOverrides/items";

const PNPM_WORKSPACE_FILE: &str = "pnpm-workspace.yaml";

fn manual_framework_fix(kind: FixActionType, description: &str, note: &str) -> IssueAction {
    IssueAction::Fix(FixAction {
        kind,
        auto_fixable: false,
        description: description.to_string(),
        note: Some(note.to_string()),
        available_in_catalogs: None,
        suggested_target: None,
    })
}

fn suppress_line(comment: &str) -> IssueAction {
    IssueAction::SuppressLine(SuppressLineAction {
        kind: SuppressLineKind::SuppressLine,
        auto_fixable: false,
        description: "Suppress with an inline comment above the line".to_string(),
        comment: comment.to_string(),
        scope: None,
    })
}

/// A per-finding caveat on a dead-code verdict that a file this run never
/// fully analyzed can distort.
///
/// Advisory provenance, in the same spirit as the fix path's
/// `low_confidence_off_graph` / `low_confidence_unresolved_imports` skip
/// reasons: a caveat NEVER withholds, reorders, downgrades, or re-severities
/// the finding, and never changes an exit code. It records that the verdict
/// was computed over an import graph fallow already knows is incomplete, so a
/// reader who sees the finding also sees the caveat instead of having to
/// notice a diagnostic at the other end of the envelope.
///
/// Deliberately NOT named `confidence`: `health --targets` already emits a
/// `confidence` key holding an enum string, and a shared consumer helper that
/// met both would see the same key change type. Emitted on every finding type
/// that registers it: the reachability arrays (`unused_files[]`,
/// `unused_exports[]`, `unused_types[]`), the member arrays
/// (`unused_enum_members[]`, `unused_class_members[]`, `unused_store_members[]`),
/// and the three dependency arrays. Sorted and deduplicated, absent from the
/// wire when empty. The set is open in the same sense
/// `workspace_diagnostics[].kind` is: treat an unrecognised value as "some
/// caveat" rather than as an error.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub enum ReachabilityCaveat {
    /// This finding's own file is one the run did not fully analyze, so the
    /// export and import lists extracted from it may stop short of the real
    /// ones. That reaches an `unused-file` verdict directly, because the
    /// "is any export of this file referenced from a reachable module" test
    /// reads exactly that truncated export list.
    ///
    /// Two workspace diagnostics put a file in this state: it was read but did
    /// not parse cleanly (`source-parse-degraded`), or it could not be read at
    /// all (`source-read-failure`). The token names the consequence rather than
    /// either cause, so a future kind that leaves a discovered file partially
    /// extracted carries the same value.
    ///
    /// Dependency findings never carry this value: the file they name is a
    /// `package.json`, not a parsed source module.
    IncompleteFileAnalysis,
    /// A module whose import list feeds this verdict was not analyzed, so the
    /// import that would have credited this finding may never have been seen.
    ///
    /// The cause is any workspace diagnostic that leaves a source file's
    /// imports unseen: a degraded parse (`source-parse-degraded`), a file that
    /// could not be read (`source-read-failure`), or a file discovery skipped
    /// before reading it (`skipped-large-file`, `skipped-minified-file`,
    /// `skipped-source-dotdir`). The token names the class rather than any one
    /// cause.
    ///
    /// Which modules feed the verdict differs by array, and the caveat is
    /// emitted only when a degraded module is actually one of them:
    ///
    /// - `unused_files[]`, `unused_exports[]`, and `unused_types[]` rest on
    ///   reachability, so only a degraded module that is itself observed
    ///   reachable can change the verdict. When every degraded module is
    ///   unreachable the caveat is absent, and soundly: the FIRST missing edge
    ///   on any entry-point path leaves from a module whose every predecessor
    ///   edge was observed, so that module is observed reachable. A file the
    ///   run never read has no module and no graph node, so its reachability
    ///   is not observable at all and that narrowing cannot be applied: any
    ///   skipped or unreadable source caveats every reachability verdict in
    ///   the run.
    /// - the member arrays (`unused_enum_members[]`, `unused_class_members[]`,
    ///   `unused_store_members[]`) do not rest on reachability at all: member
    ///   usage is collected by walking every module the run resolved,
    ///   reachable or not, so this narrowing does not apply to them either.
    ///   Same unnarrowed condition as the dependency arrays below, plus the
    ///   per-finding value above when the member's own file is the one that
    ///   was incompletely analyzed.
    /// - the dependency arrays rest on whether ANY module in the project
    ///   imports the package specifier, reachable or not, so any degraded
    ///   parse anywhere can hide the import that would have credited the
    ///   package. Reachability does not narrow that one.
    ///
    /// The limit, stated because an approximation presented as exact is worse
    /// than nothing: this is a RUN-level condition, not proof that a degraded
    /// module imports this path or package. An import the parser never saw
    /// cannot be attributed to a target, so the link cannot be narrowed
    /// further without re-reading the source. Read `workspace_diagnostics[]`
    /// for which files degraded.
    IncompleteImportGraph,
}

impl ReachabilityCaveat {
    /// The wire token.
    #[must_use]
    pub const fn token(self) -> &'static str {
        match self {
            Self::IncompleteFileAnalysis => "incomplete-file-analysis",
            Self::IncompleteImportGraph => "incomplete-import-graph",
        }
    }

    /// A one-line explanation for human and agent-facing renderers.
    ///
    /// Neither sentence names a single cause. A degraded parse is only one of
    /// the ways a file goes unread: it may also have been unreadable, or
    /// skipped before it was ever opened (oversized, minified, in a dotdir).
    /// Naming the parse case alone sent a reader whose run was degraded by the
    /// size guard hunting for parse errors that do not exist, so both messages
    /// point at `workspace_diagnostics[]`, which names the actual files.
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self {
            Self::IncompleteFileAnalysis => {
                "low: this file was not fully analyzed, so its extracted exports and imports may be incomplete; see workspace_diagnostics[]"
            }
            Self::IncompleteImportGraph => {
                "low: a module this run did not fully read may hold an import that would credit this; see workspace_diagnostics[]"
            }
        }
    }

    /// A compact label for a one-line human renderer, where the full
    /// [`Self::message`] would not fit next to the finding.
    #[must_use]
    pub const fn short_label(self) -> &'static str {
        match self {
            Self::IncompleteFileAnalysis => "incomplete file analysis",
            Self::IncompleteImportGraph => "incomplete import graph",
        }
    }
}

/// The compact labels of `caveats`, joined for a one-line renderer, or `None`
/// when there is nothing to say.
#[must_use]
pub fn caveat_labels(caveats: &[ReachabilityCaveat]) -> Option<String> {
    if caveats.is_empty() {
        return None;
    }
    let labels: Vec<&str> = caveats
        .iter()
        .map(|caveat| ReachabilityCaveat::short_label(*caveat))
        .collect();
    Some(labels.join(", "))
}

/// The compact parenthetical a one-line human renderer appends to a finding
/// carrying `caveats`, or `None` when there is nothing to say. Shared by every
/// dead-code section so the suffix reads the same everywhere.
#[must_use]
pub fn caveat_suffix(caveats: &[ReachabilityCaveat]) -> Option<String> {
    caveat_labels(caveats).map(|labels| format!("{CAVEAT_SUFFIX_MARKER}{labels})"))
}

/// The opening of the parenthetical [`caveat_suffix`] renders. Public because
/// one consumer can only see the rendered description: the CI review formats
/// build their comments from CodeClimate issues, whose `description` is the
/// only place the caveat survives (the CodeClimate wire is a published
/// contract with no field for it). Recognising the marker is what lets those
/// formats withhold a one-click mutation.
pub const CAVEAT_SUFFIX_MARKER: &str = " (caveat: ";

/// Whether a rendered finding description already carries a caveat
/// parenthetical, for a surface holding the string rather than the typed
/// finding.
///
/// Lives here, next to the renderer, so the producer and the recogniser cannot
/// drift; `a_rendered_suffix_is_recognised_by_the_marker` pins the pair.
#[must_use]
pub fn description_carries_caveat(description: &str) -> bool {
    description.contains(CAVEAT_SUFFIX_MARKER)
}

/// The compact label for one wire token, for a renderer that reads
/// `reachability_caveats[]` back off a serialized envelope instead of holding
/// the typed findings.
///
/// The value set is OPEN, exactly as the wire documentation says: a token this
/// build does not recognise is still a caveat, so it is rendered as itself with
/// its separators relaxed into spaces rather than dropped. Dropping it would
/// turn a finding whose evidence is incomplete back into a confident one,
/// which is the failure this whole mechanism exists to prevent.
#[must_use]
pub fn caveat_label_for_token(token: &str) -> String {
    match token {
        "incomplete-file-analysis" => {
            ReachabilityCaveat::short_label(ReachabilityCaveat::IncompleteFileAnalysis).to_owned()
        }
        "incomplete-import-graph" => {
            ReachabilityCaveat::short_label(ReachabilityCaveat::IncompleteImportGraph).to_owned()
        }
        other => other.replace('-', " "),
    }
}

/// The joined compact labels for wire tokens, or `None` when there are none.
/// The token-side twin of [`caveat_labels`], for renderers driven by a
/// serialized envelope rather than by typed findings.
#[must_use]
pub fn caveat_labels_for_tokens<'a>(tokens: impl IntoIterator<Item = &'a str>) -> Option<String> {
    let labels: Vec<String> = tokens.into_iter().map(caveat_label_for_token).collect();
    if labels.is_empty() {
        return None;
    }
    Some(labels.join(", "))
}

/// The token-side twin of [`caveat_suffix`], so an envelope-driven renderer
/// appends the same parenthetical as a findings-driven one.
#[must_use]
pub fn caveat_suffix_for_tokens<'a>(tokens: impl IntoIterator<Item = &'a str>) -> Option<String> {
    caveat_labels_for_tokens(tokens).map(|labels| format!("{CAVEAT_SUFFIX_MARKER}{labels})"))
}

/// The note every mutating action carries once [`MutationEvidence`] withholds
/// it. One string, so the CLI action array, the LSP diagnostic, and the MCP
/// tool contract all say the same thing about the same finding.
pub const INCOMPLETE_EVIDENCE_NOTE: &str = "Evidence is incomplete: a file this run did not fully analyze may hold the reference that \
     credits this finding, so this mutation is not applied automatically. Resolve the files named \
     in workspace_diagnostics[] and re-run, or confirm and remove it by hand.";

/// The one question every mutation surface asks before it offers, plans, or
/// performs a dead-code finding's removal.
///
/// A finding whose reachability verdict rests on a file the run never fully
/// read is still REPORTED, always: a caveat withholds no finding, changes no
/// severity, and moves no exit code. What it withholds is the automation. The
/// predicate lives here, next to the findings, rather than in any one consumer,
/// because it was re-derived per surface three times and a fourth door opened
/// every time: `fallow fix`, the LSP quick fix, and the `auto_fixable` flag an
/// agent plans against each answered it differently. Every one of those now
/// calls [`Self::may_auto_apply_mutation`], so a sixth finding type or a fourth
/// mutation surface cannot silently opt out.
///
/// Implemented only by the findings that can carry a caveat. A finding type
/// that exposes an auto-fixable mutation and does NOT implement this trait is
/// the bug this trait exists to make visible; `every_auto_fixable_dead_code_
/// mutation_is_gated` in this module's tests pins that.
pub trait MutationEvidence {
    /// The advisory caveats recorded on the reachability verdict behind this
    /// finding. Empty when the run analyzed every file it discovered.
    fn reachability_caveats(&self) -> &[ReachabilityCaveat];

    /// Whether this finding's mutation may be applied without a human first
    /// being told the evidence is incomplete. THE gate: never re-derive it,
    /// never widen it per surface.
    fn may_auto_apply_mutation(&self) -> bool {
        self.reachability_caveats().is_empty()
    }
}

/// Record a run's caveats on a finding, enforcing [`MutationEvidence`] on its
/// typed `actions` in the same step.
///
/// Separate from [`MutationEvidence`] so a read-only consumer (the fixer, the
/// LSP, a renderer) depends only on the question and never on the answer's
/// setter. `annotate` in the analysis layer is the single writer.
pub trait CaveatedFinding: MutationEvidence {
    /// Store `caveats` and downgrade every mutating action the gate now
    /// withholds. The field itself stays `pub` (a renderer test builds an
    /// already-caveated fixture directly, without running the annotation
    /// pass); every non-test writer goes through this setter instead of the
    /// field so the downgrade travels with the write.
    fn set_reachability_caveats(&mut self, caveats: Vec<ReachabilityCaveat>);
}

/// Downgrade every `Fix` action in `actions` when `caveats` is non-empty, so
/// the `auto_fixable` flag an agent plans against matches what `fallow fix`
/// will actually do. Only ever downgrades: a surface that has already decided
/// a mutation is unsafe for its own reasons keeps that decision.
fn withhold_caveated_mutations(actions: &mut [IssueAction], caveats: &[ReachabilityCaveat]) {
    if caveats.is_empty() {
        return;
    }
    for action in actions {
        let IssueAction::Fix(fix) = action else {
            continue;
        };
        fix.auto_fixable = false;
        fix.note = Some(match fix.note.take() {
            Some(existing) => format!("{existing}. {INCOMPLETE_EVIDENCE_NOTE}"),
            None => INCOMPLETE_EVIDENCE_NOTE.to_string(),
        });
    }
}

/// Implement the gate for a finding wrapper carrying a `reachability_caveats`
/// field alongside a typed `actions` array. A new caveated finding type adds
/// one line here rather than a new per-surface branch.
macro_rules! impl_caveated_finding {
    ($($finding:ty),+ $(,)?) => {
        $(
            impl MutationEvidence for $finding {
                fn reachability_caveats(&self) -> &[ReachabilityCaveat] {
                    &self.reachability_caveats
                }
            }

            impl CaveatedFinding for $finding {
                fn set_reachability_caveats(&mut self, caveats: Vec<ReachabilityCaveat>) {
                    withhold_caveated_mutations(&mut self.actions, &caveats);
                    self.reachability_caveats = caveats;
                }
            }
        )+
    };
}

/// Wire-shape envelope for an [`UnusedFile`] finding. The bare finding
/// flattens in via `#[serde(flatten)]`, with a typed `actions` array
/// populated at construction time and the audit-pass `introduced` flag
/// attached as an optional sibling.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedFileFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub file: UnusedFile,
    /// Suggested next steps: a `delete-file` primary and a `suppress-file`
    /// secondary. Always emitted (possibly empty for forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base. `None` when serialized directly from Rust.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the reachability verdict behind this finding.
    /// Sorted, deduplicated, and omitted from the wire when empty, so a run
    /// that analyzed every discovered file is byte-identical. Never gates the
    /// finding or the `delete-file` action, though `fallow fix` does withhold
    /// the removal of a caveated finding as low confidence.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedFileFinding {
    /// Build the wrapper from a raw [`UnusedFile`], computing the typed
    /// `actions` array inline. `introduced` stays `None` and is set later
    /// by `annotate_dead_code_json` if the audit pass runs.
    #[must_use]
    pub fn with_actions(file: UnusedFile) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::DeleteFile,
                auto_fixable: false,
                description: "Delete this file".to_string(),
                note: Some(
                    "File deletion may remove runtime functionality not visible to static analysis"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: "Suppress with a file-level comment at the top of the file"
                    .to_string(),
                comment: "// fallow-ignore-file unused-file".to_string(),
            }),
        ];
        Self {
            file,
            actions,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }
}

/// Wire-shape envelope for a [`PrivateTypeLeak`] finding. Mirrors
/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
/// `actions` array (`export-type` primary plus `suppress-line` secondary).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PrivateTypeLeakFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub leak: PrivateTypeLeak,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl PrivateTypeLeakFinding {
    /// Build the wrapper from a raw [`PrivateTypeLeak`].
    #[must_use]
    pub fn with_actions(leak: PrivateTypeLeak) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::ExportType,
                auto_fixable: false,
                description: "Export the referenced private type by name".to_string(),
                note: Some(
                    "Keep the type exported while it is part of a public signature".to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line private-type-leak".to_string(),
                scope: None,
            }),
        ];
        Self {
            leak,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnresolvedImport`] finding. Mirrors
/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
/// `actions` array (`resolve-import` primary plus config and inline
/// suppression actions).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnresolvedImportFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub import: UnresolvedImport,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnresolvedImportFinding {
    /// Build the wrapper from a raw [`UnresolvedImport`].
    #[must_use]
    pub fn with_actions(import: UnresolvedImport) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::ResolveImport,
                auto_fixable: false,
                description: "Fix the import specifier or install the missing module".to_string(),
                note: Some(
                    "Verify the module path and check tsconfig paths configuration".to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::AddToConfig(AddToConfigAction {
                kind: AddToConfigKind::AddToConfig,
                auto_fixable: false,
                description: format!(
                    "Add \"{}\" to ignoreUnresolvedImports in fallow config",
                    import.specifier
                ),
                config_key: "ignoreUnresolvedImports".to_string(),
                value: AddToConfigValue::Scalar(import.specifier.clone()),
                value_schema: Some(
                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreUnresolvedImports/items"
                        .to_string(),
                ),
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line unresolved-import".to_string(),
                scope: None,
            }),
        ];
        Self {
            import,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`CircularDependency`] finding. Mirrors
/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
/// `actions` array (`refactor-cycle` primary plus `suppress-line`
/// secondary).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CircularDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub cycle: CircularDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl CircularDependencyFinding {
    /// Build the wrapper from a raw [`CircularDependency`].
    #[must_use]
    pub fn with_actions(cycle: CircularDependency) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RefactorCycle,
                auto_fixable: false,
                description: "Extract shared logic into a separate module to break the cycle"
                    .to_string(),
                note: Some(
                    "Circular imports can cause initialization issues and make code harder to reason about"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line circular-dependency".to_string(),
                scope: None,
            }),
        ];
        Self {
            cycle,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`ReExportCycle`] finding. Mirrors
/// [`CircularDependencyFinding`]: flattens the bare finding and carries a
/// typed `actions` array (`refactor-re-export-cycle` informational primary
/// plus `suppress-file` secondary; cycles are file-scoped so a single
/// file-level suppression on the alphabetically-first member breaks the
/// cycle, and no `// fallow-ignore-next-line` form makes sense because the
/// diagnostic is anchored at line 1 col 0 of each member).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ReExportCycleFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub cycle: ReExportCycle,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl ReExportCycleFinding {
    /// Build the wrapper from a raw [`ReExportCycle`].
    ///
    /// The `SuppressFile` action targets the alphabetically-first member
    /// (`cycle.files[0]`; the `files` Vec is already sorted at graph layer);
    /// for multi-node cycles the description names the other members so
    /// consumers see context for why one file-level suppression suffices.
    #[must_use]
    pub fn with_actions(cycle: ReExportCycle) -> Self {
        // The description is a path-free hint about the suppression's
        // structural effect; the cycle's member list already ships in the
        // sibling `files` field, so consumers can correlate without
        // re-reading the description (and absolute paths cannot leak in
        // here, which the wrapper has no root-prefix context to strip).
        let suppress_description = match cycle.kind {
            ReExportCycleKind::SelfLoop => {
                "Suppress with a file-level comment at the top of this file. \
                 The cycle is a self-loop, so the suppression covers the entire finding."
                    .to_string()
            }
            ReExportCycleKind::MultiNode => {
                "Suppress with a file-level comment at the top of this file. \
                 One suppression on any member breaks the cycle for every member \
                 (see the sibling `files` array)."
                    .to_string()
            }
        };
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RefactorReExportCycle,
                auto_fixable: false,
                description: "Remove one `export * from` (or `export { ... } from`) \
                              statement on any one member to break the cycle"
                    .to_string(),
                note: Some(
                    "Re-export cycles are structurally a no-op: chain propagation through \
                     the loop never reaches a terminating module, so imports from any member \
                     may silently come up empty."
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: suppress_description,
                comment: "// fallow-ignore-file re-export-cycle".to_string(),
            }),
        ];
        Self {
            cycle,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`BoundaryViolation`] finding. Mirrors
/// [`UnusedFileFinding`]: flattens the bare finding and carries a typed
/// `actions` array (`refactor-boundary` primary plus `suppress-line`
/// secondary).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BoundaryViolationFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub violation: BoundaryViolation,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl BoundaryViolationFinding {
    /// Build the wrapper from a raw [`BoundaryViolation`].
    #[must_use]
    pub fn with_actions(violation: BoundaryViolation) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RefactorBoundary,
                auto_fixable: false,
                description: "Move the import through an allowed zone or restructure the dependency"
                    .to_string(),
                note: Some(
                    "This import crosses an architecture boundary that is not permitted by the configured rules"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line boundary-violation".to_string(),
                scope: None,
            }),
        ];
        Self {
            violation,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`BoundaryCoverageViolation`] finding. Carries
/// actions for assigning the file to a zone or explicitly allowing it to stay
/// unmatched.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BoundaryCoverageViolationFinding {
    /// The underlying coverage entry.
    #[serde(flatten)]
    pub violation: BoundaryCoverageViolation,
    /// Suggested next steps.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl BoundaryCoverageViolationFinding {
    /// Build the wrapper from a raw [`BoundaryCoverageViolation`].
    #[must_use]
    pub fn with_actions(violation: BoundaryCoverageViolation) -> Self {
        let path = violation.path.to_string_lossy().replace('\\', "/");
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RefactorBoundary,
                auto_fixable: false,
                description: "Add this file to a boundary zone pattern or move it under an existing zone"
                    .to_string(),
                note: Some(
                    "Boundary coverage is enabled, so every analyzed source file must match a zone unless allow-listed"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::AddToConfig(AddToConfigAction {
                kind: AddToConfigKind::AddToConfig,
                auto_fixable: false,
                description: format!(
                    "Add \"{path}\" to boundaries.coverage.allowUnmatched in fallow config"
                ),
                config_key: "boundaries.coverage.allowUnmatched".to_string(),
                value: AddToConfigValue::Scalar(path),
                value_schema: Some(
                    "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/boundaries/properties/coverage/properties/allowUnmatched/items"
                        .to_string(),
                ),
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: "Suppress with a file-level comment at the top of the file"
                    .to_string(),
                comment: "// fallow-ignore-file boundary-violation".to_string(),
            }),
        ];
        Self {
            violation,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`BoundaryCallViolation`] finding. Carries
/// actions for refactoring the forbidden call out of the zone or suppressing
/// it with the shared `boundary-violation` token.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct BoundaryCallViolationFinding {
    /// The underlying forbidden-call entry.
    #[serde(flatten)]
    pub violation: BoundaryCallViolation,
    /// Suggested next steps.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl BoundaryCallViolationFinding {
    /// Build the wrapper from a raw [`BoundaryCallViolation`].
    #[must_use]
    pub fn with_actions(violation: BoundaryCallViolation) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RefactorBoundary,
                auto_fixable: false,
                description: format!(
                    "Move the `{}` call out of zone '{}' or behind an allowed abstraction",
                    violation.callee, violation.zone,
                ),
                note: Some(format!(
                    "`boundaries.calls.forbidden` bans callees matching `{}` from zone '{}'. The check is syntactic: it applies only to files classified into a zone and does not follow aliased or re-bound callees",
                    violation.pattern, violation.zone,
                )),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line boundary-violation".to_string(),
                scope: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: "Suppress with a file-level comment at the top of the file"
                    .to_string(),
                comment: "// fallow-ignore-file boundary-violation".to_string(),
            }),
        ];
        Self {
            violation,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`PolicyViolation`] finding. Carries actions for
/// replacing the banned call, import, or effect, or suppressing it with a scoped
/// `policy-violation:<pack>/<rule-id>` token.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PolicyViolationFinding {
    /// The underlying rule-pack policy entry.
    #[serde(flatten)]
    pub violation: PolicyViolation,
    /// Suggested next steps.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl PolicyViolationFinding {
    /// Build the wrapper from a raw [`PolicyViolation`].
    #[must_use]
    pub fn with_actions(violation: PolicyViolation) -> Self {
        let what = match violation.kind {
            crate::results::PolicyRuleKind::BannedCall => "call",
            crate::results::PolicyRuleKind::BannedImport => "import",
            crate::results::PolicyRuleKind::BannedEffect => "effect",
            crate::results::PolicyRuleKind::BannedExport => "export",
        };
        let description = match &violation.message {
            Some(message) => format!("Replace the `{}` {what}: {message}", violation.matched),
            None => format!("Replace the `{}` {what}", violation.matched),
        };
        let suppress_token = format!("policy-violation:{}/{}", violation.pack, violation.rule_id);
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::ResolvePolicyViolation,
                auto_fixable: false,
                description,
                note: Some(format!(
                    "Rule `{}/{}` from the configured rule packs bans this {what}. The check is syntactic: it does not follow aliased or re-bound callees, and import matching uses the raw specifier",
                    violation.pack, violation.rule_id,
                )),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress this rule-pack rule with an inline comment above the line"
                    .to_string(),
                comment: format!("// fallow-ignore-next-line {suppress_token}"),
                scope: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description:
                    "Suppress this rule-pack rule with a file-level comment at the top of the file"
                        .to_string(),
                comment: format!("// fallow-ignore-file {suppress_token}"),
            }),
        ];
        Self {
            violation,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedExport`] finding consumed under the
/// `unused_exports` key. Same Rust struct as [`UnusedTypeFinding`], with a
/// different fix description so consumers can tell value-export from
/// type-export removal at the action level.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedExportFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub export: UnusedExport,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Type-aware evidence for this exact candidate when requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantic: Option<SemanticCandidateDecision>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the reachability verdict behind this finding.
    /// Sorted, deduplicated, and omitted from the wire when empty. Never gates
    /// the finding or the `remove-export` action, though `fallow fix` does
    /// withhold the removal of a caveated export as low confidence.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedExportFinding {
    /// Build the wrapper. When `export.is_re_export` is true, the fix
    /// action's `note` warns about possible public-API surface; otherwise
    /// `note` is absent on the fix action.
    #[must_use]
    pub fn with_actions(export: UnusedExport) -> Self {
        let note = if export.is_re_export {
            Some(
                "This finding originates from a re-export; verify it is not part of your public API before removing"
                    .to_string(),
            )
        } else {
            None
        };
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RemoveExport,
                auto_fixable: true,
                description: "Remove the unused export from the public API".to_string(),
                note,
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line unused-export".to_string(),
                scope: None,
            }),
        ];
        Self {
            export,
            actions,
            semantic: None,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }

    /// Attach type-aware evidence and disable the syntactic fix when semantic
    /// analysis could not establish complete negative evidence.
    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
        set_export_semantic_action(&mut self.actions, &decision, &self.reachability_caveats);
        self.semantic = Some(decision);
    }
}

/// Wire-shape envelope for an [`UnusedExport`] finding consumed under the
/// `unused_types` key. Wraps the same bare [`UnusedExport`] struct as
/// [`UnusedExportFinding`] but emits a fix action targeted at type-only
/// declarations, with the same `is_re_export`-aware note swap.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedTypeFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub export: UnusedExport,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Type-aware evidence for this exact candidate when requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantic: Option<SemanticCandidateDecision>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the reachability verdict behind this finding.
    /// A type export rests on exactly the reachability test an
    /// `unused_exports[]` entry does, and the LSP offers the same
    /// remove-the-`export`-keyword quick fix for both, so the two must render
    /// with the same confidence. Sorted, deduplicated, omitted when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedTypeFinding {
    /// Build the wrapper. `is_re_export` swaps the fix note the same way as
    /// [`UnusedExportFinding::with_actions`].
    #[must_use]
    pub fn with_actions(export: UnusedExport) -> Self {
        let note = if export.is_re_export {
            Some(
                "This finding originates from a re-export; verify it is not part of your public API before removing"
                    .to_string(),
            )
        } else {
            None
        };
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RemoveExport,
                auto_fixable: true,
                description:
                    "Remove the `export` (or `export type`) keyword from the type declaration"
                        .to_string(),
                note,
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line unused-type".to_string(),
                scope: None,
            }),
        ];
        Self {
            export,
            actions,
            semantic: None,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }

    /// Attach type-aware evidence and disable the syntactic fix when semantic
    /// analysis could not establish complete negative evidence.
    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
        set_export_semantic_action(&mut self.actions, &decision, &self.reachability_caveats);
        self.semantic = Some(decision);
    }
}

/// The semantic pass runs in the API layer, AFTER the analysis layer stamped
/// this run's caveats, and it is the one code path that RAISES `auto_fixable`.
/// It therefore has to ask the gate too, or a `Complete` semantic verdict would
/// silently re-open a mutation the incomplete run had already withheld.
fn set_export_semantic_action(
    actions: &mut [IssueAction],
    decision: &SemanticCandidateDecision,
    caveats: &[ReachabilityCaveat],
) {
    let complete_negative = decision.decision
        == SemanticCandidateDecisionKind::ConfirmedNoStaticReferences
        && decision.status == SemanticCompleteness::Complete;
    let Some(IssueAction::Fix(action)) = actions.first_mut() else {
        return;
    };
    action.auto_fixable = complete_negative && caveats.is_empty();
    if !complete_negative {
        action.note = Some(
            "Type-aware analysis retained this candidate because complete negative evidence was not available"
                .to_string(),
        );
    }
    if !caveats.is_empty() {
        action.note = Some(INCOMPLETE_EVIDENCE_NOTE.to_string());
    }
}

/// Wire-shape envelope for an [`InvalidClientExport`] finding. There is no safe
/// auto-fix: the export itself may be a legitimate client-component value
/// export that happens to collide with a Next.js server-only name, so removing
/// it could break the component. Actions are a manual `move-to-server-module`
/// fix (the real remediation) plus a line-level suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct InvalidClientExportFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub export: InvalidClientExport,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl InvalidClientExportFinding {
    /// Build the wrapper from a raw [`InvalidClientExport`]. Emits a manual
    /// fix action (move the server-only export to a non-client module) plus a
    /// line-level suppress: there is no safe auto-fix because removing the
    /// export could break a legitimate client component.
    #[must_use]
    pub fn with_actions(export: InvalidClientExport) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::MoveToServerModule,
                auto_fixable: false,
                description: "Move the server-only export to a non-client module and import it from there"
                    .to_string(),
                note: Some(
                    "A \"use client\" file cannot export a Next.js server-only or route-config name; Next.js rejects it at build time"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line invalid-client-export".to_string(),
                scope: None,
            }),
        ];
        Self {
            export,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`MixedClientServerBarrel`] finding. There is no
/// safe auto-fix: splitting a barrel into separate client and server modules is
/// a human decision (the barrel may intentionally aggregate both surfaces).
/// Actions are a manual `split-mixed-barrel` fix (the real remediation) plus a
/// line-level suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MixedClientServerBarrelFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub barrel: MixedClientServerBarrel,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl MixedClientServerBarrelFinding {
    /// Build the wrapper from a raw [`MixedClientServerBarrel`]. Emits a manual
    /// fix action (split the barrel into separate client and server halves)
    /// plus a line-level suppress: there is no safe auto-fix because splitting
    /// the barrel is a human decision.
    #[must_use]
    pub fn with_actions(barrel: MixedClientServerBarrel) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::SplitMixedBarrel,
                auto_fixable: false,
                description: "Split the barrel so client and server-only modules are re-exported from separate files"
                    .to_string(),
                note: Some(
                    "Importing one name from this barrel drags the other's directive across the client/server boundary"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line mixed-client-server-barrel".to_string(),
                scope: None,
            }),
        ];
        Self {
            barrel,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`MisplacedDirective`] finding. There is no safe
/// auto-fix: moving a directive to the leading prologue is a small but
/// judgement-bearing edit (the author may have intended the file to be a
/// server module after all). Actions are a manual `hoist-directive` fix (the
/// real remediation) plus a line-level suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MisplacedDirectiveFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub directive_site: MisplacedDirective,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl MisplacedDirectiveFinding {
    /// Build the wrapper from a raw [`MisplacedDirective`]. Emits a manual fix
    /// action (hoist the directive to the leading prologue) plus a line-level
    /// suppress: there is no safe auto-fix because moving a directive can
    /// change module semantics and is a human decision.
    #[must_use]
    pub fn with_actions(directive_site: MisplacedDirective) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::HoistDirective,
                auto_fixable: false,
                description: "Move the directive to the very top of the file, above all imports and statements"
                    .to_string(),
                note: Some(
                    "An RSC bundler honors the directive only in the leading prologue; here it precedes other statements and is silently ignored"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line misplaced-directive".to_string(),
                scope: None,
            }),
        ];
        Self {
            directive_site,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnprovidedInject`] finding. There is no safe
/// auto-fix: the fix is binary but judgement-bearing (add a `provide` for the
/// key, or delete the dead inject). Actions are manual remediation guidance
/// plus a line-level suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnprovidedInjectFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub inject: UnprovidedInject,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnprovidedInjectFinding {
    /// Build the wrapper from a raw [`UnprovidedInject`]. Emits a manual fix
    /// action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(inject: UnprovidedInject) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::ProvideInject,
                "Provide this injected key, or remove the inject / getContext call",
                "Manual review required: dependency-injection keys can be provided by framework wiring, tests, or package consumers outside this project.",
            ),
            suppress_line("// fallow-ignore-next-line unprovided-inject"),
        ];
        Self {
            inject,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedServerAction`] finding. There is no safe
/// auto-fix: the fix is binary but judgement-bearing (wire the action up to a
/// consumer, or delete it). Actions are manual remediation guidance plus a
/// line-level suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedServerActionFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub action: UnusedServerAction,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedServerActionFinding {
    /// Build the wrapper from a raw [`UnusedServerAction`]. Emits a manual fix
    /// action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(action: UnusedServerAction) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::WireServerAction,
                "Wire the server action to a caller or form action, or remove it",
                "Manual review required: server actions may still be POST-able by action id or invoked reflectively outside the static project graph.",
            ),
            suppress_line("// fallow-ignore-next-line unused-server-action"),
        ];
        Self {
            action,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedLoadDataKey`] finding. There is no safe
/// auto-fix: a `load()` fetch can have side effects, so deleting the key is a
/// human call. Actions are manual remediation guidance plus a line-level
/// suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedLoadDataKeyFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub key: UnusedLoadDataKey,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedLoadDataKeyFinding {
    /// Build the wrapper from a raw [`UnusedLoadDataKey`]. Emits a manual fix
    /// action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(key: UnusedLoadDataKey) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::UseLoadData,
                "Read this load data key from the route UI, or remove it from the load return",
                "Manual review required: load functions can perform real server or database work, so verify side effects before deleting the producer.",
            ),
            suppress_line("// fallow-ignore-next-line unused-load-data-key"),
        ];
        Self {
            key,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnrenderedComponent`] finding. There is no safe
/// auto-fix: the fix is binary but judgement-bearing (render the component
/// somewhere, or delete the dead component). Actions are manual remediation
/// guidance plus a line-level suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnrenderedComponentFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub component: UnrenderedComponent,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnrenderedComponentFinding {
    /// Build the wrapper from a raw [`UnrenderedComponent`]. Emits a manual
    /// fix action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(component: UnrenderedComponent) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::RenderComponent,
                "Render the reachable component from project code, or remove it",
                "Manual review required: exported library components and dynamic render registries can be intentionally reachable without static template usage.",
            ),
            suppress_line("// fallow-ignore-next-line unrendered-component"),
        ];
        Self {
            component,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedComponentProp`] finding. There is no safe
/// auto-fix: removing a declared prop is judgement-bearing (the prop may be part
/// of a deliberately-stable public component API). Actions are manual
/// remediation guidance plus a line-level suppress at the prop declaration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedComponentPropFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub prop: UnusedComponentProp,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedComponentPropFinding {
    /// Build the wrapper from a raw [`UnusedComponentProp`]. Emits a manual
    /// fix action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(prop: UnusedComponentProp) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::UseComponentProp,
                "Use the declared prop in the component, or remove it from the component API",
                "Manual review required: public component APIs can intentionally keep stable props for external consumers.",
            ),
            suppress_line("// fallow-ignore-next-line unused-component-prop"),
        ];
        Self {
            prop,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedComponentEmit`] finding. There is no safe
/// auto-fix: removing a declared emit is judgement-bearing (the event may be
/// part of a deliberately-stable public component API). Actions are manual
/// remediation guidance plus a line-level suppress at the emit declaration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedComponentEmitFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub emit: UnusedComponentEmit,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedComponentEmitFinding {
    /// Build the wrapper from a raw [`UnusedComponentEmit`]. Emits a manual
    /// fix action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(emit: UnusedComponentEmit) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::EmitComponentEvent,
                "Emit the declared event from the component, or remove it from the component API",
                "Manual review required: public component APIs can intentionally keep stable events for external listeners.",
            ),
            suppress_line("// fallow-ignore-next-line unused-component-emit"),
        ];
        Self {
            emit,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedSvelteEvent`] finding. There is no safe
/// auto-fix: removing a dispatched event is judgement-bearing (the event may be
/// part of a deliberately-stable public component API, or a listener may be
/// added later). Actions are manual remediation guidance plus a line-level
/// suppress at the `dispatch` call.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedSvelteEventFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub event: UnusedSvelteEvent,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedSvelteEventFinding {
    /// Build the wrapper from a raw [`UnusedSvelteEvent`]. Emits a manual fix
    /// action plus a line-level suppress.
    #[must_use]
    pub fn with_actions(event: UnusedSvelteEvent) -> Self {
        let actions = vec![
            manual_framework_fix(
                FixActionType::WireSvelteEvent,
                "Add or forward a listener for this custom event, or remove the dispatch",
                "Manual review required: public Svelte component APIs can intentionally dispatch events for package consumers outside this project.",
            ),
            suppress_line("// fallow-ignore-next-line unused-svelte-event"),
        ];
        Self {
            event,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`PropDrillingChain`] finding. There is no safe
/// auto-fix: collapsing a drilling chain (colocate the consumer, lift to a
/// context, or compose the component) is a design decision. The only action is a
/// line-level suppress at the source hop's prop declaration. The rule defaults
/// to `off` (opt-in health signal), so this finding is dormant by default.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PropDrillingChainFinding {
    /// The underlying located chain.
    #[serde(flatten)]
    pub chain: PropDrillingChain,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl PropDrillingChainFinding {
    /// Build the wrapper from a raw [`PropDrillingChain`]. Emits only a
    /// line-level suppress action anchored at the source hop: there is no safe
    /// auto-fix because collapsing the chain is a design decision (colocate,
    /// lift to context, or compose).
    #[must_use]
    pub fn with_actions(chain: PropDrillingChain) -> Self {
        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
            kind: SuppressLineKind::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment above the source prop declaration"
                .to_string(),
            comment: "// fallow-ignore-next-line prop-drilling".to_string(),
            scope: None,
        })];
        Self {
            chain,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`ThinWrapper`] finding. There is no safe
/// auto-fix: inlining a thin wrapper at its call sites (or deleting it) is a
/// design decision. The only action is a line-level suppress at the wrapper's
/// definition. The rule defaults to `off` (opt-in health signal), so this
/// finding is dormant by default.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ThinWrapperFinding {
    /// The underlying located thin wrapper.
    #[serde(flatten)]
    pub wrapper: ThinWrapper,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl ThinWrapperFinding {
    /// Build the wrapper from a raw [`ThinWrapper`]. Emits only a line-level
    /// suppress action anchored at the wrapper definition: there is no safe
    /// auto-fix because inlining or deleting the wrapper is a design decision.
    #[must_use]
    pub fn with_actions(wrapper: ThinWrapper) -> Self {
        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
            kind: SuppressLineKind::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment above the component definition"
                .to_string(),
            comment: "// fallow-ignore-next-line thin-wrapper".to_string(),
            scope: None,
        })];
        Self {
            wrapper,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`DuplicatePropShape`] finding. There is no safe
/// auto-fix: extracting a shared `Props` type or a base component for a group of
/// same-shaped components is a design decision. The actions are manual guidance
/// (extract the shared shape) plus a line-level suppress at the component
/// definition and a file-level suppress escape hatch (mirroring the
/// route-collision multi-file model). The rule defaults to `off` (opt-in health
/// signal), so this finding is dormant by default.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DuplicatePropShapeFinding {
    /// The underlying duplicate-prop-shape entry.
    #[serde(flatten)]
    pub shape: DuplicatePropShape,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl DuplicatePropShapeFinding {
    /// Build the wrapper from a raw [`DuplicatePropShape`]. Manual guidance is
    /// the primary action (extract a shared shape); a line-level suppress at the
    /// component definition and a file-level suppress escape hatch follow,
    /// mirroring the multi-file route-collision suppress model. There is no safe
    /// auto-fix because extracting a shared type or base component is a design
    /// decision.
    #[must_use]
    pub fn with_actions(shape: DuplicatePropShape) -> Self {
        let actions = vec![
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Three or more components share this exact prop shape. Extract one \
                              shared `Props` type (or a base component) that every member reuses, \
                              or keep them separate if a per-variant divergence is planned. \
                              Suppress one member with an inline comment above the component \
                              definition."
                    .to_string(),
                comment: "// fallow-ignore-next-line duplicate-prop-shape".to_string(),
                scope: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: "Escape hatch: a file-level suppress silences this member but it \
                              still appears in its siblings' `sharing_components` (the group is \
                              real regardless of suppression)."
                    .to_string(),
                comment: "// fallow-ignore-file duplicate-prop-shape".to_string(),
            }),
        ];
        Self {
            shape,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedComponentInput`] finding. There is no safe
/// auto-fix: removing a declared input is judgement-bearing (the input may be
/// part of a deliberately-stable public component API). The only action is a
/// line-level suppress at the input declaration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedComponentInputFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub input: UnusedComponentInput,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedComponentInputFinding {
    /// Build the wrapper from a raw [`UnusedComponentInput`]. Emits only a
    /// line-level suppress action: there is no safe auto-fix because removing an
    /// input is a human decision (it may be part of a stable component API).
    #[must_use]
    pub fn with_actions(input: UnusedComponentInput) -> Self {
        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
            kind: SuppressLineKind::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment above the line".to_string(),
            comment: "// fallow-ignore-next-line unused-component-input".to_string(),
            scope: None,
        })];
        Self {
            input,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedComponentOutput`] finding. There is no safe
/// auto-fix: removing a declared output is judgement-bearing (the event may be
/// part of a deliberately-stable public component API). The only action is a
/// line-level suppress at the output declaration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedComponentOutputFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub output: UnusedComponentOutput,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedComponentOutputFinding {
    /// Build the wrapper from a raw [`UnusedComponentOutput`]. Emits only a
    /// line-level suppress action: there is no safe auto-fix because removing an
    /// output is a human decision (it may be part of a stable component API).
    #[must_use]
    pub fn with_actions(output: UnusedComponentOutput) -> Self {
        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
            kind: SuppressLineKind::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment above the line".to_string(),
            comment: "// fallow-ignore-next-line unused-component-output".to_string(),
            scope: None,
        })];
        Self {
            output,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`RouteCollision`] finding. A route collision is a
/// guaranteed `next build` failure, so the PRIMARY action is manual guidance
/// (move or merge one of the colliding files), NOT a suppress: suppressing a
/// build error never makes the build pass. A file-level suppress is offered as
/// an escape hatch only.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RouteCollisionFinding {
    /// The underlying route-collision entry.
    #[serde(flatten)]
    pub collision: RouteCollision,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl RouteCollisionFinding {
    /// Build the wrapper from a raw [`RouteCollision`]. The primary action is
    /// manual guidance because suppressing a guaranteed build error is never
    /// the right fix; a file-level suppress is the escape hatch only.
    #[must_use]
    pub fn with_actions(collision: RouteCollision) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::ResolveRouteCollision,
                auto_fixable: false,
                description: "Two or more files resolve to the same URL. Move or merge one so \
                              each URL has a single owner. Route groups `(name)` and parallel \
                              slots `@name` are the only legal same-URL shapes."
                    .to_string(),
                note: Some(
                    "Next.js fails the build with \"You cannot have two parallel pages that \
                     resolve to the same path\". See the sibling `conflicting_paths` array for \
                     the other files that own this URL."
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: "Escape hatch only: a file-level suppress silences the finding but \
                              does NOT make `next build` pass. Prefer moving or merging a file."
                    .to_string(),
                comment: "// fallow-ignore-file route-collision".to_string(),
            }),
        ];
        Self {
            collision,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`DynamicSegmentNameConflict`] finding. The
/// conflict is a Next.js dev / runtime error (`next build` does NOT catch it),
/// so the primary action is manual guidance (rename the dynamic segments to a
/// single consistent slug name), with a file-level suppress as escape hatch.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DynamicSegmentNameConflictFinding {
    /// The underlying dynamic-segment-name-conflict entry.
    #[serde(flatten)]
    pub conflict: DynamicSegmentNameConflict,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl DynamicSegmentNameConflictFinding {
    /// Build the wrapper from a raw [`DynamicSegmentNameConflict`]. Manual
    /// guidance primary action; file-level suppress escape hatch only.
    #[must_use]
    pub fn with_actions(conflict: DynamicSegmentNameConflict) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::ResolveDynamicSegmentNameConflict,
                auto_fixable: false,
                description: "Sibling dynamic segments at the same position use different param \
                              names. Rename them to one consistent slug name (e.g. pick `[id]` \
                              or `[slug]` for both)."
                    .to_string(),
                note: Some(
                    "Next.js throws \"You cannot use different slug names for the same dynamic \
                     path\" at dev / runtime when the position is hit; `next build` does not \
                     catch it. See the sibling `conflicting_segments` array."
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressFile(SuppressFileAction {
                kind: SuppressFileKind::SuppressFile,
                auto_fixable: false,
                description: "Escape hatch only: a file-level suppress silences the finding but \
                              does NOT stop Next.js from throwing at dev / runtime. Prefer \
                              renaming the segments."
                    .to_string(),
                comment: "// fallow-ignore-file dynamic-segment-name-conflict".to_string(),
            }),
        ];
        Self {
            conflict,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
/// `unused_enum_members` key.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedEnumMemberFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub member: UnusedMember,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the verdict behind this finding. A member's usage
    /// is collected by walking the member accesses of every module the run
    /// parsed, so a member whose only reference lives in a file the run never
    /// read reads as unused exactly like an export does. Sorted,
    /// deduplicated, and omitted from the wire when empty. Never gates the
    /// finding; it does withhold the `remove-enum-member` mutation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedEnumMemberFinding {
    /// Build the wrapper from a raw [`UnusedMember`].
    #[must_use]
    pub fn with_actions(member: UnusedMember) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RemoveEnumMember,
                auto_fixable: true,
                description: "Remove this enum member".to_string(),
                note: None,
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line unused-enum-member".to_string(),
                scope: None,
            }),
        ];
        Self {
            member,
            actions,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }
}

/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
/// `unused_class_members` key. Same Rust struct as
/// [`UnusedEnumMemberFinding`]; the fix action and suppress comment carry
/// the class-member kebab-case identifier instead.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedClassMemberFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub member: UnusedMember,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Type-aware evidence for this exact candidate when requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantic: Option<SemanticCandidateDecision>,
    /// Internal marker for a framework member that the syntactic analysis
    /// suppresses, but the semantic pass may promote after proving complete
    /// closed-world absence. Never serialized as part of the public finding.
    #[serde(skip)]
    #[cfg_attr(feature = "schema", schemars(skip))]
    pub semantic_only_candidate: bool,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the verdict behind this finding. A class member's
    /// usage is collected by the same reachability-free member-access walk an
    /// enum member's is, so it takes the enum-member rule unchanged: any module
    /// this run analyzed incompletely can hold the access that credits it.
    /// Sorted, deduplicated, and omitted from the wire when empty. Never gates
    /// the finding; it does withhold the `remove-class-member` mutation that
    /// the type-aware pass would otherwise open.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedClassMemberFinding {
    /// Build the wrapper from a raw [`UnusedMember`]. Class-member fixes
    /// are not auto-applied (members can be used via dependency injection
    /// or decorators), so `auto_fixable` is `false` and a context note is
    /// attached.
    #[must_use]
    pub fn with_actions(member: UnusedMember) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::RemoveClassMember,
                auto_fixable: false,
                description: "Remove this class member".to_string(),
                note: Some(
                    "Class member may be used via dependency injection or decorators".to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with an inline comment above the line".to_string(),
                comment: "// fallow-ignore-next-line unused-class-member".to_string(),
                scope: None,
            }),
        ];
        Self {
            member,
            actions,
            semantic: None,
            semantic_only_candidate: false,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }

    /// Mark this finding as latent until semantic analysis proves that the
    /// framework contract does not apply and no static references exist.
    #[must_use]
    pub const fn semantic_only_candidate(mut self) -> Self {
        self.semantic_only_candidate = true;
        self
    }

    /// Attach the canonical semantic decision and expose the class-member fix
    /// only when the API policy granted closed-world eligibility AND this run
    /// holds the evidence for the mutation.
    ///
    /// This is the one code path that RAISES `auto_fixable` on a class member,
    /// and it runs in the API layer AFTER the analysis layer stamped the run's
    /// caveats, so it asks the gate for the same reason
    /// `set_export_semantic_action` does: a closed-world verdict computed
    /// over a program the run never fully read must not re-open a removal the
    /// incomplete run already withheld. The withheld note names the evidence
    /// gap rather than the semantic explanation, which stays readable on the
    /// finding's own `semantic` object.
    pub fn set_semantic_decision(&mut self, decision: SemanticCandidateDecision) {
        let evidence_complete = self.reachability_caveats.is_empty();
        if let Some(IssueAction::Fix(action)) = self.actions.first_mut() {
            action.auto_fixable = decision.closed_world_eligible && evidence_complete;
            action.note = Some(if evidence_complete {
                decision.explanation.clone()
            } else {
                INCOMPLETE_EVIDENCE_NOTE.to_string()
            });
        }
        self.semantic = Some(decision);
    }
}

/// Wire-shape envelope for an [`UnusedMember`] finding consumed under the
/// `unused_store_members` key (a Pinia `state` / `getters` / `actions` key, or
/// a setup-store returned key, declared but never accessed by any consumer
/// project-wide). Same Rust struct as [`UnusedClassMemberFinding`]. Emits only
/// a line-level suppress action: there is no safe auto-fix because a store
/// member can be accessed reflectively (a Pinia plugin, `store.$onAction`, or
/// dynamic dispatch) in ways syntactic analysis cannot see, so removal is a
/// behavioral change the user must own.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedStoreMemberFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub member: UnusedMember,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the verdict behind this finding. A store member's
    /// usage is collected by the same reachability-free member-access walk a
    /// class member's is, so it takes the member rule unchanged: any module
    /// this run analyzed incompletely can hold the access that credits it.
    /// Sorted, deduplicated, and omitted from the wire when empty. There is no
    /// mutation here to withhold, because a store member offers none on any
    /// surface; this is disclosure only, so a reader deciding by hand is told
    /// what the run did not see.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedStoreMemberFinding {
    /// Build the wrapper from a raw [`UnusedMember`]. Emits only a line-level
    /// suppress action (no auto-fix: store members can be accessed
    /// reflectively, so removal is never provably safe).
    #[must_use]
    pub fn with_actions(member: UnusedMember) -> Self {
        let actions = vec![IssueAction::SuppressLine(SuppressLineAction {
            kind: SuppressLineKind::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment above the line".to_string(),
            comment: "// fallow-ignore-next-line unused-store-member".to_string(),
            scope: None,
        })];
        Self {
            member,
            actions,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }
}

/// Build the `IssueAction` vec for the three `unused_dependencies`,
/// `unused_dev_dependencies`, `unused_optional_dependencies` views over the
/// same bare [`UnusedDependency`] struct. Each wrapper differs only in the
/// `package_json_location` string (`"dependencies"` / `"devDependencies"` /
/// `"optionalDependencies"`) baked into the fix-action description and in
/// the `suppress_issue_kind` used by the inline-suppress comment. All three
/// share the cross-workspace swap (when `dep.used_in_workspaces` is
/// non-empty the primary fix flips from `remove-dependency` to
/// `move-dependency` because the dep is imported by ANOTHER workspace and
/// `fallow fix` cannot safely remove it).
fn build_unused_dependency_actions(
    dep: &UnusedDependency,
    package_json_location: &str,
    suppress_issue_kind: &str,
) -> Vec<IssueAction> {
    let mut actions = Vec::with_capacity(2);
    let cross_workspace = !dep.used_in_workspaces.is_empty();
    actions.push(if cross_workspace {
        IssueAction::Fix(FixAction {
            kind: FixActionType::MoveDependency,
            auto_fixable: false,
            description: "Move this dependency to the workspace package.json that imports it"
                .to_string(),
            note: Some(
                "fallow fix will not remove dependencies that are imported by another workspace"
                    .to_string(),
            ),
            available_in_catalogs: None,
            suggested_target: None,
        })
    } else {
        IssueAction::Fix(FixAction {
            kind: FixActionType::RemoveDependency,
            auto_fixable: true,
            description: format!("Remove from {package_json_location} in package.json"),
            note: None,
            available_in_catalogs: None,
            suggested_target: None,
        })
    });
    actions.push(build_ignore_dependencies_suppress_action(
        &dep.package_name,
        suppress_issue_kind,
    ));
    actions
}

/// Build the standard `add-to-config` `ignoreDependencies` suppress action
/// for any finding whose primary key is a package name. Used by the four
/// dependency-family wrappers (unused / unlisted / type-only / test-only).
/// The `_suppress_issue_kind` argument is currently unused; the pre-2.76
/// `inject_actions` post-pass also did not embed the issue kind in this
/// shape (no inline `// fallow-ignore-next-line ...` comment because the
/// finding is anchored at a package.json line, not at a source-file line).
fn build_ignore_dependencies_suppress_action(
    package_name: &str,
    _suppress_issue_kind: &str,
) -> IssueAction {
    IssueAction::AddToConfig(AddToConfigAction {
        kind: AddToConfigKind::AddToConfig,
        auto_fixable: false,
        description: format!("Add \"{package_name}\" to ignoreDependencies in fallow config"),
        config_key: "ignoreDependencies".to_string(),
        value: AddToConfigValue::Scalar(package_name.to_string()),
        value_schema: Some(
            "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreDependencies/items"
                .to_string(),
        ),
    })
}

/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
/// the `unused_dependencies` key (production deps). Flattens the bare
/// finding; the typed `actions` array carries either a `remove-dependency`
/// or `move-dependency` primary depending on
/// `inner.used_in_workspaces`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: UnusedDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the verdict behind this finding. A dependency is
    /// reported unused when NO module in the project imports its specifier,
    /// so a module that parsed with errors can hide the import that would
    /// have credited the package. Sorted, deduplicated, and omitted from the
    /// wire when empty. Never gates the finding, though `fallow fix`
    /// withholds the `remove-dependency` write while a caveat stands.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedDependencyFinding {
    /// Build the wrapper. Switches the primary fix from `remove-dependency`
    /// to `move-dependency` when the dep is imported by another workspace.
    #[must_use]
    pub fn with_actions(dep: UnusedDependency) -> Self {
        let actions = build_unused_dependency_actions(&dep, "dependencies", "unused-dependency");
        Self {
            dep,
            actions,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }
}

/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
/// the `unused_dev_dependencies` key. Same bare struct as
/// [`UnusedDependencyFinding`]; the fix description points at
/// `devDependencies` and the suppress comment uses
/// `unused-dev-dependency`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedDevDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: UnusedDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the verdict behind this finding. A dependency is
    /// reported unused when NO module in the project imports its specifier,
    /// so a module that parsed with errors can hide the import that would
    /// have credited the package. Sorted, deduplicated, and omitted from the
    /// wire when empty. Never gates the finding, though `fallow fix`
    /// withholds the `remove-dependency` write while a caveat stands.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedDevDependencyFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(dep: UnusedDependency) -> Self {
        let actions =
            build_unused_dependency_actions(&dep, "devDependencies", "unused-dev-dependency");
        Self {
            dep,
            actions,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }
}

/// Wire-shape envelope for an [`UnusedDependency`] finding consumed under
/// the `unused_optional_dependencies` key. Same bare struct as
/// [`UnusedDependencyFinding`]; the fix description points at
/// `optionalDependencies`. Reuses the `unused-dependency` suppress
/// `IssueKind` because there is no dedicated variant for optional deps.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedOptionalDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: UnusedDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
    /// Advisory caveats on the verdict behind this finding. A dependency is
    /// reported unused when NO module in the project imports its specifier,
    /// so a module that parsed with errors can hide the import that would
    /// have credited the package. Sorted, deduplicated, and omitted from the
    /// wire when empty. Never gates the finding, though `fallow fix`
    /// withholds the `remove-dependency` write while a caveat stands.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reachability_caveats: Vec<ReachabilityCaveat>,
}

impl UnusedOptionalDependencyFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(dep: UnusedDependency) -> Self {
        let actions =
            build_unused_dependency_actions(&dep, "optionalDependencies", "unused-dependency");
        Self {
            dep,
            actions,
            introduced: None,
            reachability_caveats: Vec::new(),
        }
    }
}

/// Wire-shape envelope for an [`UnlistedDependency`] finding. Carries an
/// `install-dependency` primary (non-auto-fixable) plus the standard
/// `ignoreDependencies` config suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnlistedDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: UnlistedDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnlistedDependencyFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(dep: UnlistedDependency) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::InstallDependency,
                auto_fixable: false,
                description: "Add this package to dependencies in package.json".to_string(),
                note: Some(
                    "Verify this package should be a direct dependency before adding".to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            build_ignore_dependencies_suppress_action(&dep.package_name, "unlisted-dependency"),
        ];
        Self {
            dep,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`TypeOnlyDependency`] finding. Carries a
/// `move-to-dev` primary plus the standard `ignoreDependencies` config
/// suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TypeOnlyDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: TypeOnlyDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl TypeOnlyDependencyFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(dep: TypeOnlyDependency) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::MoveToDev,
                auto_fixable: false,
                description: "Move to devDependencies (only type imports are used)".to_string(),
                note: Some(
                    "Type imports are erased at runtime so this dependency is not needed in production"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            build_ignore_dependencies_suppress_action(&dep.package_name, "type-only-dependency"),
        ];
        Self {
            dep,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`TestOnlyDependency`] finding. Carries a
/// `move-to-dev` primary (different prose than [`TypeOnlyDependencyFinding`])
/// plus the standard `ignoreDependencies` config suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TestOnlyDependencyFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: TestOnlyDependency,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl TestOnlyDependencyFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(dep: TestOnlyDependency) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::MoveToDev,
                auto_fixable: false,
                description: "Move to devDependencies (only test files import this)".to_string(),
                note: Some(
                    "Only test files import this package so it does not need to be a production dependency"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            build_ignore_dependencies_suppress_action(&dep.package_name, "test-only-dependency"),
        ];
        Self {
            dep,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`DevDependencyInProduction`] finding. Carries a
/// `move-to-prod` primary (the promote-side mirror of
/// [`TestOnlyDependencyFinding`]'s `move-to-dev`) plus the standard
/// `ignoreDependencies` config suppress.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DevDependencyInProductionFinding {
    /// The underlying dead-code entry.
    #[serde(flatten)]
    pub dep: DevDependencyInProduction,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl DevDependencyInProductionFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(dep: DevDependencyInProduction) -> Self {
        let actions = vec![
            IssueAction::Fix(FixAction {
                kind: FixActionType::MoveToProd,
                auto_fixable: false,
                description:
                    "Move to dependencies if the deployment installs them (production code imports this)"
                        .to_string(),
                note: Some(
                    "A production-only install (`pnpm install --prod`) omits devDependencies, so an import resolved at runtime breaks. A build that inlines the package into its output resolves nothing at runtime, and moving it there can instead make the deployment require an install it did not need"
                        .to_string(),
                ),
                available_in_catalogs: None,
                suggested_target: None,
            }),
            build_ignore_dependencies_suppress_action(
                &dep.package_name,
                "dev-dependency-in-production",
            ),
        ];
        Self {
            dep,
            actions,
            introduced: None,
        }
    }
}

// ── Catalog / dep-override family ───────────────────────────────
//
// These six wrappers replace the legacy `inject_actions` post-pass in
// `crates/cli/src/report/json.rs` for the catalog and dependency-override
// findings. Each `with_actions(...)` builds the typed `actions` array
// directly from the inner struct (and any per-call context such as
// `config_fixable`), so the wire shape is identical to the pre-2.76
// post-pass output but the Rust compiler now owns the action contract.

/// Wire-shape envelope for a [`DuplicateExport`] finding. Carries up to
/// three actions in position-locked order: an `add-to-config` `ignoreExports`
/// snippet (only when `locations[]` carries at least one path) followed by
/// the `remove-duplicate` fix and the multi-location suppress.
///
/// The `add-to-config` action sits at position 0 because the documented
/// primary slot points at the safe, non-destructive path: the shadcn /
/// Radix / bits-ui namespace-barrel case where every `index.*` reexports
/// the directory's neighbours. The `remove-duplicate` fix stays as the
/// secondary so consumers that pattern-match on `actions[0].type` for
/// "primary fix" never propose deletion of an intentional barrel surface.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DuplicateExportFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub export: DuplicateExport,
    /// Suggested next steps. Always emitted (possibly empty for
    /// forward-compat).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl DuplicateExportFinding {
    /// Build the wrapper with the `add-to-config` action's `auto_fixable`
    /// defaulting to `false`. The CLI's `build_json_with_config_fixable`
    /// path layers the actual `config_fixable` signal via
    /// [`Self::set_config_fixable`] right before serialization (the
    /// fix-applier readiness check lives in `fallow-cli::fix` and is not
    /// reachable from the analyzer layer where wrappers are first built).
    /// Embedders that build `AnalysisResults` directly and never route
    /// through the CLI's JSON path keep the conservative default.
    #[must_use]
    pub fn with_actions(export: DuplicateExport) -> Self {
        let mut actions: Vec<IssueAction> = Vec::with_capacity(3);

        if let Some(rules) = build_duplicate_exports_ignore_rules(&export) {
            actions.push(IssueAction::AddToConfig(AddToConfigAction {
                kind: AddToConfigKind::AddToConfig,
                auto_fixable: false,
                description: "Add an ignoreExports rule so these files are excluded from duplicate-export grouping (use when this duplication is an intentional namespace-barrel API).".to_string(),
                config_key: "ignoreExports".to_string(),
                value: AddToConfigValue::ExportsRules(rules),
                value_schema: Some(IGNORE_EXPORTS_VALUE_SCHEMA.to_string()),
            }));
        }

        actions.push(IssueAction::Fix(FixAction {
            kind: FixActionType::RemoveDuplicate,
            auto_fixable: false,
            description: "Keep one canonical export location and remove the others".to_string(),
            note: Some(NAMESPACE_BARREL_HINT.to_string()),
            available_in_catalogs: None,
            suggested_target: None,
        }));

        actions.push(IssueAction::SuppressLine(SuppressLineAction {
            kind: SuppressLineKind::SuppressLine,
            auto_fixable: false,
            description: "Suppress with an inline comment above the line".to_string(),
            comment: "// fallow-ignore-next-line duplicate-export".to_string(),
            scope: Some(SuppressLineScope::PerLocation),
        }));

        Self {
            export,
            actions,
            introduced: None,
        }
    }

    /// Update the position-0 `add-to-config` action's `auto_fixable` flag.
    /// Idempotent and a no-op when position 0 is not an `add-to-config`
    /// action (happens when the finding has no locations). Called by the
    /// CLI's JSON serializer with the result of
    /// `crate::fix::is_config_fixable` before emitting bytes.
    pub fn set_config_fixable(&mut self, fixable: bool) {
        if let Some(IssueAction::AddToConfig(action)) = self.actions.first_mut() {
            action.auto_fixable = fixable;
        }
    }
}

/// Build a paste-ready `ignoreExports` config value from a duplicate-export
/// finding's locations. Returns one `{ file, exports: ["*"] }` entry per
/// distinct file in insertion order. `None` when no locations carry a path.
fn build_duplicate_exports_ignore_rules(
    export: &DuplicateExport,
) -> Option<Vec<IgnoreExportsRule>> {
    let mut entries: Vec<IgnoreExportsRule> = Vec::with_capacity(export.locations.len());
    for loc in &export.locations {
        // Normalize separators to forward slashes so pasting the action value
        // into `.fallowrc.json` produces a portable rule. On Windows
        // `to_string_lossy` preserves backslashes, which the old
        // `inject_actions` post-pass implicitly normalized because it read
        // the path AFTER `strip_root_prefix` had already run through
        // `normalize_uri`; the typed wrapper builds the value before
        // serialization, so the normalization has to be explicit here.
        let path = loc.path.to_string_lossy().replace('\\', "/");
        if path.is_empty() {
            continue;
        }
        if entries.iter().any(|existing| existing.file == path) {
            continue;
        }
        entries.push(IgnoreExportsRule {
            file: path,
            exports: vec!["*".to_string()],
        });
    }
    if entries.is_empty() {
        None
    } else {
        Some(entries)
    }
}

/// Wire-shape envelope for an [`UnusedCatalogEntry`] finding. Per-instance
/// `auto_fixable` flips to `false` when `hardcoded_consumers` is non-empty or
/// the source is not `pnpm-workspace.yaml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedCatalogEntryFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub entry: UnusedCatalogEntry,
    /// Suggested next steps. Always emitted.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedCatalogEntryFinding {
    /// Build the wrapper. Per-instance `auto_fixable` is `true` only when
    /// `hardcoded_consumers` is empty and the source is `pnpm-workspace.yaml`;
    /// otherwise `fallow fix` skips the entry to avoid breaking installs or
    /// applying YAML edits to Bun `package.json` catalogs.
    #[must_use]
    pub fn with_actions(entry: UnusedCatalogEntry) -> Self {
        let is_pnpm_source = is_pnpm_catalog_source(&entry.path);
        let auto_fixable = entry.hardcoded_consumers.is_empty() && is_pnpm_source;
        let note = if is_pnpm_source {
            Some(
                "If any consumer declares the same package with a hardcoded version, switch the consumer to `catalog:` before removing"
                    .to_string(),
            )
        } else {
            Some(
                "fallow fix only edits pnpm-workspace.yaml catalog entries. Edit Bun package.json catalogs manually."
                    .to_string(),
            )
        };
        let mut actions = vec![IssueAction::Fix(FixAction {
            kind: FixActionType::RemoveCatalogEntry,
            auto_fixable,
            description: if is_pnpm_source {
                "Remove the entry from pnpm-workspace.yaml".to_string()
            } else {
                "Remove the entry from the catalog source file manually".to_string()
            },
            note,
            available_in_catalogs: None,
            suggested_target: None,
        })];
        if is_pnpm_source {
            actions.push(IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with a YAML comment above the line".to_string(),
                comment: "# fallow-ignore-next-line unused-catalog-entry".to_string(),
                scope: None,
            }));
        }
        Self {
            entry,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for an [`EmptyCatalogGroup`] finding. Carries a
/// `remove-empty-catalog-group` primary. YAML-sourced findings also include a
/// YAML-comment suppress action.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct EmptyCatalogGroupFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub group: EmptyCatalogGroup,
    /// Suggested next steps. Always emitted.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl EmptyCatalogGroupFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(group: EmptyCatalogGroup) -> Self {
        let auto_fixable = is_pnpm_catalog_source(&group.path);
        let mut actions = vec![IssueAction::Fix(FixAction {
            kind: FixActionType::RemoveEmptyCatalogGroup,
            auto_fixable,
            description: if auto_fixable {
                "Remove the empty named catalog group from pnpm-workspace.yaml".to_string()
            } else {
                "Remove the empty named catalog group from the catalog source file manually"
                    .to_string()
            },
            note: Some(if auto_fixable {
                "Only named groups under `catalogs:` are flagged; the top-level `catalog:` hook is intentionally ignored"
                    .to_string()
            } else {
                "fallow fix only edits pnpm-workspace.yaml catalog groups. Edit Bun package.json catalogs manually."
                    .to_string()
            }),
            available_in_catalogs: None,
            suggested_target: None,
        })];
        if auto_fixable {
            actions.push(IssueAction::SuppressLine(SuppressLineAction {
                kind: SuppressLineKind::SuppressLine,
                auto_fixable: false,
                description: "Suppress with a YAML comment above the line".to_string(),
                comment: "# fallow-ignore-next-line empty-catalog-group".to_string(),
                scope: None,
            }));
        }
        Self {
            group,
            actions,
            introduced: None,
        }
    }
}

fn is_pnpm_catalog_source(path: &Path) -> bool {
    path == Path::new(PNPM_WORKSPACE_FILE)
}

/// Wire-shape envelope for an [`UnresolvedCatalogReference`] finding. The
/// primary action at position 0 discriminates on `available_in_catalogs`:
/// `add-catalog-entry` when the array is empty (no other catalog declares
/// the package), or `update-catalog-reference` when at least one
/// alternative exists. When exactly one alternative exists, the action
/// also carries `suggested_target` so deterministic agents can land the
/// edit without picking from a list.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnresolvedCatalogReferenceFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub reference: UnresolvedCatalogReference,
    /// Suggested next steps. Always emitted; position 0 is the discriminated
    /// primary (see struct docs).
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnresolvedCatalogReferenceFinding {
    /// Build the wrapper. The discriminator at position 0 is the
    /// `add-catalog-entry` vs `update-catalog-reference` pick documented on
    /// the struct.
    #[must_use]
    pub fn with_actions(reference: UnresolvedCatalogReference) -> Self {
        // Normalize separators to forward slashes so the
        // `ignoreCatalogReferences.consumer` action value is portable when
        // pasted into a Windows-authored config. See
        // `build_duplicate_exports_ignore_rules` for the same pattern.
        let consumer_path = reference.path.to_string_lossy().replace('\\', "/");
        let primary = catalog_reference_primary_action(&reference);
        let fallback = remove_catalog_reference_action();
        let suppress = suppress_catalog_reference_action(&reference, consumer_path);

        Self {
            reference,
            actions: vec![primary, fallback, suppress],
            introduced: None,
        }
    }
}

fn catalog_reference_primary_action(reference: &UnresolvedCatalogReference) -> IssueAction {
    if reference.available_in_catalogs.is_empty() {
        return IssueAction::Fix(FixAction {
            kind: FixActionType::AddCatalogEntry,
            auto_fixable: false,
            description: format!(
                "Add `{}` to the `{}` catalog in pnpm-workspace.yaml",
                reference.entry_name, reference.catalog_name
            ),
            note: Some(
                "Pin a version that satisfies the consumer's import; no other catalog declares this package today"
                    .to_string(),
            ),
            available_in_catalogs: None,
            suggested_target: None,
        });
    }

    let available = reference.available_in_catalogs.clone();
    let suggested_target = (available.len() == 1).then(|| available[0].clone());
    IssueAction::Fix(FixAction {
        kind: FixActionType::UpdateCatalogReference,
        auto_fixable: false,
        description: format!(
            "Switch the reference from `catalog:{}` to a catalog that declares `{}`",
            reference.catalog_name, reference.entry_name
        ),
        note: None,
        available_in_catalogs: Some(available),
        suggested_target,
    })
}

fn remove_catalog_reference_action() -> IssueAction {
    IssueAction::Fix(FixAction {
        kind: FixActionType::RemoveCatalogReference,
        auto_fixable: false,
        description: "Remove the catalog reference and pin a hardcoded version in package.json"
            .to_string(),
        note: Some(
            "Use only when neither another catalog declares the package nor the named catalog should grow to include it"
                .to_string(),
        ),
        available_in_catalogs: None,
        suggested_target: None,
    })
}

fn suppress_catalog_reference_action(
    reference: &UnresolvedCatalogReference,
    consumer_path: String,
) -> IssueAction {
    let mut suppress_value = serde_json::Map::new();
    suppress_value.insert(
        "package".to_string(),
        serde_json::Value::String(reference.entry_name.clone()),
    );
    suppress_value.insert(
        "catalog".to_string(),
        serde_json::Value::String(reference.catalog_name.clone()),
    );
    suppress_value.insert(
        "consumer".to_string(),
        serde_json::Value::String(consumer_path),
    );
    IssueAction::AddToConfig(AddToConfigAction {
        kind: AddToConfigKind::AddToConfig,
        auto_fixable: false,
        description: "Suppress this reference via ignoreCatalogReferences in fallow config (use when the catalog edit is intentionally landing in a separate PR or the package is a placeholder).".to_string(),
        config_key: "ignoreCatalogReferences".to_string(),
        value: AddToConfigValue::RuleObject(suppress_value),
        value_schema: Some(IGNORE_CATALOG_REFERENCES_VALUE_SCHEMA.to_string()),
    })
}

/// Wire-shape envelope for an [`UnusedDependencyOverride`] finding. Carries
/// a `remove-dependency-override` primary plus an `add-to-config`
/// `ignoreDependencyOverrides` suppress scoped to the target package and
/// declaration source.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnusedDependencyOverrideFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub entry: UnusedDependencyOverride,
    /// Suggested next steps. Always emitted.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl UnusedDependencyOverrideFinding {
    /// Build the wrapper.
    #[must_use]
    pub fn with_actions(entry: UnusedDependencyOverride) -> Self {
        let mut actions: Vec<IssueAction> = Vec::with_capacity(2);
        actions.push(IssueAction::Fix(FixAction {
            kind: FixActionType::RemoveDependencyOverride,
            auto_fixable: false,
            description: "Remove the package-manager override entry from its declaration source"
                .to_string(),
            note: Some(
                "Conservative static check; verify against the active package manager's frozen-lockfile install before removing in case the override targets a transitive dependency (CVE-fix pattern)"
                    .to_string(),
            ),
            available_in_catalogs: None,
            suggested_target: None,
        }));

        if let Some(suppress) = build_ignore_dependency_overrides_suppress(
            Some(&entry.target_package),
            &entry.raw_key,
            entry.source,
        ) {
            actions.push(suppress);
        }

        Self {
            entry,
            actions,
            introduced: None,
        }
    }
}

/// Wire-shape envelope for a [`MisconfiguredDependencyOverride`] finding.
/// Carries a `fix-dependency-override` primary plus the conditional
/// `add-to-config` `ignoreDependencyOverrides` suppress (skipped when both
/// `target_package` and `raw_key` are empty, since the rule matcher keys on
/// a non-empty package name).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct MisconfiguredDependencyOverrideFinding {
    /// The underlying finding.
    #[serde(flatten)]
    pub entry: MisconfiguredDependencyOverride,
    /// Suggested next steps. Always emitted.
    pub actions: Vec<IssueAction>,
    /// Set by the audit pass when this finding is introduced relative to
    /// the merge-base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub introduced: Option<AuditIntroduced>,
}

impl MisconfiguredDependencyOverrideFinding {
    /// Build the wrapper. The suppress action is omitted when neither
    /// `target_package` (set on `EmptyValue` cases) nor `raw_key` provides a
    /// non-empty package name; an `ignoreDependencyOverrides` entry with
    /// `package: ""` would be silently ignored by the config parser.
    #[must_use]
    pub fn with_actions(entry: MisconfiguredDependencyOverride) -> Self {
        let mut actions: Vec<IssueAction> = Vec::with_capacity(2);
        actions.push(IssueAction::Fix(FixAction {
            kind: FixActionType::FixDependencyOverride,
            auto_fixable: false,
            description:
                "Fix the package-manager override key or value: invalid entries are rejected or ignored"
                    .to_string(),
            note: Some(
                "Common shapes: bare `pkg`, scoped `@scope/pkg`, version-selector `pkg@<2`, parent-chain `parent>child`. Valid values include semver ranges, `-` (removal), `$ref` (self-ref), and `npm:alias@^1`."
                    .to_string(),
            ),
            available_in_catalogs: None,
            suggested_target: None,
        }));

        if let Some(suppress) = build_ignore_dependency_overrides_suppress(
            entry.target_package.as_deref(),
            &entry.raw_key,
            entry.source,
        ) {
            actions.push(suppress);
        }

        Self {
            entry,
            actions,
            introduced: None,
        }
    }
}

/// Shared `add-to-config` `ignoreDependencyOverrides` builder for the two
/// override findings. Returns `None` when no non-empty package name is
/// available; the config parser silently drops entries with an empty
/// `package` field, so emitting one would be a no-op that misleads agents.
fn build_ignore_dependency_overrides_suppress(
    target_package: Option<&str>,
    raw_key: &str,
    source: DependencyOverrideSource,
) -> Option<IssueAction> {
    let package = target_package
        .filter(|s| !s.is_empty())
        .or_else(|| Some(raw_key).filter(|s| !s.is_empty()))?
        .to_string();
    let mut value = serde_json::Map::new();
    value.insert("package".to_string(), serde_json::Value::String(package));
    value.insert(
        "source".to_string(),
        serde_json::Value::String(source.as_label().to_string()),
    );
    Some(IssueAction::AddToConfig(AddToConfigAction {
        kind: AddToConfigKind::AddToConfig,
        auto_fixable: false,
        description: "Suppress this override finding via ignoreDependencyOverrides in fallow config (use for CVE-fix overrides that target a purely-transitive package).".to_string(),
        config_key: "ignoreDependencyOverrides".to_string(),
        value: AddToConfigValue::RuleObject(value),
        value_schema: Some(IGNORE_DEPENDENCY_OVERRIDES_VALUE_SCHEMA.to_string()),
    }))
}

// ── The mutation gate, registered once ──────────────────────────
//
// Every finding whose reachability verdict a lost import edge can distort.
// The analysis layer stamps caveats through `set_reachability_caveats`, which
// enforces the gate on the finding's actions in the same call; every mutation
// surface reads the answer back through `may_auto_apply_mutation`.
impl_caveated_finding!(
    UnusedFileFinding,
    UnusedExportFinding,
    UnusedTypeFinding,
    UnusedEnumMemberFinding,
    UnusedClassMemberFinding,
    UnusedStoreMemberFinding,
    UnusedDependencyFinding,
    UnusedDevDependencyFinding,
    UnusedOptionalDependencyFinding,
);

// ── Position-0 invariant golden tests ───────────────────────────
//
// These tests document the load-bearing position-0 semantics that flow
// downstream into the GitHub Action / GitLab CI jq scripts, the MCP server
// `actions[0].type` pattern-match, and the VS Code LSP code-action
// rendering. Snapshot tests assert structural equality; these named tests
// document WHY position 0 has a specific value, so a future refactor that
// re-orders actions tells you what broke instead of just "the snapshot
// changed".
#[cfg(test)]
mod caveat_tokens {
    use super::*;

    /// The token-side helpers must render the same words as the typed ones, so
    /// one finding reads identically whether a surface holds the findings or
    /// re-reads them off a serialized envelope.
    #[test]
    fn token_labels_match_the_typed_labels() {
        let typed = [
            ReachabilityCaveat::IncompleteFileAnalysis,
            ReachabilityCaveat::IncompleteImportGraph,
        ];
        let tokens: Vec<&str> = typed.iter().map(|c| c.token()).collect();

        assert_eq!(
            caveat_labels_for_tokens(tokens.iter().copied()),
            caveat_labels(&typed)
        );
        assert_eq!(
            caveat_suffix_for_tokens(tokens.iter().copied()),
            caveat_suffix(&typed)
        );
    }

    #[test]
    fn no_tokens_means_nothing_to_say() {
        assert_eq!(caveat_labels_for_tokens(std::iter::empty()), None);
        assert_eq!(caveat_suffix_for_tokens(std::iter::empty()), None);
    }

    /// The CI review formats can only see the rendered description, so the
    /// recogniser and the renderer have to stay one pair. A description with
    /// no caveat must not match, or the review formats would withhold the
    /// suggestion block on every finding in a clean run.
    #[test]
    fn a_rendered_suffix_is_recognised_by_the_marker() {
        for caveats in [
            &[ReachabilityCaveat::IncompleteImportGraph][..],
            &[
                ReachabilityCaveat::IncompleteFileAnalysis,
                ReachabilityCaveat::IncompleteImportGraph,
            ][..],
        ] {
            let suffix = caveat_suffix(caveats).expect("a caveat renders a suffix");
            assert!(
                description_carries_caveat(&format!("Something is never referenced{suffix}")),
                "the marker must match what caveat_suffix writes: {suffix}"
            );
        }
        assert!(
            description_carries_caveat(&format!(
                "Something is never referenced{}",
                caveat_suffix_for_tokens(["some-future-cause"]).expect("token suffix")
            )),
            "the token-side renderer writes the same marker"
        );
        assert!(
            !description_carries_caveat("Class member 'Widget.helper' is never referenced"),
            "a clean description must not read as caveated"
        );
    }

    /// A caveat is a RUN-level condition covering several ways a file goes
    /// unread: a degraded parse, an unreadable file, and three kinds of file
    /// discovery skipped before opening. A message naming only the parse case
    /// told a reader whose run was degraded by the size guard to go fix parse
    /// errors that do not exist, which is the same overclaiming the caveat
    /// itself exists to prevent.
    #[test]
    fn no_caveat_message_names_a_single_cause() {
        for caveat in [
            ReachabilityCaveat::IncompleteFileAnalysis,
            ReachabilityCaveat::IncompleteImportGraph,
        ] {
            let message = caveat.message();
            assert!(
                !message.contains("parse cleanly") && !message.contains("parse error"),
                "{} names the parse cause alone, but a size-skipped or unreadable \
                 file reaches the same caveat: {message}",
                caveat.token()
            );
            assert!(
                message.contains("workspace_diagnostics"),
                "{} must point at the list that names the actual files: {message}",
                caveat.token()
            );
        }
    }

    /// The value set is open. A token a consumer build does not recognise still
    /// means the evidence is incomplete, so it must survive into the rendered
    /// hedge rather than being dropped back into a confident-looking finding.
    #[test]
    fn an_unrecognised_token_still_renders_as_a_caveat() {
        let suffix = caveat_suffix_for_tokens(["some-future-cause"])
            .expect("an unknown token is still a caveat");

        assert_eq!(suffix, " (caveat: some future cause)");
    }
}

/// The gate, pinned as one property across every finding type rather than as
/// one test per mutation surface.
///
/// Three separate reviewers found three separate mutation paths that had never
/// learned about the caveat, because each earlier round fixed the door it
/// found. These tests assert the invariant itself: for every dead-code finding
/// that can carry a caveat, a caveated finding exposes NO auto-fixable action,
/// and an uncaveated one is untouched. Adding a caveated finding type without
/// registering it in `impl_caveated_finding!` fails to compile at the
/// `set_reachability_caveats` call the annotation pass makes; adding one that
/// exposes an auto-fixable mutation and never gets annotated is what
/// `every_auto_fixable_dead_code_mutation_is_gated` catches.
#[cfg(test)]
mod mutation_gate {
    use super::*;
    use crate::extract::MemberKind;
    use crate::results::DependencyLocation;
    use std::path::PathBuf;

    const BOTH: [ReachabilityCaveat; 2] = [
        ReachabilityCaveat::IncompleteFileAnalysis,
        ReachabilityCaveat::IncompleteImportGraph,
    ];

    fn export(name: &str) -> UnusedExport {
        UnusedExport {
            path: PathBuf::from("/p/src/mod.ts"),
            export_name: name.to_string(),
            is_type_only: false,
            line: 1,
            col: 0,
            span_start: 0,
            is_re_export: false,
        }
    }

    fn member(name: &str) -> UnusedMember {
        UnusedMember {
            path: PathBuf::from("/p/src/mod.ts"),
            parent_name: "Color".to_string(),
            member_name: name.to_string(),
            kind: MemberKind::EnumMember,
            line: 2,
            col: 2,
        }
    }

    fn class_member(name: &str) -> UnusedMember {
        UnusedMember {
            parent_name: "Widget".to_string(),
            kind: MemberKind::ClassMethod,
            ..member(name)
        }
    }

    fn store_member(name: &str) -> UnusedMember {
        UnusedMember {
            parent_name: "useCounterStore".to_string(),
            kind: MemberKind::StoreMember,
            ..member(name)
        }
    }

    fn dependency(name: &str) -> UnusedDependency {
        UnusedDependency {
            package_name: name.to_string(),
            location: DependencyLocation::Dependencies,
            path: PathBuf::from("/p/package.json"),
            line: 5,
            used_in_workspaces: Vec::new(),
        }
    }

    /// One finding type: its name, the uncaveated finding, and the same
    /// finding after the annotation pass stamped a caveat on it.
    type GatedPair = (&'static str, Box<dyn Gated>, Box<dyn Gated>);

    /// Every caveated finding type, boxed behind the one question the mutation
    /// surfaces ask.
    fn every_finding_type() -> Vec<GatedPair> {
        fn pair<T: Gated + Clone + 'static>(name: &'static str, clean: T) -> GatedPair {
            let mut caveated = clean.clone();
            caveated.stamp(BOTH.to_vec());
            (name, Box::new(clean), Box::new(caveated))
        }
        vec![
            pair(
                "unused_files",
                UnusedFileFinding::with_actions(UnusedFile {
                    path: PathBuf::from("/p/src/orphan.ts"),
                }),
            ),
            pair(
                "unused_exports",
                UnusedExportFinding::with_actions(export("helper")),
            ),
            pair(
                "unused_types",
                UnusedTypeFinding::with_actions(export("Shape")),
            ),
            pair(
                "unused_enum_members",
                UnusedEnumMemberFinding::with_actions(member("Blue")),
            ),
            pair(
                "unused_class_members",
                UnusedClassMemberFinding::with_actions(class_member("legacyMethod")),
            ),
            pair(
                "unused_store_members",
                UnusedStoreMemberFinding::with_actions(store_member("onlyUsedInBigFile")),
            ),
            pair(
                "unused_dependencies",
                UnusedDependencyFinding::with_actions(dependency("lodash")),
            ),
            pair(
                "unused_dev_dependencies",
                UnusedDevDependencyFinding::with_actions(dependency("vitest")),
            ),
            pair(
                "unused_optional_dependencies",
                UnusedOptionalDependencyFinding::with_actions(dependency("fsevents")),
            ),
        ]
    }

    /// Erases the finding type down to what a mutation surface needs: the gate,
    /// the actions it gates, and the annotation-pass write.
    trait Gated {
        fn actions(&self) -> &[IssueAction];
        fn gate_allows_mutation(&self) -> bool;
        fn stamp(&mut self, caveats: Vec<ReachabilityCaveat>);
    }

    impl<T: MutationEvidence + CaveatedFinding + HasActions> Gated for T {
        fn actions(&self) -> &[IssueAction] {
            HasActions::actions(self)
        }
        fn gate_allows_mutation(&self) -> bool {
            self.may_auto_apply_mutation()
        }
        fn stamp(&mut self, caveats: Vec<ReachabilityCaveat>) {
            self.set_reachability_caveats(caveats);
        }
    }

    trait HasActions {
        fn actions(&self) -> &[IssueAction];
    }

    macro_rules! has_actions {
        ($($ty:ty),+ $(,)?) => { $( impl HasActions for $ty {
            fn actions(&self) -> &[IssueAction] { &self.actions }
        } )+ };
    }
    has_actions!(
        UnusedFileFinding,
        UnusedExportFinding,
        UnusedTypeFinding,
        UnusedEnumMemberFinding,
        UnusedClassMemberFinding,
        UnusedStoreMemberFinding,
        UnusedDependencyFinding,
        UnusedDevDependencyFinding,
        UnusedOptionalDependencyFinding,
    );

    /// THE property. Not "the CLI withholds it" or "the LSP hides it": no
    /// finding whose evidence the run itself flagged may advertise an
    /// automatically applicable mutation, whichever surface is reading.
    #[test]
    fn every_auto_fixable_dead_code_mutation_is_gated() {
        for (name, _clean, caveated) in every_finding_type() {
            assert!(
                !caveated.gate_allows_mutation(),
                "{name}: a stamped finding must fail the gate"
            );
            for action in caveated.actions() {
                assert!(
                    !action.is_auto_fixable(),
                    "{name}: a caveated finding still advertises an auto-fixable action, so an \
                     agent following the documented actions contract would plan a removal \
                     `fallow fix` refuses"
                );
            }
        }
    }

    /// The other half, and the one a blunt fix breaks: the gate must not turn
    /// every finding into a manual one. A run that read every file it
    /// discovered keeps exactly the behavior it had.
    #[test]
    fn an_uncaveated_finding_keeps_its_auto_fix() {
        let auto_fixable_types = [
            "unused_exports",
            "unused_types",
            "unused_enum_members",
            "unused_dependencies",
            "unused_dev_dependencies",
            "unused_optional_dependencies",
        ];
        for (name, clean, _caveated) in every_finding_type() {
            assert!(
                clean.gate_allows_mutation(),
                "{name}: a finding with no caveat must pass the gate"
            );
            if auto_fixable_types.contains(&name) {
                assert!(
                    clean.actions().iter().any(IssueAction::is_auto_fixable),
                    "{name}: the gate must not withhold a mutation the run has the evidence for"
                );
            }
        }
    }

    /// The caveat is advisory about the FINDING and decisive only about the
    /// MUTATION: the actions array keeps its shape so a consumer reading
    /// `actions[0].type` is unaffected, and the suppress alternative stays.
    #[test]
    fn the_gate_downgrades_a_mutation_without_removing_it() {
        let clean = UnusedExportFinding::with_actions(export("helper"));
        let mut caveated = clean.clone();
        caveated.set_reachability_caveats(BOTH.to_vec());

        assert_eq!(caveated.actions.len(), clean.actions.len());
        let IssueAction::Fix(fix) = &caveated.actions[0] else {
            panic!("position 0 stays the fix action");
        };
        assert!(!fix.auto_fixable);
        assert_eq!(
            fix.note.as_deref(),
            Some(INCOMPLETE_EVIDENCE_NOTE),
            "the withheld action says why in its own note, not only in a sibling array"
        );
    }

    /// A pre-existing note is context the user still needs (the re-export
    /// warning names a public-API risk the caveat says nothing about), so the
    /// gate appends rather than overwrites.
    #[test]
    fn a_gated_mutation_keeps_the_note_it_already_had() {
        let mut re_export = export("helper");
        re_export.is_re_export = true;
        let mut finding = UnusedExportFinding::with_actions(re_export);
        finding.set_reachability_caveats(vec![ReachabilityCaveat::IncompleteImportGraph]);

        let IssueAction::Fix(fix) = &finding.actions[0] else {
            panic!("position 0 stays the fix action");
        };
        let note = fix.note.as_deref().expect("note present");
        assert!(note.contains("public API"), "the original note survives");
        assert!(
            note.contains("Evidence is incomplete"),
            "the caveat is added"
        );
    }

    /// The gate is complete only if every finding type that can ever expose an
    /// auto-fixable mutation is in it. The one member type deliberately left
    /// out is safe for a different reason, and this pins that reason rather
    /// than trusting a comment: a store member exposes no fix action at all,
    /// because reflective access via a Pinia plugin or `$onAction` is
    /// invisible to syntactic analysis, so no evidence this run could gather
    /// would open the removal. If it ever ships one, it needs
    /// `reachability_caveats` and a row in `impl_caveated_finding!` first.
    ///
    /// A class member used to sit here on the weaker argument that its removal
    /// STARTS withheld. That argument covered only the syntactic finding: the
    /// type-aware sidecar reopens the removal through
    /// [`UnusedClassMemberFinding::set_semantic_decision`], and the review
    /// formats rendered a one-click commit for it regardless of
    /// `auto_fixable`. It is inside the gate now, so the assertion here is
    /// only that the SYNTACTIC finding still ships no auto-fix; the reopening
    /// path is pinned by `a_complete_semantic_verdict_cannot_reopen_a_
    /// caveated_class_member`.
    #[test]
    fn a_store_member_exposes_no_mutation_at_all() {
        let store = UnusedStoreMemberFinding::with_actions(member("total"));
        assert!(
            !store.actions.iter().any(IssueAction::is_auto_fixable),
            "a store member must expose no automatically applicable mutation"
        );
        assert!(
            !store
                .actions
                .iter()
                .any(|action| matches!(action, IssueAction::Fix(_))),
            "and no fix action at all"
        );

        let class = UnusedClassMemberFinding::with_actions(class_member("helper"));
        assert!(
            !class.actions.iter().any(IssueAction::is_auto_fixable),
            "a class member's syntactic removal stays withheld until semantic evidence opens it"
        );
    }

    /// The semantic pass runs after the annotation pass and is the only code
    /// path that RAISES `auto_fixable`. A `Complete` verdict must not re-open a
    /// mutation the incomplete run already withheld.
    #[test]
    fn a_complete_semantic_verdict_cannot_reopen_a_caveated_mutation() {
        use crate::semantic::{
            SemanticCandidateDecision, SemanticCandidateDecisionKind, SemanticCompleteness,
            SemanticNamespace, SemanticSymbol,
        };

        let complete_negative = || SemanticCandidateDecision {
            query_id: 0,
            subject: SemanticSymbol {
                path: PathBuf::from("/p/src/mod.ts"),
                namespace: SemanticNamespace::Value,
                declaration_kind: "function".to_string(),
                exported_name: "helper".to_string(),
                local_name: "helper".to_string(),
                owner: None,
                line: 1,
                col: 0,
            },
            decision: SemanticCandidateDecisionKind::ConfirmedNoStaticReferences,
            status: SemanticCompleteness::Complete,
            owning_projects: Vec::new(),
            evidence: Vec::new(),
            contract: None,
            framework_contract: None,
            closed_world_eligible: false,
            edit_guard: None,
            reason_code: None,
            explanation: String::new(),
            actions: Vec::new(),
            total_evidence_count: 0,
            truncated: false,
            omissions: Vec::new(),
        };

        let mut clean = UnusedExportFinding::with_actions(export("helper"));
        clean.set_semantic_decision(complete_negative());
        assert!(
            clean.actions.iter().any(IssueAction::is_auto_fixable),
            "a complete negative verdict on a clean run still enables the fix"
        );

        let mut caveated = UnusedExportFinding::with_actions(export("helper"));
        caveated.set_reachability_caveats(vec![ReachabilityCaveat::IncompleteImportGraph]);
        caveated.set_semantic_decision(complete_negative());
        assert!(
            !caveated.actions.iter().any(IssueAction::is_auto_fixable),
            "the semantic pass must ask the gate too"
        );
    }

    /// The class-member twin, on its own eligibility flag. `closed_world_
    /// eligible` is proved over the program the sidecar could see, which is
    /// the program this run parsed; a member whose only call site sits in a
    /// file the run never opened is absent from that world for the same reason
    /// it is absent from the syntactic verdict, so a `true` here is not
    /// evidence the run lacks.
    #[test]
    fn a_complete_semantic_verdict_cannot_reopen_a_caveated_class_member() {
        use crate::semantic::{
            SemanticCandidateDecision, SemanticCandidateDecisionKind, SemanticCompleteness,
            SemanticNamespace, SemanticSymbol,
        };

        let eligible = || SemanticCandidateDecision {
            query_id: 0,
            subject: SemanticSymbol {
                path: PathBuf::from("/p/src/mod.ts"),
                namespace: SemanticNamespace::Value,
                declaration_kind: "method".to_string(),
                exported_name: "Widget".to_string(),
                local_name: "legacyMethod".to_string(),
                owner: Some("Widget".to_string()),
                line: 2,
                col: 2,
            },
            decision: SemanticCandidateDecisionKind::ConfirmedNoStaticReferences,
            status: SemanticCompleteness::Complete,
            owning_projects: Vec::new(),
            evidence: Vec::new(),
            contract: None,
            framework_contract: None,
            closed_world_eligible: true,
            edit_guard: None,
            reason_code: None,
            explanation: "closed world proved".to_string(),
            actions: Vec::new(),
            total_evidence_count: 0,
            truncated: false,
            omissions: Vec::new(),
        };

        let mut clean = UnusedClassMemberFinding::with_actions(class_member("legacyMethod"));
        clean.set_semantic_decision(eligible());
        assert!(
            clean.actions.iter().any(IssueAction::is_auto_fixable),
            "a closed-world verdict on a run that read every file still opens the removal"
        );

        let mut caveated = UnusedClassMemberFinding::with_actions(class_member("legacyMethod"));
        caveated.set_reachability_caveats(vec![ReachabilityCaveat::IncompleteImportGraph]);
        caveated.set_semantic_decision(eligible());
        assert!(
            !caveated.actions.iter().any(IssueAction::is_auto_fixable),
            "the class-member semantic pass must ask the gate too"
        );
        let IssueAction::Fix(fix) = &caveated.actions[0] else {
            panic!("position 0 stays the fix action");
        };
        assert_eq!(
            fix.note.as_deref(),
            Some(INCOMPLETE_EVIDENCE_NOTE),
            "the withheld action says why, rather than repeating a closed-world explanation \
             computed over a program the run did not fully read"
        );
    }
}

#[cfg(test)]
mod position_0_invariants {
    use super::*;
    use crate::output::FixActionType;
    use crate::results::{DependencyOverrideSource, DuplicateLocation};
    use std::path::PathBuf;

    /// Helper: extract the kebab-case `type` discriminant from an
    /// [`IssueAction`] at a specific position. Returns `None` when the
    /// position is out of bounds or the action shape lacks a discriminant
    /// (today every variant has one).
    fn action_type(action: &IssueAction) -> &'static str {
        match action {
            IssueAction::Fix(fix) => match fix.kind {
                FixActionType::RemoveExport => "remove-export",
                FixActionType::DeleteFile => "delete-file",
                FixActionType::RemoveDependency => "remove-dependency",
                FixActionType::MoveDependency => "move-dependency",
                FixActionType::RemoveEnumMember => "remove-enum-member",
                FixActionType::RemoveClassMember => "remove-class-member",
                FixActionType::ResolveImport => "resolve-import",
                FixActionType::InstallDependency => "install-dependency",
                FixActionType::RemoveDuplicate => "remove-duplicate",
                FixActionType::MoveToDev => "move-to-dev",
                FixActionType::MoveToProd => "move-to-prod",
                FixActionType::RefactorCycle => "refactor-cycle",
                FixActionType::RefactorReExportCycle => "refactor-re-export-cycle",
                FixActionType::RefactorBoundary => "refactor-boundary",
                FixActionType::ExportType => "export-type",
                FixActionType::RemoveCatalogEntry => "remove-catalog-entry",
                FixActionType::RemoveEmptyCatalogGroup => "remove-empty-catalog-group",
                FixActionType::UpdateCatalogReference => "update-catalog-reference",
                FixActionType::AddCatalogEntry => "add-catalog-entry",
                FixActionType::RemoveCatalogReference => "remove-catalog-reference",
                FixActionType::RemoveDependencyOverride => "remove-dependency-override",
                FixActionType::FixDependencyOverride => "fix-dependency-override",
                FixActionType::ResolvePolicyViolation => "resolve-policy-violation",
                FixActionType::MoveToServerModule => "move-to-server-module",
                FixActionType::SplitMixedBarrel => "split-mixed-barrel",
                FixActionType::HoistDirective => "hoist-directive",
                FixActionType::WireServerAction => "wire-server-action",
                FixActionType::ProvideInject => "provide-inject",
                FixActionType::UseLoadData => "use-load-data",
                FixActionType::RenderComponent => "render-component",
                FixActionType::UseComponentProp => "use-component-prop",
                FixActionType::EmitComponentEvent => "emit-component-event",
                FixActionType::WireSvelteEvent => "wire-svelte-event",
                FixActionType::ResolveRouteCollision => "resolve-route-collision",
                FixActionType::ResolveDynamicSegmentNameConflict => {
                    "resolve-dynamic-segment-name-conflict"
                }
                FixActionType::AddSuppressionReason => "add-suppression-reason",
                FixActionType::RemoveStaleSuppression => "remove-stale-suppression",
            },
            IssueAction::SuppressLine(_) => "suppress-line",
            IssueAction::SuppressFile(_) => "suppress-file",
            IssueAction::AddToConfig(_) => "add-to-config",
        }
    }

    fn assert_manual_fix_then_suppress(
        actions: &[IssueAction],
        primary_type: &str,
        suppress_comment: &str,
    ) {
        assert_eq!(actions.len(), 2);
        assert_eq!(action_type(&actions[0]), primary_type);
        let IssueAction::Fix(primary) = &actions[0] else {
            panic!("position-0 should be a manual fix action");
        };
        assert!(!primary.auto_fixable);
        assert!(primary.note.is_some());
        assert_eq!(action_type(&actions[1]), "suppress-line");
        let IssueAction::SuppressLine(suppress) = &actions[1] else {
            panic!("position-1 should be a suppress-line action");
        };
        assert_eq!(suppress.comment, suppress_comment);
    }

    #[test]
    fn pnpm_catalog_entry_action_is_auto_fixable() {
        let finding = UnusedCatalogEntryFinding::with_actions(UnusedCatalogEntry {
            entry_name: "unused".to_string(),
            catalog_name: "default".to_string(),
            path: PathBuf::from("pnpm-workspace.yaml"),
            line: 3,
            hardcoded_consumers: vec![],
        });

        let IssueAction::Fix(fix) = &finding.actions[0] else {
            panic!("position-0 should be a fix action");
        };
        assert!(fix.auto_fixable);
        assert_eq!(finding.actions.len(), 2);
        assert_eq!(action_type(&finding.actions[1]), "suppress-line");
    }

    #[test]
    fn bun_package_json_catalog_entry_action_is_manual_only() {
        let finding = UnusedCatalogEntryFinding::with_actions(UnusedCatalogEntry {
            entry_name: "unused".to_string(),
            catalog_name: "default".to_string(),
            path: PathBuf::from("package.json"),
            line: 4,
            hardcoded_consumers: vec![],
        });

        let IssueAction::Fix(fix) = &finding.actions[0] else {
            panic!("position-0 should be a fix action");
        };
        assert!(!fix.auto_fixable);
        assert!(fix.description.contains("manually"));
        assert_eq!(finding.actions.len(), 1);
    }

    #[test]
    fn bun_package_json_empty_catalog_group_action_is_manual_only() {
        let finding = EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
            catalog_name: "empty".to_string(),
            path: PathBuf::from("package.json"),
            line: 4,
        });

        let IssueAction::Fix(fix) = &finding.actions[0] else {
            panic!("position-0 should be a fix action");
        };
        assert!(!fix.auto_fixable);
        assert!(fix.description.contains("manually"));
        assert_eq!(finding.actions.len(), 1);
    }

    #[test]
    fn unprovided_inject_primary_action_is_provide_inject() {
        let finding = UnprovidedInjectFinding::with_actions(UnprovidedInject {
            path: PathBuf::from("src/context.ts"),
            key_name: "userKey".to_string(),
            framework: "svelte".to_string(),
            line: 7,
            col: 12,
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "provide-inject",
            "// fallow-ignore-next-line unprovided-inject",
        );
    }

    #[test]
    fn unused_server_action_primary_action_is_wire_server_action() {
        let finding = UnusedServerActionFinding::with_actions(UnusedServerAction {
            path: PathBuf::from("app/actions.ts"),
            action_name: "saveDraft".to_string(),
            line: 3,
            col: 13,
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "wire-server-action",
            "// fallow-ignore-next-line unused-server-action",
        );
    }

    #[test]
    fn unused_load_data_key_primary_action_is_use_load_data() {
        let finding = UnusedLoadDataKeyFinding::with_actions(UnusedLoadDataKey {
            path: PathBuf::from("src/routes/+page.server.ts"),
            key_name: "profile".to_string(),
            line: 12,
            col: 6,
            route_dir: Some("src/routes".to_string()),
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "use-load-data",
            "// fallow-ignore-next-line unused-load-data-key",
        );
    }

    #[test]
    fn unrendered_component_primary_action_is_render_component() {
        let finding = UnrenderedComponentFinding::with_actions(UnrenderedComponent {
            path: PathBuf::from("src/components/EmptyState.vue"),
            component_name: "EmptyState".to_string(),
            framework: "vue".to_string(),
            reachable_via: None,
            line: 1,
            col: 0,
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "render-component",
            "// fallow-ignore-next-line unrendered-component",
        );
    }

    #[test]
    fn unused_component_prop_primary_action_is_use_component_prop() {
        let finding = UnusedComponentPropFinding::with_actions(UnusedComponentProp {
            path: PathBuf::from("src/components/Card.vue"),
            component_name: "Card".to_string(),
            prop_name: "variant".to_string(),
            line: 5,
            col: 10,
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "use-component-prop",
            "// fallow-ignore-next-line unused-component-prop",
        );
    }

    #[test]
    fn unused_component_emit_primary_action_is_emit_component_event() {
        let finding = UnusedComponentEmitFinding::with_actions(UnusedComponentEmit {
            path: PathBuf::from("src/components/Picker.vue"),
            component_name: "Picker".to_string(),
            emit_name: "focus".to_string(),
            line: 6,
            col: 14,
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "emit-component-event",
            "// fallow-ignore-next-line unused-component-emit",
        );
    }

    #[test]
    fn unused_svelte_event_primary_action_is_wire_svelte_event() {
        let finding = UnusedSvelteEventFinding::with_actions(UnusedSvelteEvent {
            path: PathBuf::from("src/Dialog.svelte"),
            component_name: "Dialog".to_string(),
            event_name: "closed".to_string(),
            line: 19,
            col: 8,
        });

        assert_manual_fix_then_suppress(
            &finding.actions,
            "wire-svelte-event",
            "// fallow-ignore-next-line unused-svelte-event",
        );
    }

    #[test]
    fn unresolved_import_actions_include_ignore_unresolved_imports_config_suppress() {
        let inner = UnresolvedImport {
            specifier: "@example/icons".to_string(),
            path: PathBuf::from("src/index.ts"),
            line: 4,
            col: 12,
            specifier_col: 18,
        };
        let finding = UnresolvedImportFinding::with_actions(inner);

        assert_eq!(action_type(&finding.actions[0]), "resolve-import");
        assert_eq!(action_type(&finding.actions[1]), "add-to-config");
        let IssueAction::AddToConfig(action) = &finding.actions[1] else {
            panic!("position-1 should be AddToConfig");
        };
        assert!(!action.auto_fixable);
        assert_eq!(action.config_key, "ignoreUnresolvedImports");
        let AddToConfigValue::Scalar(value) = &action.value else {
            panic!("ignoreUnresolvedImports action should carry a scalar value");
        };
        assert_eq!(value, "@example/icons");
        assert_eq!(
            action.value_schema.as_deref(),
            Some(
                "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json#/properties/ignoreUnresolvedImports/items"
            )
        );
    }

    /// Invariant: when no other catalog declares the package, position 0
    /// of `unresolved_catalog_references[].actions` is `add-catalog-entry`,
    /// directing the agent to grow the targeted catalog.
    ///
    /// Downstream consumers (MCP `actions[0].type` dispatch, jq scripts in
    /// `action/jq/review-comments-check.jq` and `ci/jq/review-check.jq`)
    /// pattern-match on this string. A future refactor that puts the
    /// generic `remove-catalog-reference` fallback at position 0 would
    /// flip every CI annotation from "add this entry" to "remove this
    /// reference", reversing the recommended action.
    #[test]
    fn unresolved_catalog_position_0_is_add_when_no_alternatives() {
        let inner = UnresolvedCatalogReference {
            entry_name: "react".to_string(),
            catalog_name: "default".to_string(),
            path: PathBuf::from("apps/web/package.json"),
            line: 7,
            available_in_catalogs: Vec::new(),
        };
        let finding = UnresolvedCatalogReferenceFinding::with_actions(inner);
        assert_eq!(
            action_type(&finding.actions[0]),
            "add-catalog-entry",
            "position-0 must be `add-catalog-entry` when no alternative catalog declares the package"
        );
        let IssueAction::Fix(fix) = &finding.actions[0] else {
            panic!("position-0 should be an IssueAction::Fix");
        };
        assert!(
            fix.available_in_catalogs.is_none(),
            "add-catalog-entry must NOT carry available_in_catalogs"
        );
        assert!(
            fix.suggested_target.is_none(),
            "add-catalog-entry must NOT carry suggested_target"
        );
    }

    /// Invariant: when at least one alternative catalog declares the
    /// package, position 0 flips to `update-catalog-reference` and carries
    /// the alternative list. When exactly one alternative exists, the
    /// action also carries `suggested_target` so deterministic agents can
    /// land the edit without picking from the list. This is the
    /// counterpart to `unresolved_catalog_position_0_is_add_when_no_alternatives`.
    #[test]
    fn unresolved_catalog_position_0_is_update_when_alternatives_exist() {
        let inner = UnresolvedCatalogReference {
            entry_name: "react".to_string(),
            catalog_name: "default".to_string(),
            path: PathBuf::from("apps/web/package.json"),
            line: 7,
            available_in_catalogs: vec!["react18".to_string()],
        };
        let finding = UnresolvedCatalogReferenceFinding::with_actions(inner);
        assert_eq!(
            action_type(&finding.actions[0]),
            "update-catalog-reference",
            "position-0 must be `update-catalog-reference` when at least one alternative catalog declares the package"
        );
        let IssueAction::Fix(fix) = &finding.actions[0] else {
            panic!("position-0 should be an IssueAction::Fix");
        };
        assert_eq!(
            fix.available_in_catalogs.as_deref(),
            Some(&["react18".to_string()][..]),
            "update-catalog-reference must carry the alternative list"
        );
        assert_eq!(
            fix.suggested_target.as_deref(),
            Some("react18"),
            "single-alternative case must surface `suggested_target` for deterministic agents"
        );

        // Two alternatives: still update, but no unambiguous target.
        let inner_two = UnresolvedCatalogReference {
            entry_name: "react".to_string(),
            catalog_name: "default".to_string(),
            path: PathBuf::from("apps/web/package.json"),
            line: 7,
            available_in_catalogs: vec!["react17".to_string(), "react18".to_string()],
        };
        let finding_two = UnresolvedCatalogReferenceFinding::with_actions(inner_two);
        assert_eq!(
            action_type(&finding_two.actions[0]),
            "update-catalog-reference"
        );
        let IssueAction::Fix(fix_two) = &finding_two.actions[0] else {
            panic!("position-0 should be an IssueAction::Fix");
        };
        assert!(
            fix_two.suggested_target.is_none(),
            "multi-alternative case must NOT carry `suggested_target` (agent must pick)"
        );
    }

    /// Invariant: position 0 of `duplicate_exports[].actions` is
    /// `add-to-config` (the safe `ignoreExports` rule for the
    /// namespace-barrel case), NOT the destructive `remove-duplicate`.
    ///
    /// This protects the shadcn / Radix / bits-ui pattern where every
    /// `components/ui/<name>/index.ts` intentionally re-exports the same
    /// short names. Any consumer that reads `actions[0].type` as "the
    /// recommended fix" must see the non-destructive path first; flipping
    /// position 0 to `remove-duplicate` would propose deleting an
    /// intentional API surface.
    ///
    /// This test pins position 0 across both possible auto_fixable values
    /// for the add-to-config action (the per-instance flip flag handled
    /// by `set_config_fixable`).
    #[test]
    fn duplicate_exports_position_0_is_add_to_config_not_remove_duplicate() {
        let inner = DuplicateExport {
            export_name: "Root".to_string(),
            locations: vec![
                DuplicateLocation {
                    path: PathBuf::from("components/ui/accordion/index.ts"),
                    line: 1,
                    col: 0,
                },
                DuplicateLocation {
                    path: PathBuf::from("components/ui/dialog/index.ts"),
                    line: 1,
                    col: 0,
                },
            ],
        };
        let finding = DuplicateExportFinding::with_actions(inner);
        assert_eq!(
            action_type(&finding.actions[0]),
            "add-to-config",
            "position-0 must be `add-to-config` (safe `ignoreExports` path), NOT `remove-duplicate`"
        );
        assert_eq!(
            action_type(&finding.actions[1]),
            "remove-duplicate",
            "position-1 must be the destructive `remove-duplicate` fallback"
        );

        // `set_config_fixable(true)` flips the position-0 add-to-config
        // bool but must NOT re-order positions.
        let mut promoted = finding;
        promoted.set_config_fixable(true);
        assert_eq!(action_type(&promoted.actions[0]), "add-to-config");
        let IssueAction::AddToConfig(action) = &promoted.actions[0] else {
            panic!("position-0 should still be AddToConfig after set_config_fixable");
        };
        assert!(
            action.auto_fixable,
            "set_config_fixable(true) must flip auto_fixable"
        );
    }

    /// Invariant: a duplicate-exports finding with empty `locations`
    /// degenerate input drops the `add-to-config` action entirely, so
    /// position 0 falls through to `remove-duplicate`. Documents the
    /// degenerate-case contract.
    #[test]
    fn duplicate_exports_no_locations_falls_through_to_remove_duplicate() {
        let inner = DuplicateExport {
            export_name: "Root".to_string(),
            locations: Vec::new(),
        };
        let finding = DuplicateExportFinding::with_actions(inner);
        assert_eq!(
            action_type(&finding.actions[0]),
            "remove-duplicate",
            "with no locations there is no ignoreExports rule to suggest; the destructive remove becomes position-0"
        );

        // `set_config_fixable(true)` is a no-op on this shape.
        let mut promoted = finding;
        promoted.set_config_fixable(true);
        assert_eq!(
            action_type(&promoted.actions[0]),
            "remove-duplicate",
            "set_config_fixable is a no-op when position-0 is not add-to-config"
        );
    }

    /// Invariant: misconfigured-dependency-override with empty
    /// `target_package` AND empty `raw_key` drops the suppress action
    /// (no usable package name for the `ignoreDependencyOverrides`
    /// matcher; emitting `package: ""` would be silently dropped by the
    /// config parser). Documents the suppress-omission contract.
    #[test]
    fn misconfigured_override_drops_suppress_when_no_package_name() {
        let inner = MisconfiguredDependencyOverride {
            raw_key: String::new(),
            target_package: None,
            raw_value: String::new(),
            reason: crate::results::DependencyOverrideMisconfigReason::EmptyValue,
            source: DependencyOverrideSource::PnpmWorkspaceYaml,
            path: PathBuf::from("pnpm-workspace.yaml"),
            line: 12,
        };
        let finding = MisconfiguredDependencyOverrideFinding::with_actions(inner);
        // Only the primary fix-dependency-override action: no suppress.
        assert_eq!(finding.actions.len(), 1);
        assert_eq!(action_type(&finding.actions[0]), "fix-dependency-override");
    }
}