cargo-antigen 0.2.0

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

use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand};

use antigen::{audit, presents, scan};

/// Cargo subcommand for antigen.
#[derive(Debug, Parser)]
#[command(name = "cargo-antigen", bin_name = "cargo", version)]
struct CargoCli {
    #[command(subcommand)]
    command: CargoSubcommand,
}

#[derive(Debug, Subcommand)]
enum CargoSubcommand {
    /// The "antigen" subcommand of cargo.
    Antigen(AntigenCli),
}

#[derive(Debug, Parser)]
#[command(version)]
struct AntigenCli {
    #[command(subcommand)]
    command: AntigenSubcommand,
}

#[derive(Debug, Subcommand)]
enum AntigenSubcommand {
    /// Scan the workspace for antigen presentations and report unaddressed ones.
    Scan(ScanArgs),
    /// Scaffold a new antigen declaration (design phase).
    ///
    /// Hidden from `--help` output until the command ships beyond its
    /// design-phase stub. Stub message remains for users who discover the
    /// name via docs or history. Per the onboarding sweep (Phase 1) +
    /// Tekgy's directive: show new users the surface that works, not the
    /// surface that doesn't.
    #[command(hide = true)]
    New {
        /// kebab-case name for the new antigen
        name: String,
    },
    /// Apply known immunity pattern across a structural family (design phase).
    ///
    /// Hidden from `--help` output until the command ships beyond its
    /// design-phase stub (see `New` above for the same discipline).
    #[command(hide = true)]
    Vaccinate {
        /// Antigen type to apply
        antigen: String,
        /// Pattern (glob or path) describing target sites
        pattern: String,
    },
    /// Comprehensive immunity coverage report — witness resolution and tier validation.
    Audit(AuditArgs),
    /// Manage `.attest/<Antigen>.json` substrate-witness sidecars (ADR-019).
    Attest(AttestCli),
    /// Manage tolerance-ratification sidecars (ADR-019 §tolerance tier).
    Tolerate(TolerateCli),
    /// Manage Oracle artifact-class records (ADR-021 §D3).
    ///
    /// Oracles are structurally-distinguished discipline artifacts with lifecycle
    /// state (Draft → Complete → Deprecated/Retired/Revoked), dedicated stewards,
    /// and provenance tracking. `cargo antigen oracle` manages the Oracle JSON
    /// records and their state-machine transitions.
    Oracle(OracleCli),
    /// Drive Supply-Chain Defense Family verifications (ADR-025).
    ///
    /// Eight subcommands cover dep-pinning, dep-attestation, content-hash
    /// recording/verification, maintainer snapshots, and (v0.4+ stubs)
    /// sandbox/behavioral checks. The `cargo antigen verify` family backs
    /// the supply-chain stdlib antigens declared in
    /// `antigen::stdlib::supply_chain` — `cargo antigen audit` walks
    /// `requires = ...` substrate-witness predicates and routes them
    /// through these handlers.
    Verify(VerifyCli),
    /// Drive VCS-Information-Loss Family observations (ADR-026).
    ///
    /// Observation subcommands (v0.2): `scan` (surface VCS-info-loss risk
    /// across the repo), `check-commit` (evaluate one commit's trailers
    /// against the rollback-triage chain), `attest` (record a branch-archive
    /// or rollback-triage attestation sidecar), `rollback-prepare` (scaffold
    /// a triage-commit before a rollback), `branch-archive` (attest a branch
    /// deletion). These OBSERVE the git substrate via the
    /// `antigen::vcs_witness` evaluators; they do not install hooks.
    /// `install-hooks` / `install-server-hooks` (the enforcement layer that
    /// executes the detection decision tree) defer to v0.2.x post-ADR-026
    /// Amendment 4 ratification per the witness-layer-independence split.
    Vcs(VcsCli),
    /// Map mucosal trust boundaries across the workspace (ADR-027 + Amd 1).
    ///
    /// Walks the scan report's mucosal declarations and runs the
    /// `audit_mucosal` pipeline (incl. the Change-5 three-tier delegate
    /// kind-matching diagnosis). `--undefended` lists boundaries with no
    /// `#[mucosal]` / `#[mucosal_tolerant]` declaration; `--tolerant` lists
    /// the active-tolerance boundaries for periodic reviewer audit;
    /// `--kind <kind>` filters to one `MucosalKind`.
    MucosalMap(MucosalMapArgs),
    /// Print the structural fingerprint of a scanned item.
    ///
    /// The same digest `attest scaffold`/`sign` need and `scan --format json`
    /// surfaces, exposed as a first-class verb so an operator can obtain a
    /// fingerprint WITHOUT scaffolding first — for the `sign` step, for
    /// hand-editing a sidecar, or for scripting. Scans the `--root` subtree and
    /// prints the `structural_fingerprint` of every immune/presents site,
    /// optionally narrowed by `--antigen` and/or `--item-path`.
    Fingerprint(FingerprintArgs),
}

#[derive(Debug, Parser)]
struct ScanArgs {
    /// Workspace root (default: current directory)
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Output format: human or json
    #[arg(long, default_value = "human")]
    format: OutputFormat,
    /// Exit with non-zero status if unaddressed presentations are found
    #[arg(long)]
    strict: bool,
    /// Also scan dependency crates (registry/git) resolved by `cargo metadata`.
    /// Each dep is scanned independently; results appear under `dep_reports`
    /// in JSON output. Per A3 scope-lock: no cross-crate `addresses()` matching
    /// in v0.1 — each crate's report stays its own bag of antigens. Default OFF
    /// for backward compatibility.
    #[arg(long)]
    include_deps: bool,
    /// Filter to antigen declarations of a single category (ADR-028 §CLI
    /// integration). Accepts `substrate-alignment` or `functional-correctness`.
    /// A hybrid antigen (both categories) matches either filter.
    #[arg(long)]
    category: Option<String>,
}

#[derive(Debug, Parser)]
struct AuditArgs {
    /// Workspace root (default: current directory)
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Output format: human or json
    #[arg(long, default_value = "human")]
    format: OutputFormat,
    /// Exit with non-zero status if any immunity witness is unresolved
    /// (`Missing`, `NotFound`, or `Ambiguous`). v0.1: gates on `Reachability`
    /// tier minimum; `Execution`-tier gating arrives in A3 with `cargo test`
    /// integration.
    #[arg(long)]
    strict: bool,
    /// Filter the category audit to a single category (ADR-028 §CLI
    /// integration). Accepts `substrate-alignment` or `functional-correctness`.
    /// A hybrid antigen (both categories) matches either filter.
    #[arg(long)]
    category: Option<String>,
}

#[derive(Debug, Parser)]
struct FingerprintArgs {
    /// Workspace (or crate) root to scan (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Only report sites whose antigen type matches (last path segment, e.g.
    /// `SignedZeroDiscipline`). Omit to report every scanned immune/presents site.
    #[arg(long)]
    antigen: Option<String>,
    /// Only report the site at this item path (matched against the item's
    /// rendered label, e.g. `sinh`, `Type::method`). Requires the named site to
    /// exist in the scanned root.
    #[arg(long)]
    item_path: Option<String>,
    /// Output format: human or json.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
}

// ============================================================================
// cargo antigen attest subcommand family (ADR-019 substrate-witness sidecars)
// ============================================================================

#[derive(Debug, Parser)]
struct AttestCli {
    #[command(subcommand)]
    command: AttestSubcommand,
}

// AttestSubcommand carries the `Oracle` variant (hidden stub) which is a
// declared CLI surface whose implementation is gated on ADR-021 plumbing not
// yet written — a DeclaredCapabilityWithNoProductionPath instance at the
// type-system level (the variant exists in the enum and surfaces in clap, but
// invoking it returns the design-phase error rather than executing the
// promised behavior). Type-level placement on the enclosing enum because Rust
// forbids proc-macro attribute macros on variants directly (variant-position
// placement does not compile — see compile-fail fixture in antigen-macros
// tests/ui/presents_on_enum_variant.rs).
#[presents(antigen::stdlib::dogfood::DeclaredCapabilityWithNoProductionPath)]
#[derive(Debug, Subcommand)]
enum AttestSubcommand {
    /// Create a new `.attest/<Antigen>.json` sidecar file adjacent to the source file.
    Scaffold(AttestScaffoldArgs),
    /// Add a fresh signer entry to an existing `.attest/<Antigen>.json` sidecar.
    Sign(AttestSignArgs),
    /// Evaluate a substrate-witness predicate against a sidecar and report the result.
    Check(AttestCheckArgs),
    /// Add a delta-attestation entry to an existing sidecar.
    Delta(AttestDeltaArgs),
    /// Per-attestation oracle marker (design phase; v0.1-rc stub).
    ///
    /// Renamed from `oracle complete` per F28-R2 cross-ADR collision-avoidance:
    /// `cargo antigen oracle complete` (top-level) is the steward-authorized
    /// oracle-state transition Draft→Complete; this verb (`attest oracle mark`)
    /// is the per-attestation marker recording that a signer reviewed an
    /// oracle reference at this attestation. Distinct semantics, distinct
    /// CLI families. Implementation gated on ADR-021 `OracleRef` schema
    /// (now ratified — Task 1 shipped; this verb's handler is design-phase
    /// pending the `OracleCompletionMarker` schema field plumbing).
    ///
    /// **ATK-021-19 implementation requirement** (per navigator routing
    /// 2026-05-20): the CLI MUST write
    /// `OracleCompletionMarker { oracle_state_at_attestation: <current
    /// oracle state at sign time>, .. }` into the sidecar at every
    /// invocation. Without the sign-time-state anchor, sign-time-validity
    /// (ADR-021 §D4) cannot be structurally enforced — the audit cannot
    /// distinguish "signer attested when oracle was Complete, oracle later
    /// Deprecated" (hint-only, tier preserved) from "signer attested when
    /// oracle was already Deprecated" (tier reject). The audit's fallback
    /// for legacy sidecars without this field is the
    /// `oracle-sign-time-state-unknown` hint at Execution+advisory tier;
    /// new sidecars written by this verb MUST always populate it.
    #[command(hide = true, name = "oracle")]
    Oracle,
    /// List all `.attest/` sidecars in the workspace.
    List(AttestListArgs),
    /// Garbage-collect orphaned sidecar entries (report-only in v0.1).
    Gc(AttestGcArgs),
}

#[derive(Debug, Parser)]
struct AttestDeltaArgs {
    /// Path to the `.attest/<Antigen>.json` sidecar to update.
    #[arg(long)]
    sidecar: PathBuf,
    /// Item path within the sidecar to add a delta entry for.
    #[arg(long)]
    item_path: String,
    /// Signer name (defaults to `git config user.name`).
    #[arg(long)]
    signer: Option<String>,
    /// Role tag for this signer (optional).
    #[arg(long)]
    role: Option<String>,
    /// Current structural fingerprint of the item. The delta is anchored
    /// against this fingerprint. Signer attests the change from
    /// `prior_fingerprint` to this fingerprint is invariant-preserving.
    #[arg(long)]
    fingerprint: String,
    /// Fingerprint this delta is rooted against (the signer's last signature
    /// at this item).
    #[arg(long)]
    prior_fingerprint: String,
    /// Why the change is invariant-preserving. Required non-empty.
    #[arg(long)]
    rationale: String,
    /// Identity-binding strength.
    #[arg(long, default_value = "git-trust")]
    strength: SignatureStrengthArg,
}

#[derive(Debug, Parser)]
struct AttestListArgs {
    /// Workspace root to walk (defaults to current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Only list tolerance sidecars (`RatificationKind::Tolerance`).
    #[arg(long)]
    tolerance_only: bool,
    /// Walk `.attest/` directories independent of scan-side macro discovery
    /// and report orphaned sidecars (sidecars whose `item_path` doesn't appear
    /// in any scan-side Immunity declaration at that path).
    #[arg(long)]
    orphan_scan: bool,
    /// Output format.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
}

#[derive(Debug, Parser)]
struct AttestGcArgs {
    /// Workspace root to walk (defaults to current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Actually remove orphaned sidecars (default: report only).
    #[arg(long)]
    force: bool,
}

#[derive(Debug, Parser)]
struct AttestScaffoldArgs {
    /// The antigen type name (e.g., `SignedZeroCancellation`).
    #[arg(long)]
    antigen: String,
    /// The source file the `#[immune]` declaration lives in. The sidecar is
    /// created at `<source-file-dir>/.attest/<antigen>.json`.
    #[arg(long)]
    source_file: PathBuf,
    /// The item path within the source file (e.g., `sinh`, `cosh`, `MyStruct::method`).
    /// Used as the `item_path` field in the sidecar's `items` array.
    #[arg(long, default_value = "")]
    item_path: String,
    /// The current structural fingerprint of the item. Use the fingerprint from
    /// `cargo antigen scan --format json` or compute via `antigen-fingerprint`.
    /// If omitted the sidecar uses an empty placeholder — update before signing.
    #[arg(long, default_value = "")]
    fingerprint: String,
    /// Ratification kind: `immunity` (default) or `tolerance`.
    #[arg(long, default_value = "immunity")]
    kind: RatificationKindArg,
    /// Overwrite an existing sidecar without prompting.
    #[arg(long)]
    force: bool,
}

#[derive(Debug, Parser)]
struct AttestSignArgs {
    /// Path to the `.attest/<Antigen>.json` sidecar to update.
    #[arg(long)]
    sidecar: PathBuf,
    /// The item path within the sidecar's `items` array to add the signer to.
    /// Must match an existing `item_path` in the sidecar.
    #[arg(long)]
    item_path: String,
    /// Signer's display name (e.g., `alice`).
    #[arg(long)]
    signer: String,
    /// The current structural fingerprint of the item (must match the sidecar's
    /// `current_fingerprint` for the item). This is the value that `signed_against_fingerprint`
    /// records — `cargo antigen audit` compares it against the item's real fingerprint
    /// to detect staleness.
    #[arg(long)]
    fingerprint: String,
    /// Optional role for this signer (e.g., `math-reviewer`, `security-reviewer`).
    #[arg(long)]
    role: Option<String>,
    /// Optional free-text reasoning for this signature. Records WHY the signer
    /// attested to discipline compliance at this moment.
    #[arg(long)]
    reasoning: Option<String>,
    /// Identity-binding strength of this signature.
    ///
    /// `text-stamp` — name + timestamp only; no external identity verification;
    /// suitable for LLM agents or reviewers without git config.
    /// `git-trust` — identity bound to `git config user.name/email` (default).
    /// `crypto-signed` — cryptographic identity binding (v0.4+ activation path).
    #[arg(long, default_value = "git-trust")]
    strength: SignatureStrengthArg,
}

#[derive(Debug, Parser)]
struct AttestCheckArgs {
    /// Path to the `.attest/<Antigen>.json` sidecar to evaluate against.
    #[arg(long)]
    sidecar: PathBuf,
    /// The predicate JSON to evaluate. Must match the `antigen_attestation::Predicate`
    /// serde format. Example: `{"kind":"leaf","leaf":{"name":"signers","required":["alice"]}}`
    #[arg(long)]
    predicate: String,
    /// The item path within the sidecar's `items` array to evaluate.
    /// If omitted, evaluates the first item.
    #[arg(long)]
    item_path: Option<String>,
    /// The current structural fingerprint of the item, for stale-signer detection.
    /// If omitted, uses the sidecar's stored `current_fingerprint`.
    #[arg(long)]
    fingerprint: Option<String>,
}

/// CLI representation of `antigen_attestation::RatificationKind`.
#[derive(Debug, Clone, clap::ValueEnum)]
enum RatificationKindArg {
    Immunity,
    Tolerance,
}

impl From<RatificationKindArg> for antigen_attestation::RatificationKind {
    fn from(k: RatificationKindArg) -> Self {
        match k {
            RatificationKindArg::Immunity => Self::Immunity,
            RatificationKindArg::Tolerance => Self::Tolerance,
        }
    }
}

/// CLI representation of `antigen_attestation::SignatureStrength`.
#[derive(Debug, Clone, clap::ValueEnum)]
enum SignatureStrengthArg {
    TextStamp,
    GitTrust,
    CryptoSigned,
}

impl From<SignatureStrengthArg> for antigen_attestation::SignatureStrength {
    fn from(s: SignatureStrengthArg) -> Self {
        match s {
            SignatureStrengthArg::TextStamp => Self::TextStamp,
            SignatureStrengthArg::GitTrust => Self::GitTrust,
            SignatureStrengthArg::CryptoSigned => Self::CryptoSigned,
        }
    }
}

// ============================================================================
// cargo antigen tolerate subcommand family (ADR-019 tolerance sidecars)
// ============================================================================

#[derive(Debug, Parser)]
struct TolerateCli {
    #[command(subcommand)]
    command: TolerateSubcommand,
}

#[derive(Debug, Subcommand)]
enum TolerateSubcommand {
    /// Create a new tolerance sidecar at `.attest/<Antigen>.json` adjacent to source.
    ///
    /// Equivalent to `attest scaffold --kind tolerance`. Tolerance sidecars share
    /// the same `Ratification` schema — the `kind` discriminator distinguishes them.
    Scaffold(AttestScaffoldArgs),
    /// Add a fresh signer entry to an existing tolerance sidecar.
    Sign(AttestSignArgs),
    /// Evaluate a substrate-witness predicate against a tolerance sidecar.
    Check(AttestCheckArgs),
    /// List all tolerance sidecars in the workspace.
    List(AttestListArgs),
}

// ============================================================================
// cargo antigen oracle subcommand family (ADR-021 oracle-as-artifact-class)
// ============================================================================

#[derive(Debug, Parser)]
struct OracleCli {
    #[command(subcommand)]
    command: OracleSubcommand,
}

#[derive(Debug, Subcommand)]
enum OracleSubcommand {
    /// List all Oracle artifact records in the workspace.
    List(OracleListArgs),
    /// Show current state, stewards, transitions, and attestations for one oracle.
    Status(OracleStatusArgs),
    /// Create a new Oracle in DRAFT state.
    Declare(OracleDeclareArgs),
    /// Transition an oracle from DRAFT to COMPLETE (steward-authorized).
    ///
    /// Signers may attest against Complete oracles; Draft oracles block
    /// the `oracles_complete(...)` predicate per ADR-021 §D3.
    Complete(OracleCompleteArgs),
    /// Transition an oracle from COMPLETE to DEPRECATED (steward-authorized).
    ///
    /// Existing attestations honored at Execution tier (sign-time-validity D4).
    /// For INCORRECT oracles use `oracle revoke` instead.
    Deprecate(OracleDeprecateArgs),
    /// Permanently retire an oracle (steward-authorized).
    ///
    /// All prior attestations honored. Use only when oracle is gone for reasons
    /// other than incorrectness. For incorrect oracles use `oracle revoke`.
    Retire(OracleRetireArgs),
    /// Revoke an oracle for incorrectness or fraud (steward-authorized).
    ///
    /// `--invalidates-prior true` retroactively demotes prior attestations to
    /// Reachability. `--invalidates-prior false` preserves prior attestation tiers.
    Revoke(OracleRevokeArgs),
}

#[derive(Debug, Parser)]
struct OracleListArgs {
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Output format.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
}

#[derive(Debug, Parser)]
struct OracleStatusArgs {
    /// Oracle ID.
    #[arg(long)]
    id: String,
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Parser)]
struct OracleDeclareArgs {
    /// Stable oracle identifier.
    #[arg(long)]
    id: String,
    /// Reference kind: `local-file`, `url`, `doi`, `arxiv`, `github-issue`, `other`.
    #[arg(long)]
    kind: OracleRefKindArg,
    /// Reference value (file path, URL, DOI, arXiv ID, `owner/repo#N`, or free-form).
    #[arg(long)]
    reference: String,
    /// Steward name (defaults to git config user.name). Pass twice for 2 stewards.
    #[arg(long, action = clap::ArgAction::Append)]
    steward: Vec<String>,
    /// WHY this oracle is being declared (required non-empty per Amendment 2).
    #[arg(long)]
    rationale: String,
    /// Version pin at declaration time.
    #[arg(long)]
    version: Option<String>,
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Clone, clap::ValueEnum)]
#[clap(rename_all = "kebab-case")]
enum OracleRefKindArg {
    LocalFile,
    Url,
    Doi,
    Arxiv,
    GithubIssue,
    Other,
}

#[derive(Debug, Parser)]
struct OracleCompleteArgs {
    /// Oracle ID to transition Draft→Complete.
    #[arg(long)]
    id: String,
    /// Authorizing steward (defaults to git config user.name).
    #[arg(long)]
    steward: Option<String>,
    /// Version pin at completion time.
    #[arg(long)]
    version: String,
    /// WHY completing (required non-empty per Amendment 2).
    #[arg(long)]
    rationale: String,
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Parser)]
struct OracleDeprecateArgs {
    /// Oracle ID to deprecate.
    #[arg(long)]
    id: String,
    /// Authorizing steward (defaults to git config user.name).
    #[arg(long)]
    steward: Option<String>,
    /// Optional successor oracle ID.
    #[arg(long)]
    superseded_by: Option<String>,
    /// WHY deprecating (required non-empty per Amendment 2).
    #[arg(long)]
    rationale: String,
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Parser)]
struct OracleRetireArgs {
    /// Oracle ID to retire.
    #[arg(long)]
    id: String,
    /// Authorizing steward (defaults to git config user.name).
    #[arg(long)]
    steward: Option<String>,
    /// WHY retiring (required non-empty per Amendment 2).
    #[arg(long)]
    rationale: String,
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Parser)]
struct OracleRevokeArgs {
    /// Oracle ID to revoke.
    #[arg(long)]
    id: String,
    /// Authorizing steward (defaults to git config user.name).
    #[arg(long)]
    steward: Option<String>,
    /// WHY revoking (required non-empty per Amendment 2).
    #[arg(long)]
    rationale: String,
    /// Whether to retroactively demote prior attestations to Reachability.
    #[arg(long)]
    invalidates_prior: bool,
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Clone, clap::ValueEnum)]
enum OutputFormat {
    Human,
    Json,
}

// ============================================================================
// cargo antigen verify — Supply-Chain Defense Family CLI (ADR-025)
// ============================================================================

#[derive(Debug, Parser)]
struct VerifyCli {
    #[command(subcommand)]
    command: VerifySubcommand,
}

#[derive(Debug, Subcommand)]
enum VerifySubcommand {
    /// Check `Cargo.toml` for unpinned + unattested dependencies.
    Deps(VerifyDepsArgs),
    /// Detect crate-ownership changes since the last attested snapshot.
    ///
    /// **CI sequencing constraint (load-bearing)**: this subcommand MUST
    /// run BEFORE `cargo update`. After `cargo update` the new
    /// maintainer's code has already landed in `Cargo.lock`; the gate
    /// has effectively already passed. Document the sequencing in
    /// CI scripts. Per ADR-025 §Decision.
    MaintainerChanges(VerifyMaintainerChangesArgs),
    /// Record a dep-attestation sidecar.
    ///
    /// `--reviewable-artifact <PATH>` is REQUIRED — empty/missing
    /// values produce a rubber-stamp sidecar that the audit will
    /// flag with `dep-attest-without-reviewable-artifact`. Per
    /// ADR-025 §Schema-additions.
    DepAttest(VerifyDepAttestArgs),
    /// Bulk-pin every unpinned `Cargo.toml` dep with the current
    /// resolved version (advisory v0.2: prints suggested edits;
    /// in-place rewrite is v0.3+).
    DepPin(VerifyDepPinArgs),
    /// Record or check a content-hash for `<crate@version>`.
    ///
    /// **THE NON-NEGOTIABLE CHALK/DEBUG DEFENSE**. First-attestation:
    /// `cargo antigen verify content-hash record <crate@version>`.
    /// Verification: `cargo antigen verify content-hash <crate@version>`.
    /// Per ADR-025 §Decision + B1-R.
    ContentHash(VerifyContentHashArgs),
    /// v0.4+: sandbox-execute a proc-macro dep and report observations.
    /// Currently a stub that surfaces the "tooling not yet available"
    /// awareness signal per ADR-005 Amendment 2 honest-tier-naming.
    #[command(name = "proc-macro-sandbox")]
    ProcMacroSandbox,
    /// v0.4+: sandbox-execute a `build.rs` and report observations.
    /// Currently a stub (see `proc-macro-sandbox`).
    Sandbox,
    /// v0.5+: compare behavioral fingerprints across dep versions.
    /// Currently a stub.
    BehavioralDiff,
}

#[derive(Debug, Parser)]
struct VerifyDepsArgs {
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Output format: human or json.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
    /// Optional crate name to scope the check (default: every dep).
    #[arg(long)]
    crate_name: Option<String>,
    /// Exit non-zero when any unpinned/unattested dep is found.
    #[arg(long)]
    strict: bool,
}

#[derive(Debug, Parser)]
struct VerifyMaintainerChangesArgs {
    /// Workspace root.
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Crate to check.
    #[arg(long)]
    crate_name: String,
    /// Anchor version. The snapshot at
    /// `.attest/supply-chain/maintainer/<crate>.json` must match.
    #[arg(long)]
    since_version: String,
}

// `review_scope: String` (below) is the UnvalidatedSealedEnumAcceptance site:
// the arg accepts an arbitrary String at clap parse-time and is matched in
// run_verify_dep_attest against 5 valid ReviewScope variants + an `other`
// fallthrough — the sealed-enum vocabulary lives in the type system
// (`antigen::supply_chain::schema::ReviewScope`) but the CLI never enforces
// membership at the boundary. A typo or invented value parses fine and falls
// into the `other` arm with no signal. Type-level placement on the enclosing
// struct (Rust forbids proc-macro attrs on struct fields directly — same
// compile barrier as variants; see compile-fail fixture).
#[presents(antigen::stdlib::dogfood::UnvalidatedSealedEnumAcceptance)]
#[derive(Debug, Parser)]
struct VerifyDepAttestArgs {
    /// Workspace root.
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// `<crate>@<version>` positional argument.
    crate_at_version: String,
    /// **REQUIRED** non-empty path to the human-reviewable artifact
    /// that documents the review (Markdown, ADR, PR comment export,
    /// etc.). Empty values are rejected outright.
    #[arg(long, required = true)]
    reviewable_artifact: PathBuf,
    /// Review scope: `full` | `diff` | `build-script-only` |
    /// `proc-macro-only` | `metadata-only`.
    #[arg(long, default_value = "metadata-only")]
    review_scope: String,
    /// Whether the attestation applies only to this exact version
    /// (default `true`).
    #[arg(long, default_value_t = true)]
    exact_version: bool,
    /// Signer name (defaults to `git config user.name`).
    #[arg(long)]
    signed_by: Option<String>,
    /// Optional human rationale.
    #[arg(long)]
    rationale: Option<String>,
}

#[derive(Debug, Parser)]
struct VerifyDepPinArgs {
    /// Workspace root.
    #[arg(long, default_value = ".")]
    root: PathBuf,
}

#[derive(Debug, Parser)]
struct VerifyContentHashArgs {
    #[command(subcommand)]
    command: VerifyContentHashSubcommand,
}

#[derive(Debug, Subcommand)]
enum VerifyContentHashSubcommand {
    /// Record the current `Cargo.lock` checksum as the first-attestation
    /// hash for `<crate@version>`.
    Record(VerifyContentHashRecordArgs),
    /// Compare the current `Cargo.lock` checksum for `<crate@version>`
    /// against the recorded first-attestation hash.
    Check(VerifyContentHashCheckArgs),
}

#[derive(Debug, Parser)]
struct VerifyContentHashRecordArgs {
    /// Workspace root.
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// `<crate>@<version>` positional argument.
    crate_at_version: String,
    /// Signer name (defaults to `git config user.name`).
    #[arg(long)]
    signed_by: Option<String>,
}

#[derive(Debug, Parser)]
struct VerifyContentHashCheckArgs {
    /// Workspace root.
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// `<crate>@<version>` positional argument.
    crate_at_version: String,
}

fn run_verify(cli: VerifyCli) -> ExitCode {
    match cli.command {
        VerifySubcommand::Deps(args) => run_verify_deps(args),
        VerifySubcommand::MaintainerChanges(args) => run_verify_maintainer_changes(args),
        VerifySubcommand::DepAttest(args) => run_verify_dep_attest(args),
        VerifySubcommand::DepPin(args) => run_verify_dep_pin(args),
        VerifySubcommand::ContentHash(args) => match args.command {
            VerifyContentHashSubcommand::Record(a) => run_verify_content_hash_record(a),
            VerifyContentHashSubcommand::Check(a) => run_verify_content_hash_check(a),
        },
        VerifySubcommand::ProcMacroSandbox => run_verify_stub(
            "proc-macro-sandbox",
            "v0.4+",
            "Active proc-macro sandboxing (ADR-025 tooling-phase 3).",
        ),
        VerifySubcommand::Sandbox => run_verify_stub(
            "sandbox",
            "v0.4+",
            "Active build.rs sandboxing (ADR-025 tooling-phase 3).",
        ),
        VerifySubcommand::BehavioralDiff => run_verify_stub(
            "behavioral-diff",
            "v0.5+",
            "Behavioral-fingerprint comparison across versions (ADR-025 tooling-phase 4).",
        ),
    }
}

fn run_verify_deps(args: VerifyDepsArgs) -> ExitCode {
    use antigen::supply_chain::evaluate::evaluate_dep_pinned;
    use antigen::supply_chain::witness::DepPinnedState;
    let state = evaluate_dep_pinned(&args.root, args.crate_name.as_deref());
    let unpinned_names = match &state {
        DepPinnedState::AllPinned => Vec::new(),
        DepPinnedState::Unpinned { unpinned_deps } => unpinned_deps.clone(),
        DepPinnedState::NotInManifest { crate_name } => vec![crate_name.clone()],
    };
    match args.format {
        OutputFormat::Human => {
            if unpinned_names.is_empty() {
                println!("verify deps: all checked dependencies are exact-pinned.");
            } else {
                println!(
                    "verify deps: {n} dep(s) without exact-pin `=` specifiers:",
                    n = unpinned_names.len()
                );
                for n in &unpinned_names {
                    println!("  - {n}");
                }
                println!();
                println!("To fix:");
                println!("  edit Cargo.toml; change each entry to `<name> = \"=X.Y.Z\"`.");
                println!("Per ADR-025 §UnpinnedDependency — exact-pin is the discipline.");
            }
        }
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::to_string(&serde_json::json!({
                    "subcommand": "verify-deps",
                    "unpinned_deps": unpinned_names,
                    "passed": unpinned_names.is_empty(),
                }))
                .unwrap_or_else(|_| "{}".to_string())
            );
        }
    }
    if args.strict && !unpinned_names.is_empty() {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn run_verify_maintainer_changes(args: VerifyMaintainerChangesArgs) -> ExitCode {
    use antigen::supply_chain::evaluate::{evaluate_maintainer_unchanged, is_valid_crate_name};
    use antigen::supply_chain::witness::MaintainerState;
    if !is_valid_crate_name(&args.crate_name) {
        eprintln!(
            "error: --crate-name must contain only ASCII alphanumeric characters, `_`, or `-` \
             (got `{}`). Path traversal sequences are not permitted.",
            args.crate_name
        );
        return ExitCode::from(2);
    }
    println!(
        "verify maintainer-changes: checking {crate_name} @ {since_version}",
        crate_name = args.crate_name,
        since_version = args.since_version,
    );
    println!();
    println!("WARNING: this subcommand MUST run BEFORE `cargo update`. After");
    println!("`cargo update`, the new maintainer's code is already in Cargo.lock");
    println!("and the gate has effectively already passed. Per ADR-025.");
    println!();
    let state = evaluate_maintainer_unchanged(&args.root, &args.crate_name, &args.since_version);
    match state {
        MaintainerState::Unchanged => {
            println!("result: maintainer-unchanged (snapshot matches)");
            ExitCode::SUCCESS
        }
        MaintainerState::Changed { added, removed } => {
            println!("result: MAINTAINER-CHANGE-WITHOUT-REATTESTATION");
            println!("  added owners: {added:?}");
            println!("  removed owners: {removed:?}");
            ExitCode::from(1)
        }
        MaintainerState::SnapshotMissing => {
            println!("result: snapshot missing");
            println!(
                "  expected: .attest/supply-chain/maintainer/{crate_name}.json",
                crate_name = args.crate_name
            );
            println!("  (v0.2: snapshot is operator-managed; v0.3+ adds live crates.io query)");
            ExitCode::from(1)
        }
        MaintainerState::CratesIoQueryUnavailable => {
            println!("result: crates.io query unavailable (v0.2 limitation per ADR-025)");
            ExitCode::from(2)
        }
    }
}

fn run_verify_dep_attest(args: VerifyDepAttestArgs) -> ExitCode {
    use antigen::supply_chain::evaluate::dep_attest_path;
    use antigen::supply_chain::schema::{DepAttestation, ReviewScope};

    if args.reviewable_artifact.as_os_str().is_empty()
        || args.reviewable_artifact.to_string_lossy().trim().is_empty()
    {
        eprintln!(
            "error: --reviewable-artifact must be a non-empty, non-whitespace path. \
             Empty values create a rubber-stamp sidecar that the audit will flag with \
             dep-attest-without-reviewable-artifact. Per ADR-025 + ATK-SC-1-A."
        );
        return ExitCode::from(2);
    }

    let Some((crate_name, version)) = parse_crate_at_version(&args.crate_at_version) else {
        eprintln!("error: argument must be `<crate>@<version>` (e.g., `serde@1.0.197`)");
        return ExitCode::from(2);
    };

    let scope = match args.review_scope.as_str() {
        "full" => ReviewScope::Full,
        "diff" => ReviewScope::Diff,
        "build-script-only" | "build_script_only" => ReviewScope::BuildScriptOnly,
        "proc-macro-only" | "proc_macro_only" => ReviewScope::ProcMacroOnly,
        "metadata-only" | "metadata_only" => ReviewScope::MetadataOnly,
        other => {
            eprintln!(
                "error: --review-scope must be one of: full, diff, build-script-only, \
                 proc-macro-only, metadata-only (got `{other}`)"
            );
            return ExitCode::from(2);
        }
    };

    let signed_by = match resolve_steward_name(args.signed_by.as_deref()) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let date = chrono::Utc::now().format("%Y-%m-%d").to_string();

    let attest = DepAttestation {
        crate_name: crate_name.clone(),
        version: version.clone(),
        exact_version: args.exact_version,
        reviewable_artifact: args.reviewable_artifact,
        review_scope: scope,
        signed_by,
        date,
        rationale: args.rationale,
    };

    let path = dep_attest_path(&args.root, &crate_name, &version);
    if let Some(parent) = path.parent() {
        if let Err(e) = std::fs::create_dir_all(parent) {
            eprintln!("error: could not create {}: {e}", parent.display());
            return ExitCode::from(2);
        }
    }
    let json = match serde_json::to_string_pretty(&attest) {
        Ok(j) => j,
        Err(e) => {
            eprintln!("error: serialize attestation: {e}");
            return ExitCode::from(2);
        }
    };
    if let Err(e) = std::fs::write(&path, &json) {
        eprintln!("error: write {}: {e}", path.display());
        return ExitCode::from(2);
    }
    println!("recorded dep-attestation at {}", path.display());
    ExitCode::SUCCESS
}

fn run_verify_dep_pin(args: VerifyDepPinArgs) -> ExitCode {
    use antigen::supply_chain::evaluate::evaluate_dep_pinned;
    use antigen::supply_chain::witness::DepPinnedState;
    let state = evaluate_dep_pinned(&args.root, None);
    match state {
        DepPinnedState::AllPinned => {
            println!("verify dep-pin: all Cargo.toml deps already exact-pinned. No edits needed.");
            ExitCode::SUCCESS
        }
        DepPinnedState::Unpinned { unpinned_deps } => {
            println!(
                "verify dep-pin: {n} unpinned dep(s) detected. Suggested edits:",
                n = unpinned_deps.len()
            );
            for name in &unpinned_deps {
                println!("  - in Cargo.toml [dependencies]: pin `{name}` to `=<RESOLVED_VERSION>`");
            }
            println!();
            println!(
                "v0.2: this subcommand prints suggested edits. In-place \
                 rewriting is deferred to v0.3+ (needs a real toml parser to \
                 preserve formatting + comments)."
            );
            ExitCode::SUCCESS
        }
        DepPinnedState::NotInManifest { crate_name } => {
            eprintln!("error: crate `{crate_name}` not found in manifest");
            ExitCode::from(2)
        }
    }
}

fn run_verify_content_hash_record(args: VerifyContentHashRecordArgs) -> ExitCode {
    use antigen::supply_chain::evaluate::{current_hash_from_lockfile, save_content_hash_record};
    use antigen::supply_chain::schema::ContentHashRecord;

    let Some((crate_name, version)) = parse_crate_at_version(&args.crate_at_version) else {
        eprintln!("error: argument must be `<crate>@<version>`");
        return ExitCode::from(2);
    };

    let lockfile = args.root.join("Cargo.lock");
    let Some(checksum) = current_hash_from_lockfile(&lockfile, &crate_name, &version) else {
        eprintln!(
            "error: no `[[package]] name = \"{crate_name}\" version = \"{version}\" checksum = ...` \
             entry in {}. The crate must be in the lockfile with a checksum.",
            lockfile.display()
        );
        return ExitCode::from(2);
    };

    let signed_by = match resolve_steward_name(args.signed_by.as_deref()) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let date = chrono::Utc::now().format("%Y-%m-%d").to_string();

    let record = ContentHashRecord {
        crate_name,
        version,
        content_hash: checksum,
        hash_source: "cargo-lock-checksum".to_string(),
        signed_by,
        date,
    };

    match save_content_hash_record(&args.root, &record) {
        Ok(p) => {
            println!("recorded content-hash at {}", p.display());
            println!("  hash-source: cargo-lock-checksum (v0.2; tarball SHA-256 is v0.3+)");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("error: write record: {e}");
            ExitCode::from(2)
        }
    }
}

fn run_verify_content_hash_check(args: VerifyContentHashCheckArgs) -> ExitCode {
    use antigen::supply_chain::evaluate::evaluate_content_hash_matches;
    use antigen::supply_chain::witness::ContentHashState;

    let Some((crate_name, version)) = parse_crate_at_version(&args.crate_at_version) else {
        eprintln!("error: argument must be `<crate>@<version>`");
        return ExitCode::from(2);
    };

    let state = evaluate_content_hash_matches(&args.root, &crate_name, &version);
    match state {
        ContentHashState::Matches => {
            println!("content-hash: MATCH for {crate_name}@{version}");
            ExitCode::SUCCESS
        }
        ContentHashState::Mismatch { recorded, current } => {
            println!("content-hash: MISMATCH for {crate_name}@{version}");
            println!("  recorded: {recorded}");
            println!("  current:  {current}");
            println!();
            println!("This is the chalk/debug/eslint-config attack signal. Investigate before");
            println!("re-recording — if the change is legitimate, re-attest with a fresh");
            println!("signer + review artifact. Per ADR-025 §ContentHashMismatch.");
            ExitCode::from(1)
        }
        ContentHashState::NoAttestation => {
            println!("content-hash: no first-attestation for {crate_name}@{version}");
            println!("  run: cargo antigen verify content-hash record {crate_name}@{version}");
            ExitCode::from(1)
        }
        ContentHashState::CrateNotInLockfile { crate_name: cn } => {
            eprintln!("error: crate `{cn}` not found in Cargo.lock (no checksum to compare)");
            ExitCode::from(2)
        }
        ContentHashState::SidecarMalformed { error } => {
            eprintln!(
                "error: content-hash sidecar exists but did NOT deserialize cleanly. \
                 Per ATK-SC-2-A this is distinct from no-attestation — corrupting the \
                 sidecar to silently downgrade a Mismatch into a NoAttestation is exactly \
                 the attack the audit blocks. Inspect the file and re-record. \
                 Parse error: {error}"
            );
            ExitCode::from(1)
        }
    }
}

fn run_verify_stub(name: &str, version_target: &str, description: &str) -> ExitCode {
    println!("cargo antigen verify {name}: {version_target} stub");
    println!();
    println!("  {description}");
    println!();
    println!("Per ADR-005 Amendment 2 honest-tier-naming: this subcommand is");
    println!("a deliberate stub. It does NOT silently pass — the supply-chain");
    println!("audit hints surface the un-evaluated witness as the appropriate");
    println!("unsandboxed-* hint, NOT as a passing evaluation.");
    ExitCode::from(2)
}

// ============================================================================
// cargo antigen vcs subcommand family (VCS-Information-Loss Family, ADR-026)
//
// Observation layer (v0.2): reads git substrate (commit trailers, branch
// state) and routes through the `antigen::vcs_witness` evaluators. Git is
// invoked via fixed-arg subprocess per the ADR-019 §Decision §4 bright-line
// rule (git is named, has its own release process, does not execute user
// code, args are fixed). The enforcement layer (install-hooks /
// install-server-hooks that EXECUTE the detection decision tree) defers to
// v0.2.x post-ADR-026 Amendment 4 per witness-layer-independence.
// ============================================================================

#[derive(Debug, Parser)]
struct VcsCli {
    #[command(subcommand)]
    command: VcsSubcommand,
}

#[derive(Debug, Subcommand)]
enum VcsSubcommand {
    /// Evaluate a single commit's `Triage-Decision:` trailer against the
    /// rollback-triage chain (ADR-026 Amendment 4 commit-trailer signal).
    CheckCommit(VcsCheckCommitArgs),
    /// Surface VCS-info-loss risk across recent history (v0.2: reports the
    /// rollback-triage state of revert/reset commits in the recent log).
    Scan(VcsScanArgs),
    /// Record a branch-deletion attestation sidecar before deleting a branch
    /// (`.attest/vcs/branch-archive/<branch>.json`). v0.2: prints the sidecar
    /// JSON the adopter should commit; in-place write is v0.2.x.
    BranchArchive(VcsBranchArchiveArgs),
    /// Scaffold the `#[triage_commit]` + `Triage-Decision:` trailer guidance
    /// for a rollback (v0.2 advisory: prints the trailer line to add).
    RollbackPrepare(VcsRollbackPrepareArgs),
    /// v0.2.x: record a generic VCS attestation sidecar. Currently a stub
    /// surfacing the tooling-not-yet-available awareness signal per
    /// ADR-005 Amendment 2 honest-tier-naming.
    Attest,
}

#[derive(Debug, Parser)]
struct VcsCheckCommitArgs {
    /// Commit-ish to check (default: HEAD).
    #[arg(long, default_value = "HEAD")]
    commit: String,
    /// Output format: human or json.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
    /// Exit non-zero if the rollback-triage chain is absent/malformed.
    #[arg(long)]
    strict: bool,
}

#[derive(Debug, Parser)]
struct VcsScanArgs {
    /// How many recent commits to inspect.
    #[arg(long, default_value = "50")]
    depth: usize,
    /// Output format: human or json.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
}

#[derive(Debug, Parser)]
struct VcsBranchArchiveArgs {
    /// Branch name being archived (attested before deletion).
    branch: String,
    /// Role or name attesting the deletion.
    #[arg(long)]
    by: String,
    /// Rationale for the deletion (non-empty).
    #[arg(long)]
    rationale: String,
}

#[derive(Debug, Parser)]
struct VcsRollbackPrepareArgs {
    /// Triage decision (black|red|yellow|green|white).
    #[arg(long)]
    decision: String,
    /// Commit sha to roll back to.
    #[arg(long)]
    target: String,
}

fn run_vcs(cli: VcsCli) -> ExitCode {
    match cli.command {
        VcsSubcommand::CheckCommit(args) => run_vcs_check_commit(args),
        VcsSubcommand::Scan(args) => run_vcs_scan(args),
        VcsSubcommand::BranchArchive(args) => run_vcs_branch_archive(args),
        VcsSubcommand::RollbackPrepare(args) => run_vcs_rollback_prepare(args),
        VcsSubcommand::Attest => run_vcs_attest_stub(),
    }
}

/// Read a single commit's message and parse its trailers via
/// `git show --format=%B -s <commit>` piped through
/// `git interpret-trailers --parse`. Fixed-arg subprocess per the ADR-019
/// bright-line rule. Returns `(name, value)` pairs; empty on any git failure
/// (tier-honest: no trailers → chain reads as absent).
fn read_commit_trailers(commit: &str) -> Vec<(String, String)> {
    let body = std::process::Command::new("git")
        .args(["show", "--no-patch", "--format=%B", commit])
        .output();
    let body_bytes = match body {
        Ok(o) if o.status.success() => o.stdout,
        _ => return Vec::new(),
    };
    let parsed = std::process::Command::new("git")
        .args(["interpret-trailers", "--parse"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn()
        .and_then(|mut child| {
            use std::io::Write;
            if let Some(stdin) = child.stdin.take() {
                let mut stdin = stdin;
                let _ = stdin.write_all(&body_bytes);
            }
            child.wait_with_output()
        });
    match parsed {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .filter_map(|l| {
                let (k, v) = l.split_once(':')?;
                Some((k.trim().to_owned(), v.trim().to_owned()))
            })
            .collect(),
        _ => Vec::new(),
    }
}

fn run_vcs_check_commit(args: VcsCheckCommitArgs) -> ExitCode {
    use antigen::vcs_witness::RollbackTriageState;
    let trailers = read_commit_trailers(&args.commit);
    let state = RollbackTriageState::evaluate(&trailers);
    match args.format {
        OutputFormat::Json => {
            println!(
                "{}",
                serde_json::to_string_pretty(&state).unwrap_or_else(|_| "{}".to_string())
            );
        }
        OutputFormat::Human => match &state {
            RollbackTriageState::ChainPresent { decision } => {
                println!(
                    "commit {}: rollback-triage chain present (Triage-Decision: {})",
                    args.commit,
                    decision.as_str()
                );
            }
            RollbackTriageState::ChainMalformed { value } => {
                println!(
                    "commit {}: Triage-Decision trailer present but value {value:?} is not a \
                     valid triage decision (black|red|yellow|green|white)",
                    args.commit
                );
            }
            RollbackTriageState::ChainAbsent => {
                println!(
                    "commit {}: no Triage-Decision trailer — backs \
                     vcs-rollback-without-triage-commit if this is a rollback",
                    args.commit
                );
            }
        },
    }
    if args.strict && !state.is_pass() {
        return ExitCode::from(1);
    }
    ExitCode::SUCCESS
}

fn run_vcs_scan(args: VcsScanArgs) -> ExitCode {
    use antigen::vcs_witness::RollbackTriageState;
    // List recent commit shas + subjects; flag revert/reset-shaped commits
    // whose rollback-triage chain is absent.
    let log = std::process::Command::new("git")
        .args(["log", &format!("-{}", args.depth), "--format=%H%x1f%s"])
        .output();
    let log_text = match log {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).into_owned(),
        _ => {
            eprintln!("cargo antigen vcs scan: git log unavailable (not a repo, or git missing)");
            return ExitCode::from(2);
        }
    };
    let mut flagged = 0usize;
    let mut entries: Vec<(String, String, RollbackTriageState)> = Vec::new();
    for line in log_text.lines() {
        let Some((sha, subject)) = line.split_once('\u{1f}') else {
            continue;
        };
        // A revert-shaped subject is the v0.2 heuristic for "candidate
        // rollback" — the commit-trailer chain is then the real signal.
        let looks_like_rollback = subject.to_lowercase().contains("revert")
            || subject.to_lowercase().contains("rollback");
        if !looks_like_rollback {
            continue;
        }
        let state = RollbackTriageState::evaluate(&read_commit_trailers(sha));
        if !state.is_pass() {
            flagged += 1;
        }
        entries.push((sha.to_owned(), subject.to_owned(), state));
    }
    match args.format {
        OutputFormat::Json => {
            // Minimal JSON: array of {sha, subject, chain_pass}.
            let arr: Vec<_> = entries
                .iter()
                .map(|(sha, subject, state)| {
                    serde_json::json!({
                        "sha": sha,
                        "subject": subject,
                        "chain_pass": state.is_pass(),
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&arr).unwrap_or_else(|_| "[]".to_string())
            );
        }
        OutputFormat::Human => {
            if entries.is_empty() {
                println!(
                    "cargo antigen vcs scan: no revert/rollback-shaped commits in the last {} \
                     commits",
                    args.depth
                );
            } else {
                for (sha, subject, state) in &entries {
                    let short = &sha[..sha.len().min(8)];
                    let mark = if state.is_pass() { "ok " } else { "!! " };
                    println!("{mark}{short} {subject}");
                }
                println!();
                println!(
                    "{flagged} rollback-shaped commit(s) without a valid Triage-Decision chain"
                );
            }
        }
    }
    ExitCode::SUCCESS
}

fn run_vcs_branch_archive(args: VcsBranchArchiveArgs) -> ExitCode {
    if args.rationale.trim().is_empty() {
        eprintln!("cargo antigen vcs branch-archive: --rationale cannot be empty");
        return ExitCode::from(1);
    }
    // v0.2 advisory: print the sidecar JSON the adopter commits to
    // `.attest/vcs/branch-archive/<branch>.json` before deleting the branch.
    let sidecar = serde_json::json!({
        "branch": args.branch,
        "by_role": args.by,
        "rationale": args.rationale,
        "attested_at": chrono::Utc::now().to_rfc3339(),
    });
    println!(
        "{}",
        serde_json::to_string_pretty(&sidecar).unwrap_or_else(|_| "{}".to_string())
    );
    eprintln!();
    eprintln!(
        "Write this to .attest/vcs/branch-archive/{}.json and commit it BEFORE \
         deleting the branch (v0.2 advisory; in-place write is v0.2.x).",
        args.branch
    );
    ExitCode::SUCCESS
}

fn run_vcs_rollback_prepare(args: VcsRollbackPrepareArgs) -> ExitCode {
    use antigen::vcs::TriageDecision;
    if TriageDecision::parse_decision(&args.decision).is_none() {
        eprintln!(
            "cargo antigen vcs rollback-prepare: --decision {:?} is not a valid triage \
             decision (black|red|yellow|green|white)",
            args.decision
        );
        return ExitCode::from(1);
    }
    println!("Add this trailer to your rollback commit message (ADR-026 Amendment 4):");
    println!();
    println!("    Triage-Decision: {}", args.decision.to_lowercase());
    println!();
    println!(
        "Rolling back to {}. The Triage-Decision trailer is the commit-intent signal \
         the rollback-triage chain reads — NOT a source-code scan.",
        args.target
    );
    ExitCode::SUCCESS
}

fn run_vcs_attest_stub() -> ExitCode {
    println!("cargo antigen vcs attest: v0.2.x stub");
    println!();
    println!("Generic VCS attestation-sidecar recording lands in v0.2.x. For now,");
    println!("use `branch-archive` (branch-deletion attestation) or `rollback-prepare`");
    println!("(triage-commit trailer scaffolding). Per ADR-005 Amendment 2 honest-tier-");
    println!("naming: this stub does NOT silently pass.");
    ExitCode::from(2)
}

// ============================================================================
// cargo antigen mucosal-map (Mucosal Boundary Family, ADR-027 + Amendment 1)
// ============================================================================

#[derive(Debug, Parser)]
struct MucosalMapArgs {
    /// Workspace root (default: current directory).
    #[arg(long, default_value = ".")]
    root: PathBuf,
    /// Output format: human or json.
    #[arg(long, default_value = "human")]
    format: OutputFormat,
    /// List only declarations whose audit surfaced a concern.
    #[arg(long)]
    undefended: bool,
    /// List only `#[mucosal_tolerant]` (active-tolerance) declarations for
    /// periodic reviewer audit.
    #[arg(long)]
    tolerant: bool,
    /// Filter to a single `MucosalKind` (kebab-case, e.g. `user-input`).
    #[arg(long)]
    kind: Option<String>,
}

fn run_mucosal_map(args: MucosalMapArgs) -> ExitCode {
    use antigen::mucosal::MucosalKind;
    use antigen::scan::MucosalKindTag;

    if !args.root.is_dir() {
        eprintln!("error: expected a directory: {}", args.root.display());
        return ExitCode::from(2);
    }
    let report = match scan::scan_workspace(&args.root, None) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: scan failed: {e}");
            return ExitCode::from(2);
        }
    };
    let mucosal_audit = audit::audit_mucosal(&report);

    // Optional kind filter (validated against the sealed set).
    let kind_filter: Option<MucosalKind> = match args.kind.as_deref() {
        None => None,
        Some(k) => {
            let Some(mk) = MucosalKind::parse_kind(k) else {
                eprintln!(
                    "error: unknown MucosalKind {k:?}; expected a kebab-case variant \
                     (e.g. user-input, database-query, shell-argument)"
                );
                return ExitCode::from(2);
            };
            Some(mk)
        }
    };

    let entries: Vec<&antigen::audit::MucosalAudit> = mucosal_audit
        .audits
        .iter()
        .filter(|a| {
            if args.tolerant && a.declaration.tag != MucosalKindTag::MucosalTolerant {
                return false;
            }
            if args.undefended && a.hints.is_empty() {
                return false;
            }
            if let Some(kf) = kind_filter {
                // The scan stores the PascalCase final segment ("UserInput");
                // parse it back to a MucosalKind and compare enum values so
                // the --kind filter accepts any input form.
                let decl_kind = a
                    .declaration
                    .boundary_kind
                    .as_deref()
                    .and_then(MucosalKind::parse_kind);
                if decl_kind != Some(kf) {
                    return false;
                }
            }
            true
        })
        .collect();

    match args.format {
        OutputFormat::Json => {
            let arr: Vec<_> = entries
                .iter()
                .map(|a| {
                    serde_json::json!({
                        "tag": a.declaration.tag,
                        "boundary_kind": a.declaration.boundary_kind,
                        "file": a.declaration.file,
                        "line": a.declaration.line,
                        "hints": a.hints,
                    })
                })
                .collect();
            println!(
                "{}",
                serde_json::to_string_pretty(&arr).unwrap_or_else(|_| "[]".to_string())
            );
        }
        OutputFormat::Human => {
            if entries.is_empty() {
                println!("cargo antigen mucosal-map: no matching mucosal declarations");
            } else {
                for a in &entries {
                    let kind = a.declaration.boundary_kind.as_deref().unwrap_or("?");
                    let mark = if a.hints.is_empty() { "ok " } else { "!! " };
                    let file = a.declaration.file.display();
                    println!(
                        "{mark}{:<18} {kind:<20} {file}:{}",
                        format!("{:?}", a.declaration.tag),
                        a.declaration.line
                    );
                    for hint in &a.hints {
                        println!("       - {hint:?}");
                    }
                }
                println!();
                println!(
                    "{} declaration(s); {} clean, {} with concerns",
                    entries.len(),
                    entries.iter().filter(|a| a.hints.is_empty()).count(),
                    entries.iter().filter(|a| !a.hints.is_empty()).count(),
                );
            }
        }
    }
    ExitCode::SUCCESS
}

/// Parse `<crate>@<version>` into `(crate, version)`. Returns `None` on
/// any of: no `@`, empty crate, empty version, multiple `@`s, or characters
/// that could escape the `.attest/supply-chain/` directory (path traversal
/// guard: crate names must be `[a-zA-Z0-9_-]`, versions `[a-zA-Z0-9._+-]`).
fn parse_crate_at_version(s: &str) -> Option<(String, String)> {
    let (c, v) = s.split_once('@')?;
    if c.is_empty() || v.is_empty() || v.contains('@') {
        return None;
    }
    let crate_ok = c
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-');
    let version_ok = v
        .chars()
        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '+'));
    if !crate_ok || !version_ok {
        return None;
    }
    Some((c.to_string(), v.to_string()))
}

fn main() -> ExitCode {
    let cli = CargoCli::parse();
    let CargoSubcommand::Antigen(antigen_cli) = cli.command;

    match antigen_cli.command {
        AntigenSubcommand::Scan(args) => run_scan(args),
        AntigenSubcommand::New { name } => run_new(name),
        AntigenSubcommand::Vaccinate { antigen, pattern } => run_vaccinate(antigen, pattern),
        AntigenSubcommand::Audit(args) => run_audit(args),
        AntigenSubcommand::Attest(cli) => run_attest(cli),
        AntigenSubcommand::Tolerate(cli) => run_tolerate(cli),
        AntigenSubcommand::Oracle(cli) => run_oracle(cli),
        AntigenSubcommand::Verify(cli) => run_verify(cli),
        AntigenSubcommand::Vcs(cli) => run_vcs(cli),
        AntigenSubcommand::MucosalMap(args) => run_mucosal_map(args),
        AntigenSubcommand::Fingerprint(args) => run_fingerprint(args),
    }
}

// ============================================================================
// cargo antigen oracle handlers (ADR-021 oracle-as-artifact-class)
// ============================================================================

fn run_oracle(cli: OracleCli) -> ExitCode {
    match cli.command {
        OracleSubcommand::List(args) => run_oracle_list(args),
        OracleSubcommand::Status(args) => run_oracle_status(args),
        OracleSubcommand::Declare(args) => run_oracle_declare(args),
        OracleSubcommand::Complete(args) => run_oracle_complete(args),
        OracleSubcommand::Deprecate(args) => run_oracle_deprecate(args),
        OracleSubcommand::Retire(args) => run_oracle_retire(args),
        OracleSubcommand::Revoke(args) => run_oracle_revoke(args),
    }
}

fn oracle_json_path(root: &std::path::Path, id: &str) -> std::path::PathBuf {
    root.join(".antigen")
        .join("oracles")
        .join(format!("{id}.oracle.json"))
}

fn load_oracle(
    root: &std::path::Path,
    id: &str,
) -> Result<antigen_attestation::schema::Oracle, String> {
    let path = oracle_json_path(root, id);
    let content = std::fs::read_to_string(&path).map_err(|e| {
        format!(
            "error: oracle `{id}` not found at `{}`: {e}",
            path.display()
        )
    })?;
    serde_json::from_str(&content)
        .map_err(|e| format!("error: oracle `{id}` is not valid Oracle JSON: {e}"))
}

fn save_oracle(
    root: &std::path::Path,
    oracle: &antigen_attestation::schema::Oracle,
) -> Result<(), String> {
    // Tier-honesty: validate schema invariants BEFORE persisting to disk
    // (ADR-021 §D3 + Oracle::validate). Persisting an invalid oracle would
    // mean the audit later refuses to parse what the CLI wrote — a silent
    // tier-inversion. Catch at write time so the operator sees the
    // validation error immediately instead of at next audit.
    oracle
        .validate()
        .map_err(|e| format!("error: oracle validation failed: {e}"))?;
    let dir = root.join(".antigen").join("oracles");
    std::fs::create_dir_all(&dir).map_err(|e| {
        format!(
            "error: could not create oracle directory `{}`: {e}",
            dir.display()
        )
    })?;
    let path = oracle_json_path(root, &oracle.id);
    let json = serde_json::to_string_pretty(oracle)
        .map_err(|e| format!("error: failed to serialize oracle: {e}"))?;
    std::fs::write(&path, &json)
        .map_err(|e| format!("error: failed to write oracle `{}`: {e}", path.display()))?;
    Ok(())
}

fn resolve_steward_name(explicit: Option<&str>) -> Result<String, String> {
    explicit.map_or_else(
        || {
            let out = std::process::Command::new("git")
                .args(["config", "user.name"])
                .output();
            match out {
                Ok(o) if o.status.success() => {
                    Ok(String::from_utf8_lossy(&o.stdout).trim().to_owned())
                }
                _ => Err(
                    "error: --steward not provided and `git config user.name` failed".to_owned(),
                ),
            }
        },
        |s| Ok(s.to_owned()),
    )
}

fn run_oracle_list(args: OracleListArgs) -> ExitCode {
    let oracle_dir = args.root.join(".antigen").join("oracles");
    if !oracle_dir.exists() {
        eprintln!("No oracle records found under `{}`.", args.root.display());
        return ExitCode::SUCCESS;
    }
    let entries = match std::fs::read_dir(&oracle_dir) {
        Ok(e) => e,
        Err(e) => {
            eprintln!("error: could not read oracle directory: {e}");
            return ExitCode::from(2);
        }
    };
    let mut found = 0usize;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().is_some_and(|e| e == "json") {
            // Warn-and-continue on unreadable / corrupt oracle records rather
            // than silently skipping them. A silent skip lets a corrupt `.json`
            // collapse into the same "No oracle records found" + exit 0 as a
            // genuinely-empty directory — the adopter gets zero signal their
            // oracle data is broken (ATK-oracle-corrupt-json). Mirrors the
            // `attest list` warn-and-continue model.
            let content = match std::fs::read_to_string(&path) {
                Ok(c) => c,
                Err(e) => {
                    eprintln!("warning: could not read `{}`: {e}", path.display());
                    continue;
                }
            };
            let oracle = match serde_json::from_str::<antigen_attestation::schema::Oracle>(&content)
            {
                Ok(o) => o,
                Err(e) => {
                    eprintln!(
                        "warning: `{}` is not valid Oracle JSON: {e}",
                        path.display()
                    );
                    continue;
                }
            };
            match args.format {
                OutputFormat::Human => {
                    println!(
                        "{} [{:?}] — {} steward(s)",
                        oracle.id,
                        oracle.state,
                        oracle.stewards.len()
                    );
                }
                OutputFormat::Json => {
                    let obj = serde_json::json!({ "id": oracle.id, "state": format!("{:?}", oracle.state) });
                    println!("{obj}");
                }
            }
            found += 1;
        }
    }
    if found == 0 {
        eprintln!("No oracle records found under `{}`.", args.root.display());
    } else {
        eprintln!("{found} oracle(s) listed.");
    }
    ExitCode::SUCCESS
}

fn run_oracle_status(args: OracleStatusArgs) -> ExitCode {
    match load_oracle(&args.root, &args.id) {
        Ok(oracle) => {
            println!("Oracle: {}", oracle.id);
            println!("State:  {:?}", oracle.state);
            println!("Stewards ({}):", oracle.stewards.len());
            for s in &oracle.stewards {
                println!("  {} ({})", s.name, s.authorization_basis);
            }
            println!("Transitions ({}):", oracle.transitions.len());
            for t in &oracle.transitions {
                println!(
                    "  {}{} by {} on {}{}",
                    t.from, t.to, t.authorized_by, t.at, t.rationale
                );
            }
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("{e}");
            ExitCode::from(1)
        }
    }
}

/// Count the existing delta-chain depth for this signer since their last
/// Fresh-basis entry. CLI-SF-4 fix: a naive `take_while` on the reversed list
/// stops at the first non-(name+delta) entry, undercounting when other
/// signers have interleaved entries. Correct computation: find the last
/// Fresh entry for this signer, then count all subsequent delta entries
/// for this signer regardless of interleaving. Extracted from
/// `run_attest_delta` to keep that function under clippy's `too_many_lines`
/// threshold.
fn compute_delta_chain_depth(signers: &[antigen_attestation::Signer], signer_name: &str) -> u32 {
    let last_fresh_index = signers
        .iter()
        .enumerate()
        .filter(|(_, s)| s.name == signer_name && s.basis.is_fresh())
        .map(|(i, _)| i)
        .next_back();
    // No-Fresh case: caller's guard above already rejected this path; the `1`
    // here is defensive and unreachable in practice.
    last_fresh_index.map_or(1, |fresh_idx| {
        let count = signers[fresh_idx + 1..]
            .iter()
            .filter(|s| s.name == signer_name && s.basis.is_delta())
            .count();
        u32::try_from(count).unwrap_or(u32::MAX).saturating_add(1)
    })
}

/// Anti-laundering T2R-B/T2R-C: enforce minimum rationale character count at
/// CLI layer for delta attestations. The schema `validate()` also enforces
/// this at audit time, but catching here prevents writing a sidecar that
/// immediately fails validation (CLI-SF-3). Extracted from `run_attest_delta`
/// to keep that function under clippy's `too_many_lines` threshold.
fn validate_delta_rationale(rationale: &str) -> Result<(), ExitCode> {
    use antigen_attestation::schema::DEFAULT_DELTA_RATIONALE_MIN_CHARS;
    let trimmed = rationale.trim();
    if trimmed.is_empty() {
        eprintln!("error: --rationale must be non-empty (anti-laundering safeguard T2R-C)");
        return Err(ExitCode::from(1));
    }
    if trimmed.chars().count() < DEFAULT_DELTA_RATIONALE_MIN_CHARS {
        eprintln!(
            "error: --rationale is too short ({} chars); minimum is {} chars \
             (anti-laundering safeguard T2R-B). Rubber-stamp rationales are rejected.",
            trimmed.chars().count(),
            DEFAULT_DELTA_RATIONALE_MIN_CHARS,
        );
        return Err(ExitCode::from(1));
    }
    Ok(())
}

/// Build an [`antigen_attestation::schema::OracleRef`] from CLI args.
/// Extracted from `run_oracle_declare`
/// to keep that function under clippy's `too_many_lines` threshold. Returns
/// `Err(ExitCode)` on user-facing parse errors so the caller can propagate.
fn build_oracle_ref(
    kind: OracleRefKindArg,
    reference: &str,
) -> Result<antigen_attestation::schema::OracleRef, ExitCode> {
    use antigen_attestation::schema::OracleRef;
    match kind {
        OracleRefKindArg::LocalFile => Ok(OracleRef::LocalFile {
            path: std::path::PathBuf::from(reference),
            status_field: None,
            expected_status: None,
        }),
        OracleRefKindArg::Url => Ok(OracleRef::Url {
            url: reference.to_owned(),
            label: None,
        }),
        OracleRefKindArg::Doi => Ok(OracleRef::Doi {
            doi: reference.to_owned(),
            section: None,
        }),
        OracleRefKindArg::Arxiv => Ok(OracleRef::Arxiv {
            arxiv_id: reference.to_owned(),
            section: None,
        }),
        OracleRefKindArg::GithubIssue => {
            let parts: Vec<&str> = reference.splitn(2, '#').collect();
            if parts.len() != 2 {
                eprintln!("error: github-issue reference must be `owner/repo#N`");
                return Err(ExitCode::from(1));
            }
            let Ok(issue) = parts[1].parse::<u32>() else {
                eprintln!("error: issue number must be a positive integer");
                return Err(ExitCode::from(1));
            };
            Ok(OracleRef::GitHubIssue {
                repo: parts[0].to_owned(),
                issue,
            })
        }
        OracleRefKindArg::Other => Ok(OracleRef::Other {
            subkind: "other".to_owned(),
            reference: reference.to_owned(),
            label: None,
        }),
    }
}

fn run_oracle_declare(args: OracleDeclareArgs) -> ExitCode {
    use antigen_attestation::schema::{Oracle, OracleState, OracleVersion, Provenance, Steward};
    use chrono::Local;

    if args.rationale.trim().is_empty() {
        eprintln!("error: --rationale must be non-empty (Amendment 2 discipline)");
        return ExitCode::from(1);
    }

    // Resolve stewards: either from --steward flags or git config.
    let mut steward_names = args.steward.clone();
    if steward_names.is_empty() {
        match resolve_steward_name(None) {
            Ok(name) => steward_names.push(name),
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(1);
            }
        }
    }
    if steward_names.len() < 2 {
        eprintln!(
            "warning: only {} steward(s) declared; minimum 2 required for oracle to be transitioned \
             to Complete (ATK-021-13 succession mitigation). Add a second steward via --steward.",
            steward_names.len()
        );
    }

    let stewards: Vec<Steward> = steward_names
        .iter()
        .map(|name| Steward {
            name: name.clone(),
            role: None,
            authorization_basis: args.rationale.clone(),
        })
        .collect();

    let reference = match build_oracle_ref(args.kind, &args.reference) {
        Ok(r) => r,
        Err(code) => return code,
    };

    let today = Local::now().date_naive();
    // Declare does NOT write a creation-as-transition. The creation event is
    // recorded by `created: Provenance` (recorded_by + at). The transitions log
    // captures STATE-MACHINE TRANSITIONS only — Draft is the constructor state,
    // so the first transition entry is the eventual Draft→Complete written by
    // `oracle complete`. The schema validator (Oracle::validate) enforces that
    // the first transition's `from` matches the implicit initial state
    // `"draft"`; a synthetic `none → draft` creation-transition would fail
    // validation. ATK-021 schema-CLI integration test:
    // atk_a3_oracle_cli_declare_initial_state_is_draft + ..._full_lifecycle_round_trip.
    let oracle = Oracle {
        id: args.id.clone(),
        reference,
        state: OracleState::Draft,
        stewards,
        created: Provenance {
            recorded_by: steward_names[0].clone(),
            at: today,
        },
        version: OracleVersion {
            pinned: args.version.unwrap_or_else(|| format!("declared-{today}")),
            pinned_at: today,
        },
        transitions: vec![],
        extensions: std::collections::BTreeMap::default(),
    };

    match save_oracle(&args.root, &oracle) {
        Ok(()) => {
            eprintln!("Oracle `{}` created in DRAFT state.", args.id);
            eprintln!("Path: {}", oracle_json_path(&args.root, &args.id).display());
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("{e}");
            ExitCode::from(2)
        }
    }
}

const fn oracle_state_discriminant(
    state: &antigen_attestation::schema::OracleState,
) -> &'static str {
    use antigen_attestation::schema::OracleState;
    match state {
        OracleState::Draft => "draft",
        OracleState::Complete => "complete",
        OracleState::Deprecated { .. } => "deprecated",
        OracleState::Retired { .. } => "retired",
        OracleState::Revoked { .. } => "revoked",
    }
}

fn run_oracle_transition(
    root: &std::path::Path,
    id: &str,
    steward: Option<String>,
    rationale: &str,
    new_state: antigen_attestation::schema::OracleState,
) -> ExitCode {
    use antigen_attestation::schema::StateTransition;
    use chrono::Local;

    if rationale.trim().is_empty() {
        eprintln!("error: --rationale must be non-empty (Amendment 2 discipline)");
        return ExitCode::from(1);
    }
    let steward_name = match resolve_steward_name(steward.as_deref()) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };
    let mut oracle = match load_oracle(root, id) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };
    // Validate steward is in the steward list (ATK-021-15).
    if !oracle.stewards.iter().any(|s| s.name == steward_name) {
        eprintln!(
            "error: `{steward_name}` is not a declared steward of oracle `{id}`.\n\
             Declared stewards: {}",
            oracle
                .stewards
                .iter()
                .map(|s| s.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
        return ExitCode::from(1);
    }
    // Derive the `from` label from the oracle's CURRENT state (not a hardcoded
    // string per call-site). This is what the schema validator expects per
    // ADR-021 §D3 — the `from` of transition N must match the `to` of
    // transition N-1 (or the implicit "draft" initial state when N=1).
    let from_label = oracle_state_discriminant(&oracle.state).to_owned();
    let to_label = oracle_state_discriminant(&new_state).to_owned();
    let today = Local::now().date_naive();
    oracle.transitions.push(StateTransition {
        from: from_label.clone(),
        to: to_label.clone(),
        authorized_by: steward_name.clone(),
        at: today,
        rationale: rationale.to_owned(),
    });
    oracle.state = new_state;
    match save_oracle(root, &oracle) {
        Ok(()) => {
            eprintln!("Oracle `{id}` transitioned {from_label}{to_label} by {steward_name}.");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("{e}");
            ExitCode::from(2)
        }
    }
}

fn run_oracle_complete(args: OracleCompleteArgs) -> ExitCode {
    use antigen_attestation::schema::{OracleState, OracleVersion};
    use chrono::Local;

    // Load oracle to update version pin at completion time.
    let mut oracle = match load_oracle(&args.root, &args.id) {
        Ok(o) => o,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };
    oracle.version = OracleVersion {
        pinned: args.version.clone(),
        pinned_at: Local::now().date_naive(),
    };
    match save_oracle(&args.root, &oracle) {
        Ok(()) => {}
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    }
    run_oracle_transition(
        &args.root,
        &args.id,
        args.steward,
        &args.rationale,
        OracleState::Complete,
    )
}

fn run_oracle_deprecate(args: OracleDeprecateArgs) -> ExitCode {
    use antigen_attestation::schema::OracleState;
    let new_state = OracleState::Deprecated {
        superseded_by: args.superseded_by,
        reason: args.rationale.clone(),
    };
    run_oracle_transition(
        &args.root,
        &args.id,
        args.steward,
        &args.rationale,
        new_state,
    )
}

fn run_oracle_retire(args: OracleRetireArgs) -> ExitCode {
    use antigen_attestation::schema::OracleState;
    let steward_name = match resolve_steward_name(args.steward.as_deref()) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };
    let new_state = OracleState::Retired {
        reason: args.rationale.clone(),
        retired_by: steward_name.clone(),
    };
    run_oracle_transition(
        &args.root,
        &args.id,
        Some(steward_name),
        &args.rationale,
        new_state,
    )
}

fn run_oracle_revoke(args: OracleRevokeArgs) -> ExitCode {
    use antigen_attestation::schema::OracleState;
    let steward_name = match resolve_steward_name(args.steward.as_deref()) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };
    let new_state = OracleState::Revoked {
        reason: args.rationale.clone(),
        revoked_by: steward_name.clone(),
        invalidates_prior_attestations: args.invalidates_prior,
    };
    run_oracle_transition(
        &args.root,
        &args.id,
        Some(steward_name),
        &args.rationale,
        new_state,
    )
}

/// Parse the `--category` CLI argument (ADR-028 §CLI integration). Returns
/// `Ok(None)` when no filter was supplied, `Ok(Some(cat))` for a valid
/// category string, and `Err(())` (after printing a diagnostic) for an
/// unrecognized value.
fn parse_category_filter(
    raw: Option<&str>,
) -> Result<Option<antigen::category::AntigenCategory>, ()> {
    let Some(s) = raw else {
        return Ok(None);
    };
    antigen::category::AntigenCategory::parse_category(s)
        .map(Some)
        .ok_or_else(|| {
            eprintln!(
                "error: unrecognized --category `{s}`; \
                 expected `substrate-alignment` or `functional-correctness`"
            );
        })
}

/// Filter a scan report in place to antigen declarations of `cat` (ADR-028
/// §CLI integration). A hybrid antigen (both categories) matches either
/// filter. Antigens with an absent category default to `FunctionalCorrectness`
/// per ADR-028 §v0.2-backward-compat, so they match the functional-correctness
/// filter. Presentations, immunities, and tolerations addressing a dropped
/// antigen are pruned so the filtered view stays internally consistent.
fn filter_report_by_category(
    report: &mut scan::ScanReport,
    cat: antigen::category::AntigenCategory,
) {
    use antigen::category::AntigenCategory;

    let matches = |decl_category: &[AntigenCategory]| -> bool {
        if decl_category.is_empty() {
            // Absent category defaults to FunctionalCorrectness.
            cat == AntigenCategory::FunctionalCorrectness
        } else {
            decl_category.contains(&cat)
        }
    };

    report.antigens.retain(|a| matches(&a.category));
    let kept: std::collections::HashSet<String> = report
        .antigens
        .iter()
        .map(|a| a.type_name.clone())
        .collect();

    report
        .presentations
        .retain(|p| kept.contains(&p.antigen_type));
    report.immunities.retain(|i| kept.contains(&i.antigen_type));
    report.tolerances.retain(|t| kept.contains(&t.antigen_type));
}

fn run_scan(args: ScanArgs) -> ExitCode {
    if !args.root.exists() {
        eprintln!("error: path does not exist: {}", args.root.display());
        return ExitCode::from(2);
    }
    if !args.root.is_dir() {
        eprintln!(
            "error: expected a directory, got a file: {}",
            args.root.display()
        );
        return ExitCode::from(2);
    }

    // ADR-028 §CLI integration: --category filters to a single category.
    let Ok(category_filter) = parse_category_filter(args.category.as_deref()) else {
        return ExitCode::from(2);
    };

    eprintln!("Scanning workspace: {}", args.root.display());

    let mut report = match scan::scan_workspace(&args.root, None) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: scan failed: {e}");
            return ExitCode::from(2);
        }
    };

    if let Some(cat) = category_filter {
        filter_report_by_category(&mut report, cat);
    }

    let unaddressed = report.unaddressed_presentations();

    // A3 D3: optional cross-crate dep enumeration + per-crate scan. Per
    // navigator's 2026-05-09 ruling, deps are scanned independently — no
    // cross-crate addresses() matching in v0.1. Each dep report stands on
    // its own; the union appears under `dep_reports` in JSON output.
    let dep_reports = if args.include_deps {
        match scan::enumerate_dep_crate_roots(&args.root, false) {
            Ok(roots) => {
                eprintln!("Scanning {} dependency crate(s)...", roots.len());
                let mut out: Vec<DepScanResult> = Vec::with_capacity(roots.len());
                for dep in roots {
                    let mut r = match scan::scan_workspace(&dep.crate_root, None) {
                        Ok(r) => r,
                        Err(e) => {
                            eprintln!(
                                "  warning: scan failed for `{}` v{}: {e}",
                                dep.package_name, dep.version
                            );
                            continue;
                        }
                    };
                    // ADR-017 Option A: stamp canonical_path post-scan in
                    // the `"<crate-name>@<version>"` format. The
                    // scan_workspace function is a pure directory scanner
                    // and does not know which crate it just scanned; the
                    // driver carries the crate-graph context and stamps
                    // here.
                    let crate_id = format!("{}@{}", dep.package_name, dep.version);
                    r.stamp_canonical_path(&crate_id);
                    out.push(DepScanResult {
                        package_name: dep.package_name,
                        version: dep.version,
                        origin: dep.origin,
                        report: r,
                    });
                }
                Some(out)
            }
            Err(e) => {
                eprintln!("error: cargo metadata failed: {e}");
                return ExitCode::from(2);
            }
        }
    } else {
        None
    };

    match args.format {
        OutputFormat::Human => {
            print_human_report(&report, &unaddressed);
            if let Some(deps) = dep_reports.as_ref() {
                print_human_dep_summary(deps);
            }
        }
        OutputFormat::Json => match serde_json::to_string_pretty(&JsonReport {
            report: &report,
            unaddressed: &unaddressed,
            orphaned_lineage_edges: report.orphaned_lineage_edges(),
            dangling_child_lineage_edges: report.dangling_child_lineage_edges(),
            dep_reports: dep_reports.as_deref(),
        }) {
            Ok(s) => println!("{s}"),
            Err(e) => {
                eprintln!("error: failed to serialize report: {e}");
                return ExitCode::from(2);
            }
        },
    }

    // --strict gates only on unaddressed EXPLICIT presentations (match_kind == ExplicitMarker)
    // and orphaned tolerances. Fingerprint matches are informational — they're potential
    // vulnerabilities that require human triage, not CI-enforced gates.
    // Gating on ALL unaddressed (including FingerprintMatch) produces a silent mismatch:
    // the output says "All explicit presentations are addressed" but exits 1 because of
    // fingerprint matches, causing CI to fail with a confusing human-readable message.
    let unaddressed_explicit_count = unaddressed
        .iter()
        .filter(|u| u.presentation.match_kind == antigen::scan::MatchKind::ExplicitMarker)
        .count();
    // Orphaned/dangling lineage edges are structural defects (a #[descended_from]
    // pointing at a non-existent parent, or on a non-antigen child) — gate on them
    // under --strict alongside unaddressed explicit presentations and orphaned
    // tolerances.
    let lineage_broken = !report.orphaned_lineage_edges().is_empty()
        || !report.dangling_child_lineage_edges().is_empty();
    if args.strict
        && (unaddressed_explicit_count > 0
            || !report.orphaned_tolerances().is_empty()
            || lineage_broken)
    {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

/// Render a brief summary of dep scan results in human format. Per
/// navigator's ruling, dep reports are independent — we only summarize
/// counts here (full per-crate detail goes through --format json).
fn print_human_dep_summary(deps: &[DepScanResult]) {
    println!();
    println!("Cross-crate dep scan ({} crates):", deps.len());
    let mut deps_with_antigens: Vec<&DepScanResult> = deps
        .iter()
        .filter(|d| !d.report.antigens.is_empty())
        .collect();
    deps_with_antigens.sort_by_key(|d| d.package_name.clone());
    if deps_with_antigens.is_empty() {
        println!("  No antigen declarations found in any dependency.");
        println!("  (P5 finding 2026-05-09: zero `#[antigen(...)]` instances in the wild.)");
    } else {
        for d in deps_with_antigens {
            println!(
                "  {} v{}: {} antigen(s), {} presentation(s), {} immunity claim(s)",
                d.package_name,
                d.version,
                d.report.antigens.len(),
                d.report.presentations.len(),
                d.report.immunities.len()
            );
        }
    }
}

fn print_human_report(report: &scan::ScanReport, unaddressed: &[scan::UnaddressedPresentation]) {
    use antigen::scan::MatchKind;

    let explicit_count = report
        .presentations
        .iter()
        .filter(|p| p.match_kind == MatchKind::ExplicitMarker)
        .count();
    let fingerprint_count = report
        .presentations
        .iter()
        .filter(|p| p.match_kind == MatchKind::FingerprintMatch)
        .count();

    println!();
    println!(
        "Scanned {} files, found {} antigen-related declarations:",
        report.files_scanned,
        report.total_declarations()
    );
    println!("  - {} antigen declarations", report.antigens.len());
    println!("  - {} explicit #[presents] markers", explicit_count);
    if fingerprint_count > 0 {
        println!("  - {fingerprint_count} fingerprint matches (candidate sites — see below)");
    }
    if !report.tolerances.is_empty() {
        println!(
            "  - {} tolerated sites (#[antigen_tolerance])",
            report.tolerances.len()
        );
    }
    if !report.defenses.is_empty() {
        println!("  - {} #[defended_by] declarations", report.defenses.len());
    }
    if !report.immunities.is_empty() {
        println!(
            "  - {} #[immune] declarations (deprecated — migrate to #[defended_by]/#[presents])",
            report.immunities.len()
        );
    }
    if !report.parse_failures.is_empty() {
        println!(
            "  - {} parse failures (see --format json for details)",
            report.parse_failures.len()
        );
    }
    println!();

    print_fingerprint_matches(report);
    print_orphaned_tolerances(report);
    print_lineage_integrity(report);
    print_unaddressed(unaddressed);
}

/// Render `#[descended_from]` lineage-integrity defects: edges whose parent
/// antigen is not declared in the workspace (orphaned) and edges whose child is
/// not an `#[antigen]` declaration (dangling). Both are computed by the scan
/// layer (`orphaned_lineage_edges` / `dangling_child_lineage_edges`) but were
/// never rendered — the `AuditVerdictComputedButNotDelivered` delivery-arm
/// severance (same shape as dogfood antigen #25). A `#[descended_from(P)]` that
/// names a parent the workspace doesn't declare is a structurally-broken lineage
/// claim; surfacing it is the whole point of the check.
fn print_lineage_integrity(report: &scan::ScanReport) {
    let orphaned = report.orphaned_lineage_edges();
    let dangling = report.dangling_child_lineage_edges();
    if orphaned.is_empty() && dangling.is_empty() {
        return;
    }
    if !orphaned.is_empty() {
        println!(
            "{} orphaned lineage edge(s) — #[descended_from] names a parent antigen \
             not declared in the workspace:",
            orphaned.len()
        );
        println!();
        for e in &orphaned {
            println!(
                "  {}:{}  {}{} [parent antigen `{}` not found]",
                e.file.display(),
                e.line,
                e.child,
                e.parent,
                e.parent
            );
        }
        println!();
    }
    if !dangling.is_empty() {
        println!(
            "{} dangling lineage edge(s) — the child of a #[descended_from] is not \
             itself an #[antigen] declaration:",
            dangling.len()
        );
        println!();
        for e in &dangling {
            println!(
                "  {}:{}  {}{} [child `{}` has no #[antigen] declaration]",
                e.file.display(),
                e.line,
                e.child,
                e.parent,
                e.child
            );
        }
        println!();
    }
    println!(
        "  A lineage claim must resolve to real declarations on both ends. Either \
         declare the missing antigen, or remove/correct the #[descended_from] edge."
    );
    println!();
}

/// Render deferred-defense declarations (`#[anergy]` / `#[immunosuppress]` /
/// `#[poxparty]` / `#[orient]`) LOUDLY (ADR-023 + forward/suppression-loud-must-
/// be-removed). These are intentional dev permissions to proceed with a known
/// defense gap — they do NOT block the build and do NOT auto-expire, but the
/// audit must ALWAYS announce active ones prominently so they cannot become
/// silent accumulated debt. `audit_deferred_defenses` computes the state; this
/// is its delivery arm (it was computed in the library but never reached the
/// CLI — the `AuditVerdictComputedButNotDelivered` severance). Each must be
/// EXPLICITLY REMOVED to resolve; the audit keeps surfacing it until then.
fn print_deferred_defenses_loud(report: &audit::DeferredDefenseAuditReport) {
    use antigen::audit::AuditHint;
    use antigen::scan::DeferredDefenseKind;

    if report.audits.is_empty() {
        return;
    }

    println!(
        "{} deferred-defense declaration(s) — intentional, accepted defense gaps \
         (NOT blocking; must be EXPLICITLY removed to resolve):",
        report.audits.len()
    );
    println!(
        "  {} active · {} past-deadline · {} stale",
        report.active_count, report.expired_count, report.stale_count
    );
    println!();

    for a in &report.audits {
        let d = &a.declaration;
        let kind = match d.kind {
            DeferredDefenseKind::Anergy => "anergy",
            DeferredDefenseKind::Immunosuppress => "immunosuppress",
            DeferredDefenseKind::Poxparty => "poxparty",
            DeferredDefenseKind::Orient => "orient",
        };
        let antigen = d.antigen_type.as_deref().unwrap_or("(unlinked)");
        // State marker from the audit hint — past-deadline/stale states are
        // louder so an accumulated old suppression stands out from a fresh one.
        let state = match a.hint {
            AuditHint::AnergyStale => "STALE — long past review",
            AuditHint::AnergyCostimulationNotArrived
            | AuditHint::ImmunosuppressExpired
            | AuditHint::PoxpartyOutcomePending
            | AuditHint::OrientPendingActionRequired => "PAST DEADLINE — action required",
            // All active hints (AnergyActive / ImmunosuppressActive /
            // PoxpartyActive / OrientActive) — and any future deferred-defense
            // hint not yet classified expired/stale — read as active.
            _ => "active",
        };
        println!(
            "  {}:{}  #[{kind}] on `{antigen}` — {state}",
            d.file.display(),
            d.line
        );
        if !d.text.trim().is_empty() {
            println!("      reason: {}", d.text.trim());
        }
        if let Some(until) = d.until.as_deref() {
            if !until.is_empty() {
                println!("      until: {until}");
            }
        }
    }
    println!();
    println!(
        "  These suppress the BLOCK, never the GAP — the failure-class is still \
         present and undefended at these sites. Remove the declaration when the \
         defense lands (or the gap is genuinely accepted forever)."
    );
    println!();
}

/// Render concern hints for ADR-024 convergent-evidence declarations
/// (`#[diagnostic]` / `#[clonal]` / `#[igg]` / `#[crossreactive]` / etc.). The
/// library computes these (modality-insufficient, class-collapsed, clonal
/// fixed-seed, igg identity-collapse, …) but the CLI never delivered them — the
/// `AuditVerdictComputedButNotDelivered` severance. Render only declarations with
/// concerns; a clean convergent declaration is background, not a TODO.
fn print_convergent_evidence_concerns(report: &audit::ConvergentEvidenceAuditReport) {
    if report.concern_count == 0 {
        return;
    }
    println!(
        "{} convergent-evidence declaration(s) with concerns (ADR-024):",
        report.concern_count
    );
    println!();
    for a in &report.audits {
        if a.hints.is_empty() {
            continue;
        }
        let d = &a.declaration;
        let hints = a
            .hints
            .iter()
            .map(audit_hint_kebab)
            .collect::<Vec<_>>()
            .join(", ");
        println!(
            "  {}:{}  #[{}] — {hints}",
            d.file.display(),
            d.line,
            convergent_kind_str(&d.kind)
        );
    }
    println!();
}

/// Render concern hints for ADR-024 recurrent-emergence declarations
/// (`#[itch]` / `#[recurrence_anchor]` / `#[crystallize]` / `#[chronic]` /
/// `#[saturate]` / `#[strand]`). Same severance fix as the convergent surface:
/// the library computes the hints (recurrence-anchor-no-itch-precondition,
/// chronic-signal-past-review-date, …); deliver them. Concerns only.
fn print_recurrent_concerns(report: &audit::RecurrentAuditReport) {
    if report.concern_count == 0 {
        return;
    }
    println!(
        "{} recurrent-emergence declaration(s) with concerns (ADR-024):",
        report.concern_count
    );
    println!();
    for a in &report.audits {
        if a.hints.is_empty() {
            continue;
        }
        let d = &a.declaration;
        let hints = a
            .hints
            .iter()
            .map(audit_hint_kebab)
            .collect::<Vec<_>>()
            .join(", ");
        let label = d
            .antigen_type
            .as_deref()
            .or(d.name.as_deref())
            .unwrap_or("(unlinked)");
        println!(
            "  {}:{}  #[{}] `{label}` — {hints}",
            d.file.display(),
            d.line,
            recurrent_kind_str(d.kind)
        );
    }
    println!();
}

/// Render the `#[descended_from]` lineage-fidelity advisory (scientist
/// 2026-05-27: ADVISORY for v0.3). Flags edges where the child antigen's
/// fingerprint is detectably NOT a refinement of the parent's. Non-blocking —
/// it does NOT affect the exit code; it surfaces a lineage claim that doesn't
/// survive the structural check (the MHC-restriction / negative-selection
/// cognate). Quiet when no divergences (advisory = signal, not noise).
fn print_lineage_fidelity_advisory(report: &audit::LineageFidelityAuditReport) {
    if report.divergences.is_empty() {
        return;
    }
    println!(
        "{} #[descended_from] lineage(s) whose child fingerprint does not refine \
         the parent (ADVISORY — lineage-fidelity, ADR-029-adjacent):",
        report.divergences.len()
    );
    println!();
    for d in &report.divergences {
        println!(
            "  {}:{}  {}{}{}",
            d.file.display(),
            d.line,
            d.child,
            d.parent,
            d.detail
        );
    }
    println!();
    println!(
        "  A `#[descended_from(Parent)]` claims the child is a more-specific case of \
         the parent's failure-class; if the child's fingerprint matches items the \
         parent's does not, the lineage is structurally unsound. Advisory only in \
         v0.3 (hard-fail deferred to a future ADR — biology: negative selection is \
         strict). Tighten the child's fingerprint, or correct the lineage edge."
    );
    println!();
}

/// Macro-keyword string for a convergent-evidence kind (display only).
const fn convergent_kind_str(kind: &antigen::scan::ConvergentEvidenceKind) -> &'static str {
    use antigen::scan::ConvergentEvidenceKind as K;
    match kind {
        K::Diagnostic => "diagnostic",
        K::Clonal => "clonal",
        K::Igg => "igg",
        K::Crossreactive => "crossreactive",
        K::Polyclonal => "polyclonal",
        K::Monoclonal => "monoclonal",
        K::Adcc => "adcc",
    }
}

/// Macro-keyword string for a recurrent-emergence kind (display only).
const fn recurrent_kind_str(kind: antigen::scan::RecurrentKind) -> &'static str {
    use antigen::scan::RecurrentKind as K;
    match kind {
        K::Itch => "itch",
        K::RecurrenceAnchor => "recurrence_anchor",
        K::Crystallize => "crystallize",
        K::Chronic => "chronic",
        K::Saturate => "saturate",
        K::Strand => "strand",
    }
}

/// Render an `AuditHint` as its serde kebab-case key for human concern lines.
/// (The hint's `Serialize` impl is kebab-case; reuse it so the human string
/// matches the JSON + the ADR vocabulary exactly.)
fn audit_hint_kebab(hint: &audit::AuditHint) -> String {
    serde_json::to_value(hint)
        .ok()
        .and_then(|v| v.as_str().map(str::to_owned))
        .unwrap_or_else(|| format!("{hint:?}"))
}

/// Human scan output shows at most this many fingerprint-match detail lines per
/// antigen type, then a "+N more" summary pointing at `--format json`.
///
/// Fingerprint matches are the FILTER half of antigen's filter/proof split
/// (glossary): expected, noisy *candidate* sites the witness layer refines —
/// not a TODO list. On antigen's own tree these number ~18K; an unbounded
/// per-site wall teaches a newcomer the tool is noise (the opposite of
/// onboarding). The cap mirrors rustc's "...and N more" and clippy's per-lint
/// grouping. `--format json` stays exhaustive for CI gates.
const MAX_FINGERPRINT_MATCHES_PER_ANTIGEN: usize = 10;

fn print_fingerprint_matches(report: &scan::ScanReport) {
    use antigen::scan::MatchKind;
    use std::collections::BTreeMap;

    let fp_matches: Vec<_> = report
        .presentations
        .iter()
        .filter(|p| p.match_kind == MatchKind::FingerprintMatch)
        .collect();
    if fp_matches.is_empty() {
        return;
    }

    // Group by antigen type so the cap is per-antigen (one noisy antigen can't
    // crowd out the others), and so the summary reads per the design role.
    let mut by_antigen: BTreeMap<&str, Vec<&&scan::Presentation>> = BTreeMap::new();
    for p in &fp_matches {
        by_antigen
            .entry(p.antigen_type.as_str())
            .or_default()
            .push(p);
    }

    println!(
        "{} fingerprint match(es) across {} antigen type(s) — candidate sites \
         (expected noise; the witness layer refines them, per the filter/proof split). \
         Not a TODO list.",
        fp_matches.len(),
        by_antigen.len()
    );
    println!();

    for (antigen_type, sites) in &by_antigen {
        for p in sites.iter().take(MAX_FINGERPRINT_MATCHES_PER_ANTIGEN) {
            println!(
                "  {}:{}  {} on {} [fingerprint match]",
                p.file.display(),
                p.line,
                p.antigen_type,
                p.item_kind
            );
        }
        if let Some(extra) = sites
            .len()
            .checked_sub(MAX_FINGERPRINT_MATCHES_PER_ANTIGEN)
            .filter(|n| *n > 0)
        {
            println!(
                "  … +{extra} more `{antigen_type}` candidate(s) — `cargo antigen scan \
                 --format json` for the full list."
            );
        }
    }
    println!();
    println!(
        "  These are CANDIDATES, not failures. If a site genuinely presents the \
         failure-class, acknowledge it:"
    );
    println!("    #[presents(<antigen>)] to mark the site explicitly,");
    println!("      then defend it: #[defended_by(<antigen>)] on a test (code-tier), or");
    println!("      #[presents(<antigen>, requires = ...)] for substrate-witness evidence,");
    println!("    #[antigen_tolerance(<antigen>, rationale = \"...\")] to document intent.");
    println!();
}

fn print_orphaned_tolerances(report: &scan::ScanReport) {
    let orphans = report.orphaned_tolerances();
    if orphans.is_empty() {
        return;
    }
    println!(
        "{} orphaned tolerance(s) — antigen no longer declared in workspace:",
        orphans.len()
    );
    println!();
    for t in &orphans {
        println!(
            "  {}:{}  {} [tolerance for unknown antigen]",
            t.file.display(),
            t.line,
            t.antigen_type
        );
    }
    println!();
    println!("  Remove or update these tolerances — the antigen they suppress is gone.");
    println!();
}

fn print_unaddressed(unaddressed: &[scan::UnaddressedPresentation]) {
    use antigen::scan::MatchKind;
    let explicit_unaddressed: Vec<_> = unaddressed
        .iter()
        .filter(|u| u.presentation.match_kind == MatchKind::ExplicitMarker)
        .collect();
    if explicit_unaddressed.is_empty() {
        println!("All explicit presentations are addressed.");
        return;
    }
    println!(
        "{} unaddressed explicit presentation(s):",
        explicit_unaddressed.len()
    );
    println!();
    for u in &explicit_unaddressed {
        let p = &u.presentation;
        println!(
            "  {}:{}  {} on {}",
            p.file.display(),
            p.line,
            p.antigen_type,
            p.item_kind
        );
        if !u.antigen_known {
            println!(
                "    note: antigen `{}` was not declared in the scanned workspace",
                p.antigen_type
            );
        }
    }
    println!();
    println!("To address each site, use the antigen type shown above:");
    println!("  #[defended_by(<antigen>)] on a test that exercises the defense (code-tier),");
    println!(
        "  OR #[presents(<antigen>, requires = ...)] on the site for substrate-witness evidence,"
    );
    println!("  OR #[antigen_tolerance(<antigen>, rationale = \"...\")] to document intent.");
}

#[derive(serde::Serialize)]
struct JsonReport<'a> {
    report: &'a scan::ScanReport,
    unaddressed: &'a [scan::UnaddressedPresentation],
    /// `#[descended_from]` edges whose parent antigen is not declared in the
    /// workspace (orphaned) — a structurally-broken lineage claim. Computed via
    /// `ScanReport::orphaned_lineage_edges()` and attached here (sibling to
    /// `unaddressed`, same computed-then-attached pattern) so the JSON surface
    /// DELIVERS the verdict the scan layer computes. Empty vec when sound.
    orphaned_lineage_edges: Vec<&'a scan::LineageEdge>,
    /// `#[descended_from]` edges whose child is not itself an `#[antigen]`
    /// declaration (dangling). Computed via `dangling_child_lineage_edges()`.
    dangling_child_lineage_edges: Vec<&'a scan::LineageEdge>,
    /// A3 D3: when `--include-deps` is set, one entry per scanned dep
    /// crate. `None` (skipped in JSON output via `skip_serializing_if`)
    /// when the flag wasn't passed — preserves byte-identical output for
    /// existing consumers.
    #[serde(skip_serializing_if = "Option::is_none")]
    dep_reports: Option<&'a [DepScanResult]>,
}

/// Per-dependency scan result returned by the `--include-deps` mode of
/// `cargo antigen scan`. Each dep is scanned independently — per navigator's
/// 2026-05-09 ruling on cross-crate scope, no cross-crate `addresses()`
/// matching happens here (ATK-A3-005 / module-path-qualified `ItemTarget`
/// is an ADR-class decision deferred to aristotle Phase 1-8).
#[derive(serde::Serialize)]
struct DepScanResult {
    package_name: String,
    version: String,
    origin: scan::CrateOrigin,
    report: scan::ScanReport,
}

fn run_new(name: String) -> ExitCode {
    eprintln!(
        "cargo-antigen new {} — design phase\n\
         \n\
         Antigen scaffolding (interactive scaffolding for a new declaration) is\n\
         under design. The eventual command will:\n\
           - Prompt for family (one of the 8 first-principles classes or custom)\n\
           - Prompt for fingerprint (assist with structural pattern composition)\n\
           - Prompt for witness type (test, proptest, lint, formal-verification)\n\
           - Generate a starter declaration file in your project's antigen module\n\
         \n\
         For now, please write antigen declarations by hand. See the project's\n\
         docs/expedition/conventions.md for naming guidance.\n",
        name
    );
    ExitCode::FAILURE
}

fn run_vaccinate(antigen: String, pattern: String) -> ExitCode {
    eprintln!(
        "cargo-antigen vaccinate {} {} — design phase\n\
         \n\
         Vaccination (apply known immunity pattern across a structural family) is\n\
         under design. The eventual command will:\n\
           - Search the workspace for items matching `pattern`\n\
           - For each match without existing immunity, scaffold a witness stub\n\
           - Add #[presents] and #[immune] markers atomically with confirmation\n\
         \n\
         For now, apply immunity manually per site.\n",
        antigen, pattern
    );
    ExitCode::FAILURE
}

/// One scanned site's fingerprint, for `cargo antigen fingerprint` output.
#[derive(serde::Serialize)]
struct FingerprintMatch {
    antigen_type: String,
    item_path: String,
    /// `"immune"` or `"presents"` — which kind of declaration this site is.
    site_kind: &'static str,
    structural_fingerprint: String,
    file: String,
    line: usize,
}

fn run_fingerprint(args: FingerprintArgs) -> ExitCode {
    if !args.root.exists() {
        eprintln!("error: path does not exist: {}", args.root.display());
        return ExitCode::from(2);
    }

    let report = match scan::scan_workspace(&args.root, None) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: scan failed: {e}");
            return ExitCode::from(2);
        }
    };

    let antigen_filter = args.antigen.as_deref();
    let item_filter = args.item_path.as_deref();
    let keep = |antigen_type: &str, target: &scan::ItemTarget| {
        antigen_filter.is_none_or(|a| antigen_type == a)
            && item_filter.is_none_or(|p| target.label() == p)
    };

    // Immunities always carry a fingerprint; presentations carry one only for
    // fingerprint-matches (explicit markers leave it empty). Report immune
    // sites first, then presentations whose fingerprint is non-empty.
    let mut matches: Vec<FingerprintMatch> = report
        .immunities
        .iter()
        .filter(|i| keep(&i.antigen_type, &i.item_target))
        .map(|i| FingerprintMatch {
            antigen_type: i.antigen_type.clone(),
            item_path: i.item_target.label(),
            site_kind: "immune",
            structural_fingerprint: i.structural_fingerprint.clone(),
            file: i.file.display().to_string(),
            line: i.line,
        })
        .collect();
    matches.extend(
        report
            .presentations
            .iter()
            .filter(|p| keep(&p.antigen_type, &p.item_target))
            .filter(|p| !p.structural_fingerprint.is_empty())
            .map(|p| FingerprintMatch {
                antigen_type: p.antigen_type.clone(),
                item_path: p.item_target.label(),
                site_kind: "presents",
                structural_fingerprint: p.structural_fingerprint.clone(),
                file: p.file.display().to_string(),
                line: p.line,
            }),
    );

    match args.format {
        OutputFormat::Json => match serde_json::to_string_pretty(&matches) {
            Ok(s) => println!("{s}"),
            Err(e) => {
                eprintln!("error: failed to serialize fingerprints: {e}");
                return ExitCode::from(2);
            }
        },
        OutputFormat::Human => {
            if matches.is_empty() {
                let scope = match (antigen_filter, item_filter) {
                    (Some(a), Some(p)) => format!(" for antigen `{a}` at item `{p}`"),
                    (Some(a), None) => format!(" for antigen `{a}`"),
                    (None, Some(p)) => format!(" at item `{p}`"),
                    (None, None) => String::new(),
                };
                eprintln!(
                    "no immune/presents site with an obtainable fingerprint found{scope} \
                     under {}.",
                    args.root.display()
                );
            } else {
                for m in &matches {
                    println!(
                        "{}  {} [{}] on {}  {}:{}",
                        m.structural_fingerprint,
                        m.antigen_type,
                        m.site_kind,
                        m.item_path,
                        m.file,
                        m.line
                    );
                }
            }
        }
    }

    // A requested-but-not-found site is a user-visible failure (exit 1) so
    // scripts (e.g. `FP=$(cargo antigen fingerprint --antigen X --item-path y)`)
    // don't silently capture an empty value. An unfiltered empty workspace is
    // not a failure.
    if matches.is_empty() && (antigen_filter.is_some() || item_filter.is_some()) {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn run_audit(args: AuditArgs) -> ExitCode {
    if !args.root.exists() {
        eprintln!("error: path does not exist: {}", args.root.display());
        return ExitCode::from(2);
    }
    if !args.root.is_dir() {
        eprintln!(
            "error: expected a directory, got a file: {}",
            args.root.display()
        );
        return ExitCode::from(2);
    }

    // ADR-028 §CLI integration: --category filters the audit to a single category.
    let Ok(category_filter) = parse_category_filter(args.category.as_deref()) else {
        return ExitCode::from(2);
    };

    eprintln!("Auditing workspace: {}", args.root.display());

    let mut scan_report = match scan::scan_workspace(&args.root, None) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: scan failed: {e}");
            return ExitCode::from(2);
        }
    };

    if let Some(cat) = category_filter {
        filter_report_by_category(&mut scan_report, cat);
    }

    let audit_report = audit::audit(&scan_report, &args.root);

    // ADR-028 category audit (audit-time):
    //   G1 (scan-time-only enforcement): surface the
    //   antigen-category-defaulted-implicit-functional migration hint for every
    //   antigen declaration with an absent category — the load-bearing signal
    //   (per adversarial's G1 ratification) that makes absent-category visible
    //   rather than a silent false-green.
    //   G2 (category↔witness-type cross-check): surface
    //   antigen-category-claim-inconsistent-with-predicate-type for any
    //   explicit-category declaration whose immunities are the wrong witness
    //   type for the declared category (per Amendment 2 + aristotle F1).
    let category_report = audit::audit_category(&scan_report);

    // ADR-023 + team-lead reframe (forward/suppression-loud-must-be-removed):
    // #[anergy] / #[immunosuppress] are intentional dev permissions to proceed
    // with a known defense gap. They must be LOUD — the audit ALWAYS announces
    // active ones prominently so they cannot become silent accumulated debt.
    // `audit_deferred_defenses` computes the state; this is the delivery arm
    // (it was computed in the library but never reached the CLI — the
    // AuditVerdictComputedButNotDelivered severance, same shape as the lineage
    // surface). 30-day default stale-grace per the library contract.
    let deferred_report = audit::audit_deferred_defenses(&scan_report, 30);

    // ADR-024 convergent-evidence (#[diagnostic]/#[clonal]/#[igg]/...) +
    // recurrent-emergence (#[itch]/#[recurrence_anchor]/#[crystallize]/...)
    // audits. Both were computed by the library + populated by scan but NEVER
    // delivered by any CLI command (the AuditVerdictComputedButNotDelivered
    // severance — same shape as the lineage + deferred-defense surfaces). Wire
    // their concern-hints into the audit output so the verdict actually reaches
    // the adopter.
    let convergent_report = audit::audit_convergent_evidence(&scan_report);
    let recurrent_report = audit::audit_recurrent(&scan_report);
    // ADVISORY (scientist 2026-05-27): #[descended_from] lineage-fidelity —
    // flag (advisory, non-blocking) where a child antigen's fingerprint is
    // detectably NOT a refinement of its parent's. Delivered here so the
    // computed verdict reaches the adopter (the delivery-arm discipline).
    let lineage_fidelity_report = audit::audit_lineage_fidelity(&scan_report);

    match args.format {
        OutputFormat::Human => {
            print_audit_human(&scan_report, &audit_report);
            print_deferred_defenses_loud(&deferred_report);
            print_convergent_evidence_concerns(&convergent_report);
            print_recurrent_concerns(&recurrent_report);
            print_lineage_fidelity_advisory(&lineage_fidelity_report);
            print_category_audit_human(&category_report);
        }
        OutputFormat::Json => match serde_json::to_string_pretty(&JsonAuditReport {
            scan: &scan_report,
            audit: &audit_report,
            category: &category_report,
            deferred_defense_audit: &deferred_report,
            convergent_evidence_audit: &convergent_report,
            recurrent_audit: &recurrent_report,
            lineage_fidelity_audit: &lineage_fidelity_report,
        }) {
            Ok(s) => println!("{s}"),
            Err(e) => {
                eprintln!("error: failed to serialize report: {e}");
                return ExitCode::from(2);
            }
        },
    }

    // ADR-018 §"Audit diagnostic text" + §"7-state interaction matrix":
    // `--strict` promotes state 7 (inherited + unaddressed) from warn to
    // error. Without `--strict`, the audit reports state 7 as a warning
    // but still exits 0.
    let strict_state7_fails = args.strict && !audit_report.inherited_unaddressed.is_empty();
    let strict_witness_fails =
        args.strict && !audit_report.all_meet_tier(audit::WitnessTier::Reachability);
    // ADR-029 §Enforcement: under --strict, an undefended presents-site fails the
    // gate. Immunity is observed: a presents-site with no #[defended_by] witness
    // and no passing requires= predicate is an open defense circuit. (substrate-gap
    // is NOT gated here — the intent exists; it warrants a warning, not a hard
    // fail, until per-antigen severity lands in a later slice.)
    let strict_undefended_fails = args.strict && !audit_report.undefended_verdicts().is_empty();
    // ATK-STRICT-5 / findings/scan-audit-strict-divergence: audit --strict is the
    // CI integration point and MUST be a superset of scan --strict. The three
    // structural-defect gates that `scan --strict` enforces (orphaned tolerances,
    // orphaned lineage edges, dangling child lineage edges) belong in the audit
    // strict gate too — otherwise an adopter who runs `cargo antigen audit --strict`
    // for CI silently misses them. scan_report is already in scope here (line
    // ~3040 above), so this is a substrate-witness lift, not a recompute.
    let strict_orphaned_tolerances = args.strict && !scan_report.orphaned_tolerances().is_empty();
    let strict_lineage_broken = args.strict
        && (!scan_report.orphaned_lineage_edges().is_empty()
            || !scan_report.dangling_child_lineage_edges().is_empty());
    if strict_state7_fails
        || strict_witness_fails
        || strict_undefended_fails
        || strict_orphaned_tolerances
        || strict_lineage_broken
    {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

// ============================================================================
// cargo antigen attest handlers
// ============================================================================

fn run_attest(cli: AttestCli) -> ExitCode {
    match cli.command {
        AttestSubcommand::Scaffold(args) => {
            run_attest_scaffold(args, antigen_attestation::RatificationKind::Immunity)
        }
        AttestSubcommand::Sign(args) => run_attest_sign(args),
        AttestSubcommand::Check(args) => run_attest_check(args),
        AttestSubcommand::Delta(args) => run_attest_delta(args),
        AttestSubcommand::List(args) => run_attest_list(args),
        AttestSubcommand::Gc(args) => run_attest_gc(args),
        AttestSubcommand::Oracle => {
            eprintln!(
                "`attest oracle mark` is not yet implemented in v0.1-rc.\n\
                 Renamed from `attest oracle complete` per ADR-021 F28-R2 to \
                 disambiguate from the top-level `cargo antigen oracle complete` \
                 state-machine verb. Implementation pending: must write \
                 `OracleCompletionMarker {{ oracle_state_at_attestation, .. }}` \
                 at sign time per ADR-021 §D4 + ATK-021-19 (without the \
                 sign-time-state anchor, sign-time-validity cannot be \
                 structurally enforced — the audit cannot distinguish post-\
                 sign-time deprecation from pre-sign-time deprecation).\n\
                 Operator scripts MUST NOT rely on this exit code as success."
            );
            ExitCode::FAILURE
        }
    }
}

fn run_tolerate(cli: TolerateCli) -> ExitCode {
    match cli.command {
        TolerateSubcommand::Scaffold(args) => {
            run_attest_scaffold(args, antigen_attestation::RatificationKind::Tolerance)
        }
        TolerateSubcommand::Sign(args) => run_attest_sign(args),
        TolerateSubcommand::Check(args) => run_attest_check(args),
        TolerateSubcommand::List(mut args) => {
            args.tolerance_only = true;
            run_attest_list(args)
        }
    }
}

/// `attest scaffold` / `tolerate scaffold`: create a new `.attest/<Antigen>.json` sidecar.
/// Attempt to auto-fill the `current_fingerprint` for a scaffold whose
/// `--fingerprint` was omitted, by scanning the source file's crate subtree and
/// matching the immunity/presentation the operator named.
///
/// Composes with the existing scan machinery (ADR-002 compose-don't-compete)
/// rather than re-deriving the item-walk: scan already finds every immune/
/// presents site and computes its `structural_fingerprint`. We scan the source
/// file's directory subtree (a tight, predictable radius — the operator told us
/// which file the declaration lives in), then match on the antigen's last path
/// segment plus, if the operator passed one, the item path (against
/// [`scan::ItemTarget::label`]).
///
/// Returns:
/// - `Ok(Some(fp))` — exactly one match with a non-empty fingerprint.
/// - `Ok(None)` — no usable match (zero matches, or only matches with empty
///   fingerprints, e.g. explicit-marker presentations). Caller keeps the
///   empty-placeholder behavior; auto-fill is a convenience, never a hard fail.
/// - `Err(reason)` — ambiguous: multiple distinct fingerprints matched and the
///   operator didn't disambiguate with `--item-path`. Caller surfaces the
///   reason so the operator can narrow it.
fn autofill_fingerprint(
    source_file: &Path,
    antigen_stem: &str,
    item_path: &str,
) -> Result<Option<String>, String> {
    let scan_root = source_file.parent().unwrap_or_else(|| Path::new("."));
    let Ok(report) = scan::scan_workspace(scan_root, None) else {
        // A scan failure is not the operator's problem to solve here — fall
        // back to the placeholder path silently.
        return Ok(None);
    };

    let item_filter = (!item_path.is_empty()).then_some(item_path);
    let matches = |antigen_type: &str, target: &scan::ItemTarget| {
        antigen_type == antigen_stem && item_filter.is_none_or(|p| target.label() == p)
    };

    // Immunities always carry a fingerprint; presentations only for
    // fingerprint-matches (explicit markers leave it empty). Prefer immunities,
    // then fall back to presentations with a non-empty fingerprint.
    let mut fingerprints: Vec<String> = report
        .immunities
        .iter()
        .filter(|i| matches(&i.antigen_type, &i.item_target))
        .map(|i| i.structural_fingerprint.clone())
        .filter(|fp| !fp.is_empty())
        .collect();
    if fingerprints.is_empty() {
        fingerprints = report
            .presentations
            .iter()
            .filter(|p| matches(&p.antigen_type, &p.item_target))
            .map(|p| p.structural_fingerprint.clone())
            .filter(|fp| !fp.is_empty())
            .collect();
    }

    fingerprints.sort();
    fingerprints.dedup();
    match fingerprints.as_slice() {
        [] => Ok(None),
        [single] => Ok(Some(single.clone())),
        many => Err(format!(
            "auto-fill found {} distinct fingerprints for antigen `{antigen_stem}`\
             {} — pass `--item-path` to disambiguate, or `--fingerprint` explicitly.",
            many.len(),
            if item_filter.is_some() {
                format!(" at item `{item_path}`")
            } else {
                String::new()
            }
        )),
    }
}

fn run_attest_scaffold(
    args: AttestScaffoldArgs,
    kind_override: antigen_attestation::RatificationKind,
) -> ExitCode {
    use antigen_attestation::{
        AntigenIdentifier, ItemRatification, Ratification, RatificationKind, SchemaVersion,
    };
    use std::collections::BTreeMap;

    // The effective kind: --kind arg on the scaffold command, but `run_tolerate`
    // forces Tolerance regardless of the --kind arg (tolerate scaffold implies it).
    let kind = if matches!(kind_override, RatificationKind::Immunity) {
        args.kind.into()
    } else {
        kind_override
    };

    // Derive the antigen's last segment as the sidecar filename stem.
    let stem = args.antigen.rsplit("::").next().unwrap_or(&args.antigen);
    let Some(source_dir_ref) = args.source_file.parent() else {
        eprintln!("error: source-file has no parent directory");
        return ExitCode::from(2);
    };
    let source_dir = source_dir_ref.to_path_buf();
    let attest_dir = source_dir.join(".attest");
    let sidecar_path = attest_dir.join(format!("{stem}.json"));

    if sidecar_path.exists() && !args.force {
        eprintln!(
            "error: sidecar already exists: {}\n\
             Use --force to overwrite.",
            sidecar_path.display()
        );
        return ExitCode::from(1);
    }

    if let Err(e) = std::fs::create_dir_all(&attest_dir) {
        eprintln!("error: failed to create .attest/ directory: {e}");
        return ExitCode::from(2);
    }

    // When `--fingerprint` is omitted, try to auto-fill it by scanning the
    // source file's crate subtree for the immunity/presentation the operator
    // named. This removes the manual `scan --format json | jq` + hand-edit
    // dance the placeholder note otherwise prescribes.
    let mut fingerprint = args.fingerprint.clone();
    let mut autofilled = false;
    if fingerprint.is_empty() {
        match autofill_fingerprint(&args.source_file, stem, &args.item_path) {
            Ok(Some(fp)) => {
                fingerprint = fp;
                autofilled = true;
            }
            Ok(None) => {}
            Err(reason) => {
                eprintln!("error: {reason}");
                return ExitCode::from(1);
            }
        }
    }

    // An explicitly-passed --fingerprint may be malformed (auto-filled values
    // come from scan and are always valid, so this only fires for operator
    // input). A malformed digest scaffolds a sidecar whose current_fingerprint
    // can never match the item's real digest at audit — warn loudly rather than
    // bake a dead value silently. (FingerprintDigestWithoutFormatValidation —
    // the same cross-site guard run at the sign site.)
    if !autofilled {
        warn_if_empty_fingerprint(&fingerprint);
    }

    let ratification = Ratification {
        schema_version: SchemaVersion::V1,
        kind,
        antigen: AntigenIdentifier {
            name: stem.to_string(),
            defined_in: None,
        },
        source_file: args.source_file.clone(),
        items: vec![ItemRatification {
            item_path: args.item_path.clone(),
            current_fingerprint: fingerprint.clone(),
            doc_ref: None,
            signers: vec![],
            oracles: vec![],
            fresh_through: None,
            extensions: BTreeMap::new(),
        }],
    };

    let json = match serde_json::to_string_pretty(&ratification) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: failed to serialize sidecar: {e}");
            return ExitCode::from(2);
        }
    };

    if let Err(e) = std::fs::write(&sidecar_path, &json) {
        eprintln!("error: failed to write sidecar: {e}");
        return ExitCode::from(2);
    }

    eprintln!("Created sidecar: {}", sidecar_path.display());
    if autofilled {
        eprintln!("  fingerprint auto-filled from scan: {fingerprint}");
    } else if fingerprint.is_empty() {
        eprintln!(
            "  note: fingerprint is empty — auto-fill found no matching scanned site, so \
             update `current_fingerprint` before signing.\n\
             \n\
             Get the item fingerprint from:\n\
             \n  cargo antigen scan --format json | jq '.report.immunities[] | select(.antigen_type==\"{}\") | .structural_fingerprint'\n",
            stem
        );
    }
    let next_fp = if fingerprint.is_empty() {
        "<fp>".to_string()
    } else {
        fingerprint
    };
    eprintln!(
        "\nNext: `cargo antigen attest sign --sidecar {} --item-path \"{}\" --signer <name> --fingerprint {next_fp}`",
        sidecar_path.display(),
        args.item_path
    );
    ExitCode::SUCCESS
}

/// DX finding 8 guard: warn when signing against empty fingerprint.
/// Extracted to keep `run_attest_sign` under clippy's `too_many_lines` threshold.
/// Whether a string has the shape of a structural digest: the self-describing
/// `fnv1a64:` version prefix followed by 16 lowercase-hex chars (see
/// `antigen_fingerprint::digest`). A digest that doesn't match this shape can
/// never equal an item's real digest, so a substrate-witness predicate bound to
/// it silently fails at audit forever.
fn looks_like_structural_digest(fingerprint: &str) -> bool {
    let Some(hex) = fingerprint.strip_prefix("fnv1a64:") else {
        return false;
    };
    hex.len() == 16
        && hex
            .bytes()
            .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
}

/// DX finding 8 + the digest-format gap: warn when signing against a fingerprint
/// that can't be a real structural digest — empty, OR present-but-malformed
/// (e.g. a DSL grammar string, an unprefixed hash, or a typo). Both cases record
/// a `signed_against_fingerprint` that never matches the item's real digest, so
/// the signature is dead-on-arrival at audit. A warning (not a hard error) keeps
/// the empty-case posture and tolerates a future digest scheme, but makes the
/// dead-signature loud instead of silent.
fn warn_if_empty_fingerprint(fingerprint: &str) {
    if fingerprint.is_empty() {
        eprintln!(
            "warning: signing against an empty fingerprint. A substrate-witness \
             predicate bound to `against = \"current\"` (or `fresh_within_days`) \
             will fail at audit time because the signed-against fingerprint `` \
             cannot match the item's real structural digest. Obtain the item's \
             fingerprint from `cargo antigen scan --format json` (the \
             `structural_fingerprint` field on the immunity/presentation entry) \
             and pass it via `--fingerprint`."
        );
    } else if !looks_like_structural_digest(fingerprint) {
        eprintln!(
            "warning: `--fingerprint {fingerprint}` does not look like a structural \
             digest (expected `fnv1a64:` + 16 lowercase-hex chars). It will be \
             recorded as the signed-against fingerprint, but a substrate-witness \
             predicate bound to `against = \"current\"` will never match the item's \
             real digest at audit time — the signature is dead-on-arrival. Obtain \
             the digest from `cargo antigen fingerprint` (or `scan --format json`) \
             and pass that value."
        );
    }
}

/// `attest sign` / `tolerate sign`: add a signer entry to an existing sidecar.
fn run_attest_sign(args: AttestSignArgs) -> ExitCode {
    use antigen_attestation::{Ratification, Signer, SignerBasis};

    // Load the existing sidecar.
    let content = match std::fs::read_to_string(&args.sidecar) {
        Ok(c) => c,
        Err(e) => {
            eprintln!(
                "error: failed to read sidecar {}: {e}",
                args.sidecar.display()
            );
            return ExitCode::from(2);
        }
    };
    let mut ratification: Ratification = match serde_json::from_str(&content) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: sidecar is not valid JSON (Ratification schema): {e}");
            return ExitCode::from(2);
        }
    };

    // Find the target item.
    let item = ratification
        .items
        .iter_mut()
        .find(|i| i.item_path == args.item_path);
    let Some(item) = item else {
        eprintln!(
            "error: no item with path `{}` in sidecar.\n\
             Available item paths: {}",
            args.item_path,
            ratification
                .items
                .iter()
                .map(|i| i.item_path.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
        return ExitCode::from(1);
    };

    // Check for duplicate signer + fingerprint combo.
    let already_signed = item
        .signers
        .iter()
        .any(|s| s.name == args.signer && s.signed_against_fingerprint == args.fingerprint);
    if already_signed {
        eprintln!(
            "warning: signer `{}` has already signed this item against fingerprint `{}`.\n\
             No entry added.",
            args.signer, args.fingerprint
        );
        return ExitCode::SUCCESS;
    }

    warn_if_empty_fingerprint(&args.fingerprint);

    // Warn if signing against a fingerprint that doesn't match the sidecar's stored
    // current_fingerprint — the resulting entry will be immediately stale at audit time.
    if !item.current_fingerprint.is_empty() && args.fingerprint != item.current_fingerprint {
        eprintln!(
            "warning: --fingerprint `{}` does not match sidecar's stored \
             current_fingerprint `{}`. The new signer entry will be immediately \
             stale at audit time. Update the sidecar's current_fingerprint first, \
             or re-run `cargo antigen scan --format json` to get the current fingerprint.",
            args.fingerprint, item.current_fingerprint
        );
    }

    let today = chrono::Local::now().date_naive();
    item.signers.push(Signer {
        name: args.signer.clone(),
        role: args.role.clone(),
        date: today,
        signed_against_fingerprint: args.fingerprint.clone(),
        basis: SignerBasis::Fresh {
            reasoning: args.reasoning.clone(),
        },
        strength: antigen_attestation::SignatureStrength::from(args.strength),
        signature: None,
    });

    let json = match serde_json::to_string_pretty(&ratification) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: failed to serialize updated sidecar: {e}");
            return ExitCode::from(2);
        }
    };
    if let Err(e) = std::fs::write(&args.sidecar, &json) {
        eprintln!("error: failed to write updated sidecar: {e}");
        return ExitCode::from(2);
    }

    eprintln!(
        "Signed: {} added to `{}` item `{}` against fingerprint `{}`",
        args.signer,
        args.sidecar.display(),
        args.item_path,
        args.fingerprint
    );
    if let Some(role) = &args.role {
        eprintln!("  role: {role}");
    }
    ExitCode::SUCCESS
}

/// `attest delta`: append a carry-forward delta entry to an existing sidecar.
///
/// Reads the current sidecar, finds the last fresh-basis signature for the
/// named signer at the named item, computes `chain_depth`, enforces the
/// anti-laundering safeguards (ADR-019 §Decision §E3), and writes the new
/// `DeltaFrom` entry back.
fn run_attest_delta(args: AttestDeltaArgs) -> ExitCode {
    use antigen_attestation::schema::HARD_DELTA_CHAIN_CAP_MAX;
    use antigen_attestation::{Ratification, Signer, SignerBasis};

    // Anti-laundering safeguard: enforce chain-depth cap (default 3; hard max
    // = HARD_DELTA_CHAIN_CAP_MAX). Project TOML config may tighten; tighter
    // caps also enforced at audit time by evaluator.
    const DEFAULT_DELTA_CAP: u32 = 3;

    let content = match std::fs::read_to_string(&args.sidecar) {
        Ok(s) => s,
        Err(e) => {
            eprintln!(
                "error: could not read sidecar `{}`: {e}",
                args.sidecar.display()
            );
            return ExitCode::from(2);
        }
    };
    let mut ratification: Ratification = match serde_json::from_str(&content) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: sidecar is not valid Ratification JSON: {e}");
            return ExitCode::from(2);
        }
    };

    // Resolve signer name from arg or git config.
    let signer_name = match resolve_steward_name(args.signer.as_deref()) {
        Ok(n) => n,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(1);
        }
    };

    if let Err(code) = validate_delta_rationale(&args.rationale) {
        return code;
    }

    let item = ratification
        .items
        .iter_mut()
        .find(|i| i.item_path == args.item_path);
    let Some(item) = item else {
        eprintln!(
            "error: no item with path `{}` in sidecar `{}`",
            args.item_path,
            args.sidecar.display()
        );
        return ExitCode::from(1);
    };

    // Find the last Fresh basis for this signer to determine cumulative root.
    let cumulative_root = item
        .signers
        .iter()
        .rfind(|s| s.name == signer_name && s.basis.is_fresh())
        .map(|s| s.signed_against_fingerprint.clone());
    let Some(cumulative_root_fingerprint) = cumulative_root else {
        eprintln!(
            "error: no prior Fresh-basis signature found for signer `{signer_name}` \
             at item `{}`. Run `attest sign` first to establish a fresh attestation \
             before using `attest delta`.",
            args.item_path
        );
        return ExitCode::from(1);
    };

    let chain_depth = compute_delta_chain_depth(&item.signers, &signer_name);

    if chain_depth > DEFAULT_DELTA_CAP {
        eprintln!(
            "error: delta chain depth {chain_depth} exceeds default cap \
             {DEFAULT_DELTA_CAP} (hard max = {HARD_DELTA_CHAIN_CAP_MAX}). \
             Run `attest sign` to re-anchor with a Fresh basis."
        );
        return ExitCode::from(1);
    }

    // Both delta fingerprints are digests that must match real item digests at
    // audit (the new signed-against and the prior it carries forward from). A
    // malformed value silently breaks the chain — warn at the boundary
    // (FingerprintDigestWithoutFormatValidation, same guard as sign/scaffold).
    warn_if_empty_fingerprint(&args.fingerprint);
    warn_if_empty_fingerprint(&args.prior_fingerprint);

    let today = chrono::Local::now().date_naive();
    item.signers.push(Signer {
        name: signer_name.clone(),
        role: args.role,
        date: today,
        signed_against_fingerprint: args.fingerprint.clone(),
        basis: SignerBasis::DeltaFrom {
            prior_fingerprint: args.prior_fingerprint.clone(),
            cumulative_root_fingerprint,
            chain_depth,
            rationale: args.rationale.clone(),
        },
        strength: antigen_attestation::SignatureStrength::from(args.strength),
        signature: None,
    });

    let json = match serde_json::to_string_pretty(&ratification) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("error: failed to serialize updated sidecar: {e}");
            return ExitCode::from(2);
        }
    };
    if let Err(e) = std::fs::write(&args.sidecar, &json) {
        eprintln!("error: failed to write sidecar: {e}");
        return ExitCode::from(2);
    }

    eprintln!(
        "Delta: `{}` signed `{}` item `{}` at depth {chain_depth}",
        signer_name,
        args.sidecar.display(),
        args.item_path,
    );
    ExitCode::SUCCESS
}

/// `attest list` / `tolerate list`: walk the workspace and enumerate all `.attest/` sidecars.
fn run_attest_list(args: AttestListArgs) -> ExitCode {
    use antigen_attestation::Ratification;

    let sidecars = collect_sidecars(&args.root);
    if sidecars.is_empty() {
        eprintln!(
            "No .attest/ sidecars found under `{}`.",
            args.root.display()
        );
        return ExitCode::SUCCESS;
    }

    let mut printed = 0usize;
    for path in &sidecars {
        let content = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("warning: could not read `{}`: {e}", path.display());
                continue;
            }
        };
        let rat: Ratification = match serde_json::from_str(&content) {
            Ok(r) => r,
            Err(e) => {
                eprintln!(
                    "warning: `{}` is not valid Ratification JSON: {e}",
                    path.display()
                );
                continue;
            }
        };
        if args.tolerance_only && rat.kind != antigen_attestation::RatificationKind::Tolerance {
            continue;
        }

        match args.format {
            OutputFormat::Human => {
                println!(
                    "{} [{:?}] — {} item(s)",
                    path.display(),
                    rat.kind,
                    rat.items.len()
                );
                for item in &rat.items {
                    println!("  {} ({} signer(s))", item.item_path, item.signers.len());
                }
            }
            OutputFormat::Json => {
                // One JSON object per line (newline-delimited JSON).
                let obj = serde_json::json!({
                    "path": path.display().to_string(),
                    "kind": format!("{:?}", rat.kind),
                    "antigen": rat.antigen.name,
                    "item_count": rat.items.len(),
                });
                println!("{obj}");
            }
        }
        printed += 1;
    }

    if args.orphan_scan {
        eprintln!("\n-- Orphan scan (--orphan-scan): comparing sidecar item_paths against source macros --");
        eprintln!("(Note: full bidirectional scan requires `cargo antigen scan` integration; v0.2 adds gc bidirectional traversal)");
        for path in &sidecars {
            let Ok(content) = std::fs::read_to_string(path) else {
                continue;
            };
            if let Ok(rat) = serde_json::from_str::<Ratification>(&content) {
                for item in &rat.items {
                    if item.signers.is_empty() {
                        println!(
                            "ORPHAN-CANDIDATE: {} item `{}` has no signers",
                            path.display(),
                            item.item_path
                        );
                    }
                }
            }
        }
    }

    eprintln!("{printed} sidecar(s) listed.");
    ExitCode::SUCCESS
}

/// `attest gc`: report orphaned sidecars (report-only in v0.1; --force deletes).
fn run_attest_gc(args: AttestGcArgs) -> ExitCode {
    use antigen_attestation::Ratification;

    let sidecars = collect_sidecars(&args.root);
    let mut orphans: Vec<std::path::PathBuf> = Vec::new();

    for path in &sidecars {
        // Warn-and-continue on unreadable / corrupt sidecars (same fix as
        // `oracle list` / the `attest list` model). A silently-skipped corrupt
        // sidecar can never be gc'd AND gives the operator no signal it's broken
        // — it just vanishes from the orphan scan (ATK-oracle-corrupt-json,
        // gc-side). A corrupt sidecar can't have its source_file checked, so it
        // is neither confirmed-orphan nor confirmed-live; surface it loudly.
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("warning: could not read `{}`: {e}", path.display());
                continue;
            }
        };
        let rat: Ratification = match serde_json::from_str(&content) {
            Ok(r) => r,
            Err(e) => {
                eprintln!(
                    "warning: `{}` is not valid Ratification JSON: {e} \
                     (corrupt sidecar — cannot evaluate for gc; surfaced rather than \
                     silently skipped)",
                    path.display()
                );
                continue;
            }
        };
        // An orphan heuristic: if source_file doesn't exist relative to workspace root.
        let source = args.root.join(&rat.source_file);
        if !source.exists() {
            orphans.push(path.clone());
        }
    }

    if orphans.is_empty() {
        eprintln!(
            "No orphaned sidecars found under `{}`.",
            args.root.display()
        );
        return ExitCode::SUCCESS;
    }

    eprintln!("{} orphaned sidecar(s) found:", orphans.len());
    for path in &orphans {
        println!("{}", path.display());
    }

    if args.force {
        let mut removed = 0usize;
        for path in &orphans {
            match std::fs::remove_file(path) {
                Ok(()) => {
                    eprintln!("Removed: {}", path.display());
                    removed += 1;
                }
                Err(e) => eprintln!("error removing `{}`: {e}", path.display()),
            }
        }
        eprintln!("{removed} sidecar(s) removed.");
    } else {
        eprintln!("(Run with --force to delete. Report-only in v0.1.)");
    }

    ExitCode::SUCCESS
}

/// Walk `root` recursively and return all `.attest/*.json` files found.
fn collect_sidecars(root: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut result = Vec::new();
    let Ok(entries) = std::fs::read_dir(root) else {
        return result;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            if path
                .file_name()
                .is_some_and(|n| n.to_string_lossy().ends_with(".attest"))
            {
                // Collect JSON files inside .attest/ directories.
                if let Ok(inner) = std::fs::read_dir(&path) {
                    for inner_entry in inner.flatten() {
                        let inner_path = inner_entry.path();
                        if inner_path.extension().is_some_and(|e| e == "json") {
                            result.push(inner_path);
                        }
                    }
                }
            } else if path.file_name().is_none_or(|n| {
                let s = n.to_string_lossy();
                !s.starts_with('.') && s != "target"
            }) {
                // Recurse into non-hidden, non-target directories.
                result.extend(collect_sidecars(&path));
            }
        }
    }
    result
}

/// Filesystem-backed evaluation context for the CLI check commands.
struct CheckContext;

impl antigen_attestation::EvaluationContext for CheckContext {
    fn today(&self) -> chrono::NaiveDate {
        chrono::Local::now().date_naive()
    }

    fn read_doc(&self, path: &std::path::Path) -> Option<String> {
        std::fs::read_to_string(path).ok()
    }

    fn read_oracle(&self, path: &std::path::Path) -> Option<String> {
        std::fs::read_to_string(path).ok()
    }

    fn read_git_trailers(
        &self,
        item_source_file: &std::path::Path,
        _item_path: &str,
    ) -> Vec<String> {
        // Invoke `git log --format=%B -- <file>` to collect all commit messages
        // touching the item's source file, then pipe through `git interpret-trailers
        // --parse` to extract structured trailers. This satisfies the signed_trailer
        // leaf contract (ADR-019 §Decision §4 bright-line rule: git is named, has own
        // release process, does not execute user code, args are fixed).
        //
        // If git is unavailable or the file has no commits, returns Vec::new()
        // (tier-honest: no trailers found → signed_trailer predicate fails → None tier).
        let log_output = std::process::Command::new("git")
            .args([
                "log",
                "--format=%B",
                "--",
                item_source_file.to_str().unwrap_or(""),
            ])
            .output();
        let log_bytes = match log_output {
            Ok(o) if o.status.success() => o.stdout,
            _ => return Vec::new(),
        };

        let trailer_output = std::process::Command::new("git")
            .args(["interpret-trailers", "--parse"])
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .spawn()
            .and_then(|mut child| {
                use std::io::Write;
                if let Some(stdin) = child.stdin.take() {
                    let mut stdin = stdin;
                    let _ = stdin.write_all(&log_bytes);
                }
                child.wait_with_output()
            });

        match trailer_output {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
                .lines()
                .map(|l| l.trim().to_owned())
                .filter(|l| !l.is_empty())
                .collect(),
            _ => Vec::new(),
        }
    }
}

/// `attest check` / `tolerate check`: evaluate a predicate against a sidecar.
fn run_attest_check(args: AttestCheckArgs) -> ExitCode {
    use antigen_attestation::{evaluate::evaluate_predicate_with_kind, Predicate, Ratification};

    // Load sidecar.
    let content = match std::fs::read_to_string(&args.sidecar) {
        Ok(c) => c,
        Err(e) => {
            eprintln!(
                "error: failed to read sidecar {}: {e}",
                args.sidecar.display()
            );
            return ExitCode::from(2);
        }
    };
    let ratification: Ratification = match serde_json::from_str(&content) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: sidecar schema invalid: {e}");
            return ExitCode::from(2);
        }
    };

    // Deserialize the predicate.
    let predicate: Predicate = match serde_json::from_str(&args.predicate) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("error: predicate JSON invalid: {e}");
            return ExitCode::from(2);
        }
    };

    // Find the target item (first, or by item_path).
    let item = if let Some(ref path) = args.item_path {
        if let Some(i) = ratification.items.iter().find(|i| i.item_path == *path) {
            i
        } else {
            eprintln!("error: no item with path `{path}` in sidecar.");
            return ExitCode::from(1);
        }
    } else if let Some(i) = ratification.items.first() {
        i
    } else {
        eprintln!("error: sidecar has no items.");
        return ExitCode::from(1);
    };

    // CLI-SF-1: when --fingerprint is omitted, fall back to the sidecar's stored
    // current_fingerprint. This is self-referential and cannot detect stale signers —
    // a signer who signed against fp-old looks current if the sidecar's stored fp is
    // also fp-old, even when the real item has changed to fp-new. Always supply
    // --fingerprint from `cargo antigen scan --format json` for accurate stale detection.
    if args.fingerprint.is_none() {
        eprintln!(
            "warning: --fingerprint not supplied; using sidecar's stored \
             current_fingerprint for stale-signer detection.\n\
             If the item's code has changed since the sidecar was written, stale \
             signers will appear current. Supply --fingerprint from \
             `cargo antigen scan --format json` for accurate stale detection.\n\
             (CLI-SF-1: self-referential fingerprint cannot detect real staleness)"
        );
    } else if let Some(fp) = args.fingerprint.as_deref() {
        // A supplied --fingerprint is compared against signers' signed-against
        // digests; a malformed one mis-reports staleness either way. Warn at the
        // boundary (FingerprintDigestWithoutFormatValidation, same guard as
        // sign/scaffold/delta). Empty is impossible here (it's Some), so only the
        // format branch can fire.
        warn_if_empty_fingerprint(fp);
    }
    let current_fingerprint = args
        .fingerprint
        .as_deref()
        .unwrap_or(&item.current_fingerprint);

    let result = match evaluate_predicate_with_kind(
        &predicate,
        item,
        current_fingerprint,
        &args.sidecar,
        ratification.kind,
        &CheckContext,
    ) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("error: evaluation error: {e}");
            return ExitCode::from(2);
        }
    };

    eprintln!("Sidecar:   {}", args.sidecar.display());
    eprintln!("Item path: {}", item.item_path);
    eprintln!("Kind:      {:?}", ratification.kind);
    eprintln!();
    eprintln!("Result:");
    eprintln!("  witness_tier:      {:?}", result.witness_tier);
    eprintln!("  audit_hint:        {:?}", result.audit_hint);
    eprintln!("  evidence_kind:     {:?}", result.evidence_kind);
    eprintln!("  signature_strength:{:?}", result.signature_strength);

    // Finding 7: per-leaf pass/fail with expected-vs-found, so a failed compound
    // predicate is debuggable from the CLI output alone (no evaluator source dive).
    if !result.leaf_outcomes.is_empty() {
        eprintln!();
        eprintln!("Per-leaf:");
        for leaf in &result.leaf_outcomes {
            let mark = if leaf.passed { "PASS" } else { "FAIL" };
            eprintln!("  {}: {}{}", leaf.label, mark, leaf.reason);
        }
    }

    // Exit 1 if predicate failed (tier = None means failed or missing-sidecar).
    if result.witness_tier == antigen_attestation::WitnessTier::None {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

#[derive(serde::Serialize)]
struct JsonAuditReport<'a> {
    scan: &'a scan::ScanReport,
    audit: &'a audit::AuditReport,
    /// ADR-028 G1 antigen-category coverage (defaulted-implicit-functional).
    category: &'a audit::CategoryAuditReport,
    /// ADR-023 deferred-defense state (anergy / immunosuppress / poxparty /
    /// orient): active/expired/stale counts + per-declaration hints. Always
    /// present so consumers can detect active suppressions — the LOUD invariant
    /// (forward/suppression-loud-must-be-removed): intentional defense gaps must
    /// never be silently invisible.
    deferred_defense_audit: &'a audit::DeferredDefenseAuditReport,
    /// ADR-024 convergent-evidence audit (`#[diagnostic]`/`#[clonal]`/`#[igg]`/...):
    /// per-declaration concern hints + clean/concern counts. Delivered here so
    /// the computed verdict reaches consumers (was a severed delivery arm).
    convergent_evidence_audit: &'a audit::ConvergentEvidenceAuditReport,
    /// ADR-024 recurrent-emergence audit (`#[itch]`/`#[recurrence_anchor]`/...):
    /// per-declaration concern hints + clean/concern counts. Delivered here so
    /// the computed verdict reaches consumers (was a severed delivery arm).
    recurrent_audit: &'a audit::RecurrentAuditReport,
    /// `#[descended_from]` lineage-fidelity advisory (scientist 2026-05-27):
    /// edges where the child antigen's fingerprint is detectably NOT a
    /// refinement of the parent's. ADVISORY (non-blocking) for v0.3.
    lineage_fidelity_audit: &'a audit::LineageFidelityAuditReport,
}

fn print_audit_human(scan_report: &scan::ScanReport, audit_report: &audit::AuditReport) {
    println!();
    print_audit_summary(audit_report);
    println!();

    // ATK-A3-019 fix: confirmed-claims block, parallel to the warnings
    // block below. Above-Execution-tier claims get an explicit positive
    // confirmation; without it, a FormalProof witness is invisible in the
    // human-readable output (the warnings block only lists claims BELOW
    // Execution). The JSON output has always carried this; the human path
    // was display-incomplete.
    print_confirmed_immunity_claims(audit_report);

    let problematic = audit_report.problematic_audits();

    if problematic.is_empty() {
        println!("✓ All immunity claims meet the Execution tier or higher.");
        println!(
            "  Note: semantic verification (does the witness actually test this failure class?)"
        );
        println!("  requires fingerprint-aware audit, planned for Sweep A4-A5.");
        if scan_report.immunities.is_empty() {
            println!("  (No immunity declarations found in the workspace.)");
        }
    } else {
        println!(
            "{} immunity claim(s) below Execution tier:",
            problematic.len()
        );
        println!();
        for a in &problematic {
            let i = &a.immunity;
            println!(
                "  {}:{}  {} (witness = `{}`)",
                i.file.display(),
                i.line,
                i.antigen_type,
                i.witness
            );
            println!("    tier = {:?}, hint = {:?}", a.witness_tier, a.audit_hint);
            // Finding 7: per-leaf expected-vs-found, so a failed substrate-witness
            // predicate is legible without reading evaluator source.
            for leaf in &a.leaf_outcomes {
                let mark = if !leaf.evaluated {
                    "NOT-EVALUATED"
                } else if leaf.passed {
                    "PASS"
                } else {
                    "FAIL"
                };
                println!("      {}: {}{}", leaf.label, mark, leaf.reason);
            }
            match &a.witness_status {
                audit::WitnessStatus::NotFound { reason } => {
                    println!("    → broken: {reason}");
                }
                audit::WitnessStatus::Missing => {
                    println!(
                        "    → missing: declaration has no witness identifier; \
                         a marker without proof is not a claim (per ADR-005)"
                    );
                }
                audit::WitnessStatus::Ambiguous { candidates } => {
                    println!(
                        "    → ambiguous: witness name matches {} workspace functions",
                        candidates.len(),
                    );
                    for c in candidates {
                        println!("        - {}", c.display());
                    }
                    println!(
                        "      Fix: rename one of the colliding functions, or \
                         qualify the witness path"
                    );
                }
                audit::WitnessStatus::External { tool_hint } => {
                    println!(
                        "    → external ({tool_hint}): tool prefix recognized but not invoked. \
                         A3+ will run the tool to promote this witness to Execution tier."
                    );
                }
                audit::WitnessStatus::Resolved { .. } => {
                    // Resolved witnesses below Execution tier (Reachability):
                    // empty function bodies, ignored tests, or unrun tests.
                    // The hint already says which case applies.
                }
            }
            // DX finding 3: a code-witness (`witness = ...`) site that also has
            // a `.attest/` sidecar on disk. The sidecar is silently uncredited
            // — substrate-witness sidecars are evaluated only on the
            // `requires = ...` path — so warn rather than let the adopter
            // believe a signed sidecar attests this site.
            if a.code_witness_sidecar_ignored {
                println!(
                    "    → sidecar ignored: a `.attest/` substrate-witness sidecar exists \
                     for this antigen, but this site uses `witness = ...`, not \
                     `requires = ...`. Substrate-witness sidecars are credited only for \
                     `requires =` immunities, so the sidecar can never be counted here. \
                     Either switch this site to `requires = <predicate>` to use the \
                     sidecar, or remove the orphan sidecar."
                );
            }
        }
        println!();
        println!(
            "Resolve below-Execution claims by either:\n  \
             a) Adding test invocation that exercises the witness path (A4-A5 feature)\n  \
             b) Pointing the witness at a runnable test (#[test] without #[ignore])\n  \
             c) Renaming colliding functions or qualifying ambiguous witness paths\n  \
             d) Adding the witness function to the workspace if it's missing\n  \
             e) Tolerating the gap with `#[antigen_tolerance(...)]` if intentional"
        );
    }

    print_state7_diagnostics(audit_report);
    print_immune_state_verdicts(audit_report);
}

/// Render the per-presents-site immune-state verdicts (ADR-029: Immunity Is
/// Observed, Not Declared). This is the audit's authoritative voice on immune
/// state — it reports `defended` / `undefended` / `substrate-gap` per site and
/// NEVER says "immune to X." The verdict describes the state of the defense
/// circuit, not whether the failure mode can fire.
fn print_immune_state_verdicts(audit_report: &audit::AuditReport) {
    use audit::ImmuneVerdict;

    if audit_report.presentation_verdicts.is_empty() {
        return;
    }

    println!();
    println!("Immune-state verdicts (ADR-029 — observed, not declared):");

    let undefended = audit_report.undefended_verdicts();
    let defended_count = audit_report
        .presentation_verdicts
        .iter()
        .filter(|v| matches!(v.verdict, ImmuneVerdict::Defended { .. }))
        .count();
    let gap_count = audit_report
        .presentation_verdicts
        .iter()
        .filter(|v| matches!(v.verdict, ImmuneVerdict::SubstrateGap))
        .count();

    println!(
        "  {} defended, {} undefended, {} substrate-gap \
         (across {} presents-site(s))",
        defended_count,
        undefended.len(),
        gap_count,
        audit_report.presentation_verdicts.len()
    );

    for v in &audit_report.presentation_verdicts {
        let site = format!("{}:{}", v.presentation.file.display(), v.presentation.line);
        match &v.verdict {
            ImmuneVerdict::Defended { tier } => {
                let witnesses = if v.defended_by.is_empty() {
                    String::new()
                } else {
                    format!(" by {}", v.defended_by.join(", "))
                };
                println!(
                    "{site}  {} — defended at {tier:?}{witnesses}",
                    v.antigen_type
                );
            }
            ImmuneVerdict::Undefended => {
                println!(
                    "{site}  {} — undefended (no #[defended_by] witness, \
                     no passing requires= predicate)",
                    v.antigen_type
                );
            }
            ImmuneVerdict::SubstrateGap => {
                println!(
                    "{site}  {} — substrate-gap (defense intent present; \
                     current substrate does not satisfy the requires= predicate)",
                    v.antigen_type
                );
            }
        }
    }
}

fn print_category_audit_human(category_report: &audit::CategoryAuditReport) {
    if !category_report.all_explicit() {
        println!();
        println!(
            "antigen-category: {} declaration(s) with absent category \
             (defaulted to FunctionalCorrectness):",
            category_report.defaulted_count
        );
        for ca in &category_report.audits {
            if ca
                .hints
                .contains(&audit::AuditHint::AntigenCategoryDefaultedImplicitFunctional)
            {
                println!(
                    "  - {} ({}:{}) — antigen-category-defaulted-implicit-functional",
                    ca.antigen_type,
                    ca.file.display(),
                    ca.line
                );
            }
        }
        println!(
            "  Add `category = AntigenCategory::...` per ADR-028. (v0.2: \
             scan-time hint; v0.2.x: parse-time hard-error for new decls.)"
        );
    }
    if !category_report.no_category_witness_mismatch() {
        println!();
        println!(
            "antigen-category: {} declaration(s) whose category is not \
             backed by a matching witness type:",
            category_report.mismatch_count
        );
        for ca in &category_report.audits {
            if ca
                .hints
                .contains(&audit::AuditHint::AntigenCategoryClaimInconsistentWithPredicateType)
            {
                println!(
                    "  - {} ({}:{}) — antigen-category-claim-inconsistent-with-predicate-type",
                    ca.antigen_type,
                    ca.file.display(),
                    ca.line
                );
            } else if ca
                .hints
                .contains(&audit::AuditHint::AntigenCategoryHybridIncompleteEvidence)
            {
                println!(
                    "  - {} ({}:{}) — antigen-category-hybrid-incomplete-evidence",
                    ca.antigen_type,
                    ca.file.display(),
                    ca.line
                );
            }
        }
        println!(
            "  SubstrateAlignment needs a `requires = ...` immunity; \
             FunctionalCorrectness needs a `witness = ...` immunity; \
             hybrid needs both (one axis present → \
             hybrid-incomplete-evidence; ADR-028 §Schema)."
        );
    }
    print_silence_witness_advisory(category_report);
}

/// Render the silence-witness shape-mismatch advisories (scientist design +
/// aristotle gate, forward/silence-witness-shape-mismatch-{hint,impl}). A
/// `SubstrateAlignment` antigen fails by silence-by-absence: a representation
/// drifts and nothing fires, because the antigen is about the ABSENCE of a
/// closure-mechanism. The two advisories flag witness shapes that cannot detect
/// that silence — no witness at all (no-witness) or a code-tier-only witness
/// that detects behavioral, not substrate-alignment, failures (wrong-tier).
/// Split out of [`print_category_audit_human`] to keep each section within the
/// per-function line budget.
fn print_silence_witness_advisory(category_report: &audit::CategoryAuditReport) {
    if category_report.no_silence_witness_mismatch() {
        return;
    }
    println!();
    println!(
        "antigen-category: SubstrateAlignment declaration(s) whose witness \
         shape cannot detect silence (advisory):"
    );
    for ca in &category_report.audits {
        if ca
            .hints
            .contains(&audit::AuditHint::AntigenWitnessShapeMismatchForSilenceNoWitness)
        {
            println!(
                "  - {} ({}:{}) — antigen-witness-shape-mismatch-for-silence-no-witness",
                ca.antigen_type,
                ca.file.display(),
                ca.line
            );
        }
        if ca
            .hints
            .contains(&audit::AuditHint::AntigenWitnessShapeMismatchForSilenceWrongTier)
        {
            println!(
                "  - {} ({}:{}) — antigen-witness-shape-mismatch-for-silence-wrong-tier",
                ca.antigen_type,
                ca.file.display(),
                ca.line
            );
        }
    }
    println!(
        "  A SubstrateAlignment failure is silence-by-absence: it surfaces \
         only when a mechanism asserts the closure exists. no-witness → wire \
         a parity/bijection witness (assert the mechanism exists, not just \
         that the two representations agree now). wrong-tier → a code-tier \
         test detects behavioral failures; reach for a `requires = ...` \
         substrate predicate or a bijection-parity test (exception: the \
         wrong-weighting generator legitimately uses a code-tier \
         confidence test — confirm the intended generator first)."
    );
}

/// Audit summary with per-tier sub-counts per ATK-A3-019 (A3.5 onboarding sweep).
///
/// Per ADR-005 Amendment 3: tier counts report the work the audit ACTUALLY
/// PERFORMED, never potential maximum evidence. A `#[test]` whose run was
/// not invoked sits at Reachability, not Execution.
///
/// `resolved_count` is split into per-tier sub-counts so a `FormalProof`
/// claim (phantom-type witness, type-system-encoded proof) does NOT get
/// labeled "not yet semantically verified" — that label is true for
/// `Reachability`-tier resolutions only. `FormalProof` is semantically
/// verified at compile time; `Execution` is verified by an executed test run.
fn print_audit_summary(audit_report: &audit::AuditReport) {
    let formal_proof_count = audit_report
        .audits
        .iter()
        .filter(|a| a.witness_tier == audit::WitnessTier::FormalProof)
        .count();
    let execution_count = audit_report
        .audits
        .iter()
        .filter(|a| a.witness_tier == audit::WitnessTier::Execution)
        .count();
    // `Resolved` status entries that aren't FormalProof or Execution sit at
    // Reachability — the original "declared but not semantically verified"
    // case. resolved_count is the total of Resolved entries from the
    // AuditReport bookkeeping; the remainder after subtracting the higher
    // tiers is what stays at Reachability.
    let reachability_resolved_count = audit_report
        .resolved_count
        .saturating_sub(formal_proof_count + execution_count);

    println!("Audited {} immunity claim(s):", audit_report.audits.len());
    if formal_proof_count > 0 {
        println!(
            "  - {formal_proof_count} formal-proof (phantom-type or formal-verification \
             tool — compile-time evidence)"
        );
    }
    if execution_count > 0 {
        println!("  - {execution_count} execution (test/proptest run confirmed by audit)");
    }
    println!(
        "  - {reachability_resolved_count} declared (witness identifier found in \
         workspace — not yet semantically verified)"
    );
    println!(
        "  - {} external (delegated to clippy/kani/prusti/etc. — not yet executed by antigen)",
        audit_report.external_count
    );
    println!(
        "  - {} ambiguous (witness name resolves to multiple workspace functions)",
        audit_report.ambiguous_count
    );
    println!(
        "  - {} broken (witness identifier not found)",
        audit_report.broken_count
    );
    println!(
        "  - {} missing (no witness identifier)",
        audit_report.missing_count
    );
}

/// Confirmed-immunity-claims block per ATK-A3-019 (A3.5 onboarding sweep).
///
/// Parallel to the warnings block but for the positive case: lists immunity
/// claims whose witness reached `Execution` or `FormalProof` tier — the
/// audit tiers that represent confirmed evidence rather than mere
/// reachability. Without this block, a `FormalProof` claim (phantom-type
/// witness) was invisible in human-readable output; the warnings block only
/// surfaces below-Execution claims.
fn print_confirmed_immunity_claims(audit_report: &audit::AuditReport) {
    let confirmed: Vec<&audit::ImmunityAudit> = audit_report
        .audits
        .iter()
        .filter(|a| a.witness_tier >= audit::WitnessTier::Execution)
        .collect();
    if confirmed.is_empty() {
        return;
    }
    println!(
        "{} immunity claim(s) at Execution tier or higher:",
        confirmed.len()
    );
    println!();
    for a in &confirmed {
        let i = &a.immunity;
        println!(
            "  {}:{}  {} (witness = `{}`)",
            i.file.display(),
            i.line,
            i.antigen_type,
            i.witness
        );
        println!("    tier = {:?}, hint = {:?}", a.witness_tier, a.audit_hint);
    }
    println!();
}

fn print_state7_diagnostics(audit_report: &audit::AuditReport) {
    // ADR-018 §"Audit diagnostic text": state-7 warnings (inherited
    // Presentations lacking re-attestation on the descendant site).
    if audit_report.inherited_unaddressed.is_empty() {
        return;
    }
    println!();
    println!(
        "{} inherited presentation(s) not re-attested on the descendant \
         (state 7 of the 7-state interaction matrix):",
        audit_report.inherited_unaddressed.len()
    );
    println!();
    for iu in &audit_report.inherited_unaddressed {
        let p = &iu.presentation;
        let ancestors: Vec<String> = p
            .inherited_from
            .as_ref()
            .map(|chain| chain.iter().map(|pe| pe.antigen_type.clone()).collect())
            .unwrap_or_default();
        println!(
            "  warning: inherited presentation: `{}` flowed from {:?} \
             to `{}` via `#[descended_from]`;",
            p.antigen_type, ancestors, p.item_kind
        );
        println!(
            "  the witness inherited from the ancestor has not been \
             re-attested on the descendant."
        );
        println!(
            "  Add `#[defended_by({})]` on a test (code-tier), or \
             `#[presents({}, requires = ...)]` for substrate-witness evidence, or \
             `#[antigen_tolerance({}, rationale = \"...\")]` on the descendant.",
            p.antigen_type, p.antigen_type, p.antigen_type
        );
        println!("    --> {}:{}", p.file.display(), p.line);
        println!();
    }
    println!(
        "  Note: behavioral re-validation (does the ancestor's witness \
         apply to the descendant?) is A4-A5 work; reachability-tier \
         audit cannot perform this check."
    );
    println!(
        "  Use `cargo antigen audit --strict` to promote state-7 \
         warnings to errors for CI gating."
    );
}