antigen-macros 0.3.0

Procedural macros for the antigen crate. Not for direct use; use antigen instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
//! Argument parsing for the antigen attribute macros.
//!
//! ## Span discipline (W4)
//!
//! Validation errors point at the offending token, not the whole macro
//! invocation. Each parsed field carries its own `proc_macro2::Span` (the
//! span of the *value* literal, e.g., the `""` in `name = ""`). For
//! missing-required-field errors there is no offending token — those errors
//! are anchored at `args_span`, the span of the macro's argument list. This
//! is consistently better than `Span::call_site()`, which points at the
//! whole `#[antigen(...)]` invocation.

use proc_macro2::Span;
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Expr, Ident, Lit, LitStr, Path, Token};

// ============================================================================
// RequiresExpr is now defined in antigen-attestation behind the `parser`
// feature so the scan layer can re-use the same parser without depending on
// macro expansion. See `antigen_attestation::parser` for the implementation
// and the JSON-format contract.
//
// The macro side re-exports the types so existing call-sites compile
// unchanged; both sides round-trip through `serde_json` and the runtime
// `antigen_attestation::Predicate` type.
// ============================================================================

pub use antigen_attestation::parser::RequiresExpr;

// LeafExpr is only used by the depth-guard regression tests below; pull it
// in there via `super::*` rather than re-exporting from the macro crate's
// public surface (we keep the re-export of RequiresExpr because the
// ImmuneArgs / ToleranceArgs structs expose `requires: Option<(RequiresExpr,
// Span)>`).
#[cfg(test)]
use antigen_attestation::parser::LeafExpr;

// ============================================================================
// MacroAntigenCategory — local mirror of antigen::AntigenCategory (ADR-028)
//
// proc-macro crates cannot depend on the `antigen` library crate (circular
// dependency), so we maintain a local parse-time mirror. The two enums stay
// in sync; extending either requires an ADR amendment per ADR-001 C6.
// ============================================================================

/// Parse-time antigen-category variant (mirrors `antigen::AntigenCategory`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MacroAntigenCategory {
    SubstrateAlignment,
    FunctionalCorrectness,
}

impl MacroAntigenCategory {
    /// Parse from path-style expression strings produced by the proc-macro parser.
    ///
    /// Accepted forms match what a developer can write in `category = <value>`:
    /// - `SubstrateAlignment` (Pascal ident, unqualified import)
    /// - `AntigenCategory::SubstrateAlignment` (fully-qualified path)
    ///
    /// Kebab and snake are NOT accepted: they are not valid Rust path tokens and
    /// no proc-macro input source produces them.
    fn from_path_str(s: &str) -> Option<Self> {
        match s {
            "SubstrateAlignment" | "AntigenCategory::SubstrateAlignment" => {
                Some(Self::SubstrateAlignment)
            }
            "FunctionalCorrectness" | "AntigenCategory::FunctionalCorrectness" => {
                Some(Self::FunctionalCorrectness)
            }
            _ => None,
        }
    }

    #[allow(dead_code)]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::SubstrateAlignment => "substrate-alignment",
            Self::FunctionalCorrectness => "functional-correctness",
        }
    }
}

// ============================================================================
// MacroProvenance / MacroPresentation — local mirrors of
// antigen::finding::{Provenance, Presentation} (ADR-039 §C)
//
// proc-macro crates cannot depend on the `antigen` library crate (circular
// dependency), so we maintain local parse-time mirrors — the same pattern as
// MacroAntigenCategory. The provenance LADDER + the passive/active axis are the
// already-locked ADR-039 design; this is the declaration macro growing to match
// it (the AUTHORED claim the audit tier-VERIFIER checks). The mirrors stay in
// sync with `finding.rs`; extending either requires an ADR amendment.
// ============================================================================

/// Parse-time provenance ladder (mirrors `antigen::finding::Provenance`,
/// ADR-039 §C). The AUTHORED claim of *how we know this failure-class exists*:
/// a verified core (`Encountered`, `Constructable`) + two unverified tiers
/// (`Heuristic` = correlational-not-causal; `Imagined` = a tell but no demo).
///
/// This is provenance (the class's evidence basis), NOT confidence-tier
/// (suspected/named) — the tier is DIAL-DERIVED at audit, never authored.
/// Provenance sets the FLOOR the dial may graduate from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MacroProvenance {
    /// Seen in real code — highest provenance.
    Encountered,
    /// A minimal case can be built that verifiably exhibits the failure.
    Constructable,
    /// A scannable tell that correlates without a verifiable-constructable demo.
    Heuristic,
    /// Articulated from shape — a tell but no constructable demo yet (lowest).
    Imagined,
}

impl MacroProvenance {
    /// Parse from the path-style expression strings the proc-macro parser
    /// produces. Accepts the unqualified Pascal ident (`Heuristic`) and the
    /// qualified path (`Provenance::Heuristic`); kebab/snake are not valid Rust
    /// path tokens and no input source produces them (same as the category
    /// mirror).
    fn from_path_str(s: &str) -> Option<Self> {
        match s {
            "Encountered" | "Provenance::Encountered" => Some(Self::Encountered),
            "Constructable" | "Provenance::Constructable" => Some(Self::Constructable),
            "Heuristic" | "Provenance::Heuristic" => Some(Self::Heuristic),
            "Imagined" | "Provenance::Imagined" => Some(Self::Imagined),
            _ => None,
        }
    }

    #[allow(dead_code)]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Encountered => "encountered",
            Self::Constructable => "constructable",
            Self::Heuristic => "heuristic",
            Self::Imagined => "imagined",
        }
    }
}

/// Parse-time presentation axis (mirrors `antigen::finding::Presentation`,
/// ADR-039 §C): `Passive` (tooling/scan-side, the default for
/// imagined/low-provenance — no user-macro burden) vs `Active` (user-facing,
/// chosen by an encounterer).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MacroPresentation {
    /// Tooling/scan-side; the default for imagined/low-provenance classes.
    Passive,
    /// User-macro; chosen by whoever encounters the thing.
    Active,
}

impl MacroPresentation {
    /// Parse from path-style expression strings — unqualified Pascal
    /// (`Passive`) or qualified (`Presentation::Passive`).
    fn from_path_str(s: &str) -> Option<Self> {
        match s {
            "Passive" | "Presentation::Passive" => Some(Self::Passive),
            "Active" | "Presentation::Active" => Some(Self::Active),
            _ => None,
        }
    }

    #[allow(dead_code)]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Passive => "passive",
            Self::Active => "active",
        }
    }
}

/// Arguments to `#[antigen(...)]`.
#[allow(dead_code)]
// family/summary/references are captured for validation but
// not currently used in macro expansion. They will be used
// when the macro emits richer #[doc] forwards or registers
// declarations for cross-crate discovery (future ADRs).
#[derive(Debug)]
pub struct AntigenArgs {
    pub name: String,
    /// Structural fingerprint (ADR-010 grammar). `None` for verify-only antigens
    /// (ADR-009 Amendment 1): supply-chain / VCS-info-loss families whose
    /// detection-model is external-substrate (Cargo.lock, registry, git) — they
    /// have no syn-scannable source surface, so forcing a fingerprint forced them
    /// to declare a scan-surface they don't have (the ~14.8k spurious-presentation
    /// bug). Absent ⇒ verify-only: no scan-detection; audit evaluates via
    /// `requires=`/witness only.
    pub fingerprint: Option<String>,
    pub family: Option<String>,
    pub summary: Option<String>,
    pub references: Vec<String>,
    /// Antigen-category (ADR-028). Optional at parse time for backward-compat
    /// with v0.1 antigens; absence emits `antigen-category-defaulted-implicit-functional`
    /// at audit time. v0.2+ new declarations SHOULD supply this explicitly.
    pub category: Vec<MacroAntigenCategory>,
    /// Authored provenance claim (ADR-039 §C) — *how we know this failure-class
    /// exists*: `Encountered`/`Constructable` (verified core) or
    /// `Heuristic`/`Imagined` (unverified). `None` ⇒ defaults to `Imagined` (the
    /// lowest tier — an unlabeled antigen is honestly the weakest claim). This is
    /// the AUTHORED claim the audit tier-VERIFIER checks; it sets the FLOOR the
    /// dial-derived confidence may graduate from. There is no authored confidence
    /// `tier` — that is dial-derived.
    pub provenance: Option<MacroProvenance>,
    /// Authored presentation axis (ADR-039 §C) — `Passive` (tooling/scan-side, the
    /// default for low-provenance) vs `Active` (user-facing). `None` ⇒ defaults to
    /// `Passive` (the ADR-039 passive-by-default-for-low-provenance rule: imagined
    /// antigens cost nothing until someone encounters one).
    pub presentation: Option<MacroPresentation>,
    /// Span of the `name`'s string literal value.
    /// `None` only when the field was missing — see [`AntigenArgs::validate`].
    pub name_span: Option<Span>,
    /// Span of the `fingerprint`'s string literal value.
    /// `None` only when the field was missing — see [`AntigenArgs::validate`].
    pub fingerprint_span: Option<Span>,
    /// Span of the macro's argument list as a whole. Used as the fallback
    /// anchor for missing-required-field errors (no offending token).
    pub args_span: Span,
}

/// Arguments to `#[presents(antigen_type, [requires = <predicate>], [proof = <expr>])]`.
///
/// ADR-029 (R5): site-attached defense evidence folds into `#[presents]`. A
/// presents-site may optionally carry:
/// - `requires = <predicate>` — substrate-tier evidence (the predicate the audit
///   must verify against `.attest/` sidecars; same grammar as the deprecated
///   `#[immune(requires = ...)]`). The substrate-witness migration target.
/// - `proof = <expr>` — phantom-tier evidence (a type-system construction whose
///   existence is the proof, e.g. `NonPanickingProof::<T>::verified`). The
///   phantom-witness migration target.
///
/// Both are *site-attached* evidence (the evidence IS at the site). Code-tier
/// evidence (a test elsewhere) registers via `#[defended_by]` on the test, not
/// here — the R5 discriminator: evidence belongs where it is.
#[derive(Debug)]
pub struct PresentsArgs {
    #[allow(dead_code)]
    pub antigen: Path,
    /// Substrate-tier evidence (ADR-029 R5; substrate-witness predicate, ADR-019).
    pub requires: Option<(RequiresExpr, Span)>,
    /// Phantom-tier evidence (ADR-029 R5; type-system construction).
    #[allow(dead_code)]
    pub proof: Option<Expr>,
}

/// Arguments to `#[immune(antigen_type, witness = ..., [rationale = ...])]`.
///
/// Accepts EITHER `witness = <expr>` (code-tier immunity) OR
/// `requires = <predicate>` (substrate-witness predicate, ADR-019).
/// Providing both or neither is a compile error.
pub struct ImmuneArgs {
    pub antigen: Path,
    pub witness: Option<Expr>,
    /// Substrate-witness predicate (ADR-019). Mutually exclusive with `witness`.
    pub requires: Option<(RequiresExpr, Span)>,
    #[allow(dead_code)]
    pub rationale: Option<String>,
}

/// Arguments to `#[descended_from(parent_path)]`.
pub struct DescendedFromArgs {
    #[allow(dead_code)]
    pub parent: Path,
}

/// Arguments to `#[defended_by(antigen_type)]` (ADR-029).
///
/// Code-tier witness registration: a `#[test]` / proptest function declares
/// *what failure-class it defends*. The cross-reference to the presents-sites
/// it covers — and whether it actually defends them — is computed by
/// `cargo antigen audit`, not asserted here. Immunity is observed, not declared.
///
/// Single positional argument: the antigen type path (e.g.
/// `ParallelStateTrackersDiverge` or `crate::antigens::Foo`).
#[derive(Debug)]
pub struct DefendedByArgs {
    #[allow(dead_code)]
    pub antigen: Path,
}

/// Arguments to `#[antigen_tolerance(antigen, rationale = "...", until = "...", see = [...])]`.
///
/// Per ADR-011: positional antigen, required `rationale` (non-empty),
/// optional `until` (non-empty if present), optional `see` (open-vocab string array),
/// optional `requires = <predicate>` (substrate-witness sidecar predicate, ADR-019).
pub struct ToleranceArgs {
    #[allow(dead_code)]
    pub antigen: Path,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub until: Option<String>,
    pub until_span: Option<Span>,
    #[allow(dead_code)]
    pub see: Vec<String>,
    /// Optional substrate-witness sidecar predicate (ADR-019 tolerance tier).
    pub requires: Option<(RequiresExpr, Span)>,
    pub args_span: Span,
}

// ============================================================================
// AntigenArgs parsing
// ============================================================================

impl Parse for AntigenArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();

        let mut name: Option<String> = None;
        let mut name_span: Option<Span> = None;
        let mut fingerprint: Option<String> = None;
        let mut fingerprint_span: Option<Span> = None;
        let mut family: Option<String> = None;
        let mut summary: Option<String> = None;
        let mut references: Vec<String> = Vec::new();
        let mut category: Vec<MacroAntigenCategory> = Vec::new();
        let mut provenance: Option<MacroProvenance> = None;
        let mut presentation: Option<MacroPresentation> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;

        for pair in pairs {
            match pair.key.to_string().as_str() {
                "name" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    name = Some(s);
                    name_span = Some(span);
                }
                "fingerprint" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    fingerprint = Some(s);
                    fingerprint_span = Some(span);
                }
                "family" => family = Some(pair.expect_string()?),
                "summary" => summary = Some(pair.expect_string()?),
                "references" => references = pair.expect_string_array()?,
                "category" => category = pair.expect_antigen_category()?,
                "provenance" => provenance = Some(pair.expect_provenance()?),
                "presentation" => presentation = Some(pair.expect_presentation()?),
                // There is NO authored confidence `tier` — the confidence tier
                // (suspected/named) is DIAL-DERIVED at audit (ADR-039 §B), not
                // declared. Point an author who reaches for it at `provenance`,
                // which IS the authored claim (and sets the floor the dial may
                // graduate from).
                "tier" | "confidence" | "named" | "suspected" => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        "#[antigen] has no authored confidence tier — the tier \
                         (suspected/named) is dial-derived at audit (ADR-039 §B). \
                         Author `provenance = Provenance::{Encountered|Constructable|\
                         Heuristic|Imagined}` instead; provenance is the verified \
                         claim that sets the tier floor.",
                    ))
                }
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[antigen] field `{other}`; expected one of: \
                                 name, fingerprint, family, summary, references, \
                                 category, provenance, presentation"
                        ),
                    ))
                }
            }
        }

        let name =
            name.ok_or_else(|| syn::Error::new(args_span, "#[antigen] requires `name = \"...\"`"))?;
        // ADR-009 Amendment 1: `fingerprint` is no longer required. Absent ⇒
        // verify-only antigen (external-substrate detection-model; no syn-scan
        // surface). Present ⇒ validated/parsed in `validate()` as before.

        Ok(Self {
            name,
            fingerprint,
            family,
            summary,
            references,
            category,
            provenance,
            presentation,
            name_span,
            fingerprint_span,
            args_span,
        })
    }
}

impl AntigenArgs {
    pub fn validate(&self) -> syn::Result<()> {
        if self.name.is_empty() {
            return Err(syn::Error::new(
                self.name_span.unwrap_or(self.args_span),
                "#[antigen] `name` cannot be empty",
            ));
        }
        if !is_kebab_case(&self.name) {
            return Err(syn::Error::new(
                self.name_span.unwrap_or(self.args_span),
                format!(
                    "#[antigen] `name = \"{}\"` must be kebab-case (lowercase with hyphens)",
                    self.name
                ),
            ));
        }
        // ADR-009 Amendment 1: `fingerprint` is optional (verify-only antigens
        // omit it). When PRESENT it must still be non-empty + parse — an empty
        // or malformed fingerprint is a user error, distinct from a deliberate
        // absence. When absent, there is no scan-surface to validate.
        if let Some(fingerprint) = self.fingerprint.as_deref() {
            if fingerprint.is_empty() {
                return Err(syn::Error::new(
                    self.fingerprint_span.unwrap_or(self.args_span),
                    "#[antigen] `fingerprint` cannot be empty (omit the field entirely \
                     for a verify-only antigen, per ADR-009 Amendment 1)",
                ));
            }
            // W6a: per ADR-010 Amendment 3 Clause E, the fingerprint string is
            // parsed at macro-compile time so malformed fingerprints don't ship.
            // Re-anchor any Path-C parser error to the fingerprint literal's span
            // so the user sees the squiggle on the offending text.
            if let Err(parse_err) = antigen_fingerprint::Fingerprint::parse(fingerprint) {
                let anchor = self.fingerprint_span.unwrap_or(self.args_span);
                return Err(syn::Error::new(
                    anchor,
                    format!(
                        "#[antigen] `fingerprint` does not parse: {parse_err}\n\
                         (per ADR-010 Amendment 1 Path C — DSL syntax, not raw Rust expressions)"
                    ),
                ));
            }
        }
        // ADR-028: category is a SET (SubstrateAlignment | FunctionalCorrectness | both).
        // Vec<MacroAntigenCategory> must not contain duplicate entries — duplicates
        // look like hybrid antigens (len == 2) but are not.
        {
            let mut seen = std::collections::HashSet::new();
            for cat in &self.category {
                if !seen.insert(cat) {
                    return Err(syn::Error::new(
                        self.args_span,
                        "duplicate AntigenCategory variant in `category` array; \
                         each category variant may appear at most once",
                    ));
                }
            }
        }
        Ok(())
    }
}

// ============================================================================
// PresentsArgs parsing
// ============================================================================

impl Parse for PresentsArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let antigen: Path = input.parse()?;
        let mut requires: Option<(RequiresExpr, Span)> = None;
        let mut proof: Option<Expr> = None;

        while !input.is_empty() {
            input.parse::<Token![,]>()?;
            if input.is_empty() {
                break;
            }
            let key: Ident = input.parse()?;
            let key_span = key.span();
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "requires" => {
                    let pred: RequiresExpr = input.parse()?;
                    requires = Some((pred, key_span));
                }
                "proof" => {
                    proof = Some(input.parse()?);
                }
                "witness" => {
                    // Reject `witness =` on #[presents] with a clear migration message.
                    // Code-tier witnesses register via `#[defended_by(X)]` on the test
                    // function, not `witness =` on the presents-site (ADR-029 R5
                    // discriminator: evidence belongs where it is).
                    let _: Expr = input.parse()?; // consume the value
                    return Err(syn::Error::new(
                        key_span,
                        "`witness = ...` is not valid on `#[presents]`. \
                         Code-tier witnesses register via `#[defended_by(X)]` on the \
                         test/proptest function, not on the presents-site. \
                         For substrate-tier evidence use `requires = ...` here. \
                         For phantom-tier evidence use `proof = ...` here.",
                    ));
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[presents] field `{other}`; expected one of: \
                             requires, proof"
                        ),
                    ));
                }
            }
        }

        Ok(Self {
            antigen,
            requires,
            proof,
        })
    }
}

impl PresentsArgs {
    pub fn validate(&self) -> syn::Result<()> {
        // Validate the requires predicate if present.
        if let Some((pred, span)) = &self.requires {
            pred.validate(*span)?;
        }
        // ADR-029 phantom-tier guard: `proof = <expr>` must be a type-system
        // construction whose existence IS the evidence (e.g.
        // `NonPanickingProof::<T>::verified`). A STRING LITERAL — especially an
        // empty/whitespace one used as a placeholder — is not a phantom proof:
        // the audit grades any `proof = Some(_)` as FormalProof (the strongest
        // tier), so `proof = ""` would silently overclaim the strongest evidence
        // with zero substance. Reject string-literal proofs at the macro (the
        // authoring-time layer, parallel to the `#[immune] witness=` string-lit
        // guard and the non-empty-fingerprint guard). ADR-005 sub-clause F: a
        // trust-boundary input in an unhonorable shape is not a valid claim.
        if let Some(Expr::Lit(syn::ExprLit {
            lit: Lit::Str(s), ..
        })) = &self.proof
        {
            return Err(syn::Error::new_spanned(
                s,
                format!(
                    "#[presents] `proof` must be a type-system construction whose \
                     existence is the proof (e.g. `proof = NonPanickingProof::<T>::verified`), \
                     not a string literal. `proof = \"{}\"` would silently grade FormalProof \
                     (the strongest tier) at audit time with no actual phantom evidence. \
                     {}",
                    s.value(),
                    if s.value().trim().is_empty() {
                        "An empty/placeholder proof especially must not claim FormalProof."
                    } else {
                        "Drop the quotes and reference the phantom constructor directly."
                    }
                ),
            ));
        }
        Ok(())
    }

    /// If `requires` is set, return the JSON string for the predicate.
    /// The scan layer reads this from the `antigen:requires:v1:` doc marker.
    pub fn requires_json(&self) -> Option<String> {
        self.requires.as_ref().map(|(pred, _)| pred.to_json())
    }
}

// ============================================================================
// ImmuneArgs parsing
// ============================================================================

impl Parse for ImmuneArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let antigen: Path = input.parse()?;
        let mut witness: Option<Expr> = None;
        let mut requires: Option<(RequiresExpr, Span)> = None;
        let mut rationale: Option<String> = None;

        while !input.is_empty() {
            input.parse::<Token![,]>()?;
            if input.is_empty() {
                break;
            }
            let key: Ident = input.parse()?;
            let key_span = key.span();
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "witness" => {
                    witness = Some(input.parse()?);
                }
                "requires" => {
                    let pred: RequiresExpr = input.parse()?;
                    requires = Some((pred, key_span));
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[immune] field `{other}`; expected one of: \
                             witness, requires, rationale"
                        ),
                    ));
                }
            }
        }

        Ok(Self {
            antigen,
            witness,
            requires,
            rationale,
        })
    }
}

impl ImmuneArgs {
    pub fn validate(&self) -> syn::Result<()> {
        match (&self.witness, &self.requires) {
            (None, None) => Err(syn::Error::new_spanned(
                &self.antigen,
                "#[immune] requires either `witness = ...` (code-tier: a test, proptest, \
                 lint reference, formal-verification proof, or phantom-type construction) \
                 or `requires = <predicate>` (substrate-witness predicate, ADR-019). \
                 A marker without proof is not a claim.",
            )),
            (Some(_), Some((_, span))) => Err(syn::Error::new(
                *span,
                "#[immune] accepts either `witness = ...` or `requires = ...`, not both. \
                 For compound evidence across code-tier and substrate-tier (e.g., \
                 hybrid antigens per ADR-028), stack two `#[immune]` attributes on \
                 the same item — one with `witness = ...`, one with `requires = ...`. \
                 Audit treats stacked `#[immune]` attributes as independent coverage \
                 entries.",
            )),
            (_, Some((pred, span))) => pred.validate(*span),
            (Some(witness), None) => {
                // A witness must be a bare identifier or path to the verifying
                // item (a test fn, lint reference, proof, or phantom-type
                // construction). A STRING LITERAL (`witness = "my_test"`) is
                // accepted by `Expr` parsing but silently never resolves: the
                // audit-time resolver compares fn names against the witness
                // token, and a string literal carries its quote characters, so
                // it searches for a fn literally named `"my_test"` and always
                // reports "broken: no function found." Reject it loudly here —
                // the macro is the earliest, clearest place to catch the
                // mis-shape (ADR-005 sub-clause F: a trust-boundary input
                // accepted in an unhonorable shape is not a valid claim).
                if let Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Str(s),
                    ..
                }) = witness
                {
                    return Err(syn::Error::new_spanned(
                        witness,
                        format!(
                            "#[immune] `witness` must be a bare identifier or path to the \
                             verifying item (e.g. `witness = my_test`), not a string literal. \
                             `witness = \"{}\"` silently never resolves at audit time because \
                             the resolver matches function names against the token, and a \
                             string literal carries its quotes. Drop the quotes: \
                             `witness = {}`.",
                            s.value(),
                            s.value()
                        ),
                    ));
                }
                Ok(())
            }
        }
    }

    /// If `requires` is set, return the JSON string for the predicate.
    /// The scan layer reads this from the `antigen:requires:v1:` doc marker.
    pub fn requires_json(&self) -> Option<String> {
        self.requires.as_ref().map(|(pred, _)| pred.to_json())
    }
}

// ============================================================================
// DescendedFromArgs parsing
// ============================================================================

impl Parse for DescendedFromArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let parent: Path = input.parse()?;
        Ok(Self { parent })
    }
}

// ============================================================================
// DefendedByArgs parsing (ADR-029)
// ============================================================================

impl Parse for DefendedByArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let antigen: Path = input.parse()?;
        if !input.is_empty() {
            // `#[defended_by]` is a pure code-tier witness registration: it
            // carries only the failure-class it defends. Site-attached evidence
            // (`requires=`, `proof=`) folds into `#[presents]` instead (ADR-029
            // R5 discriminator: evidence belongs where it is). Reject trailing
            // tokens loudly so a developer who reaches for `#[defended_by(X,
            // witness = ...)]` (the old `#[immune]` shape) is pointed at the
            // right primitive rather than having the extra args silently dropped.
            return Err(syn::Error::new(
                input.span(),
                "#[defended_by] takes exactly one positional argument: the antigen \
                 type it defends, e.g. `#[defended_by(ParallelStateTrackersDiverge)]`. \
                 It registers a code-tier witness (a test/proptest); it does NOT carry \
                 `witness =`/`requires =`/`proof =`. Site-attached evidence folds into \
                 `#[presents]` (ADR-029).",
            ));
        }
        Ok(Self { antigen })
    }
}

// ============================================================================
// ToleranceArgs parsing (ADR-011)
// ============================================================================

impl Parse for ToleranceArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let antigen: Path = input.parse()?;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;
        let mut until: Option<String> = None;
        let mut until_span: Option<Span> = None;
        let mut see: Vec<String> = Vec::new();
        let mut requires: Option<(RequiresExpr, Span)> = None;

        while !input.is_empty() {
            input.parse::<Token![,]>()?;
            if input.is_empty() {
                break;
            }
            let key: Ident = input.parse()?;
            let key_span = key.span();
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                "until" => {
                    let lit: LitStr = input.parse()?;
                    until_span = Some(lit.span());
                    until = Some(lit.value());
                }
                "see" => {
                    let arr: syn::ExprArray = input.parse()?;
                    for elem in &arr.elems {
                        if let Expr::Lit(syn::ExprLit {
                            lit: Lit::Str(s), ..
                        }) = elem
                        {
                            see.push(s.value());
                        } else {
                            return Err(syn::Error::new_spanned(
                                elem,
                                "expected a string literal in `see` array",
                            ));
                        }
                    }
                }
                "requires" => {
                    let pred: RequiresExpr = input.parse()?;
                    requires = Some((pred, key_span));
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[antigen_tolerance] field `{other}`; expected one of: \
                             rationale, until, see, requires",
                        ),
                    ));
                }
            }
        }

        Ok(Self {
            antigen,
            rationale,
            rationale_span,
            until,
            until_span,
            see,
            requires,
            args_span,
        })
    }
}

impl ToleranceArgs {
    /// Trust-boundary checks per ADR-011 Mechanics:
    /// - rationale required and non-empty (claim without rationale is not a claim)
    /// - until non-empty if present (empty string indicates user error)
    /// - requires predicate valid if present (semantic invariants per ADR-019 R-A6)
    pub fn validate(&self) -> syn::Result<()> {
        let Some(rationale) = self.rationale.as_deref() else {
            return Err(syn::Error::new_spanned(
                &self.antigen,
                "#[antigen_tolerance] requires `rationale = \"...\"`. \
                 A tolerance without rationale is not a claim — it's a silent suppression.",
            ));
        };
        if rationale.is_empty() {
            return Err(syn::Error::new(
                self.rationale_span.unwrap_or(self.args_span),
                "#[antigen_tolerance] `rationale` must not be empty",
            ));
        }
        if let Some(until) = self.until.as_deref() {
            if until.is_empty() {
                return Err(syn::Error::new(
                    self.until_span.unwrap_or(self.args_span),
                    "#[antigen_tolerance] `until = \"\"` rejected — \
                     an empty expiry indicates user error. Use `until = \"v1.0\"` \
                     (or similar) or omit the field entirely for forever-tolerance.",
                ));
            }
        }
        if let Some((pred, span)) = &self.requires {
            pred.validate(*span)?;
        }
        Ok(())
    }

    /// If `requires` is set, return the JSON string for the predicate.
    pub fn requires_json(&self) -> Option<String> {
        self.requires.as_ref().map(|(pred, _)| pred.to_json())
    }
}

// ============================================================================
// MarkerArgs parsing (ADR-041 — the marked-unknown plane)
// ============================================================================

/// Arguments to a marked-unknown marker: `#[aura(trigger = "...")]` /
/// `#[dread(trigger = "...")]` / `#[red_flag(trigger = "...")]`.
///
/// A marked-unknown names NOTHING specific (it is the *unnameable* — at ⊥, off
/// the dial's classification axis), so — unlike `#[antigen_tolerance]` — there is
/// **no positional antigen**. The single field is the **required** `trigger`:
/// "what did you see that made you feel this?" The plane corner
/// (magnitude × existence-certainty) is FIXED by *which* marker macro is used
/// (`#[aura]` / `#[dread]` / `#[red_flag]`), NOT authored — so `magnitude` /
/// `existence_certainty` are not accepted as fields.
///
/// **Guard 3 (ADR-041): `trigger` is REQUIRED, not `Option`.** A triggerless
/// marker is the contentless "this seems off" graffiti the primitive exists to
/// prevent — it parse-rejects (and an empty `trigger = ""` rejects too). This is
/// the rationale-as-required-field sub-clause-F discipline (ADR-005 Amd2), the
/// same shape as `#[antigen_tolerance]`'s `rationale`. Only trigger *presence* is
/// enforced; *sincerity* is an un-tabled social boundary (observe-don't-declare).
#[derive(Debug)]
pub struct MarkerArgs {
    /// The required felt-trigger ("what did you see?"). Non-empty.
    pub trigger: Option<String>,
    /// Span of the `trigger` value, for a precise empty-string error.
    pub trigger_span: Option<Span>,
    /// Span of the macro's argument list, the fallback error anchor.
    pub args_span: Span,
    /// Which marker (for error messages). Set by the macro entrypoint, not parsed.
    pub marker_name: &'static str,
}

impl Parse for MarkerArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut trigger: Option<String> = None;
        let mut trigger_span: Option<Span> = None;

        // No leading positional — a marked-unknown names nothing. Parse
        // comma-separated `key = value` pairs (currently only `trigger`).
        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "trigger" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    trigger = Some(s);
                    trigger_span = Some(span);
                }
                // The plane corner is FIXED by the marker macro, never authored.
                "magnitude" | "existence_certainty" | "certainty" => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        "a marked-unknown marker's plane corner (magnitude × \
                         existence-certainty) is FIXED by which marker you use \
                         (#[aura] / #[dread] / #[red_flag]), not authored. Only \
                         `trigger = \"...\"` is a marker field.",
                    ))
                }
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown marked-unknown field `{other}`; the only field \
                             is `trigger = \"...\"` (required)"
                        ),
                    ))
                }
            }
        }

        Ok(Self {
            trigger,
            trigger_span,
            args_span,
            marker_name: "marked-unknown",
        })
    }
}

impl MarkerArgs {
    /// Set the marker name (for error messages) — the macro entrypoint stamps it.
    #[must_use]
    pub const fn with_marker(mut self, marker_name: &'static str) -> Self {
        self.marker_name = marker_name;
        self
    }

    /// Guard 3 (ADR-041): the `trigger` is REQUIRED and non-empty. A triggerless
    /// or empty-trigger marker is the contentless "this seems off" graffiti the
    /// primitive exists to prevent.
    pub fn validate(&self) -> syn::Result<()> {
        let Some(trigger) = self.trigger.as_deref() else {
            return Err(syn::Error::new(
                self.args_span,
                format!(
                    "#[{}] requires `trigger = \"...\"` — what did you see that \
                     made you feel this? A marked-unknown with no stated trigger \
                     is not an asserted observation; it's the contentless \"this \
                     seems off\" graffiti the marker exists to prevent (ADR-041 \
                     guard 3).",
                    self.marker_name
                ),
            ));
        };
        if trigger.trim().is_empty() {
            return Err(syn::Error::new(
                self.trigger_span.unwrap_or(self.args_span),
                format!(
                    "#[{}] `trigger` must not be empty — state what you saw.",
                    self.marker_name
                ),
            ));
        }
        Ok(())
    }

    /// The trigger string (validated non-empty by [`MarkerArgs::validate`]).
    #[must_use]
    pub fn trigger_str(&self) -> &str {
        self.trigger.as_deref().unwrap_or_default()
    }
}

// ============================================================================
// GeneratesArgs parsing (ADR-014)
// ============================================================================

/// Arguments to `#[antigen_generates(antigen_type, rationale = "...", ...)]`.
///
/// Per ADR-014: a macro author declares that their proc-macro / `macro_rules`
/// emits code presenting the named antigen. Applied to the macro DEFINITION
/// (e.g. the `#[proc_macro_derive(..)]` fn); the scan connects it to the macro
/// INVOCATION sites.
///
/// - antigen type (positional, required) — the failure-class the expansion presents
/// - `rationale = "..."` (required, non-empty; mirrors ADR-011) — why the
///   expansion presents this class + what the user should verify
/// - `witness_template = "..."` (optional, v2) — path hint for a witness skeleton
/// - `if_attr_present = "..."` (optional, v2) — conditional-generation guard
pub struct GeneratesArgs {
    pub antigen: Path,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    #[allow(dead_code)]
    pub witness_template: Option<String>,
    pub witness_template_span: Option<Span>,
    #[allow(dead_code)]
    pub if_attr_present: Option<String>,
    pub if_attr_present_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for GeneratesArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let antigen: Path = input.parse()?;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;
        let mut witness_template: Option<String> = None;
        let mut witness_template_span: Option<Span> = None;
        let mut if_attr_present: Option<String> = None;
        let mut if_attr_present_span: Option<Span> = None;

        while !input.is_empty() {
            input.parse::<Token![,]>()?;
            if input.is_empty() {
                break;
            }
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                "witness_template" => {
                    let lit: LitStr = input.parse()?;
                    witness_template_span = Some(lit.span());
                    witness_template = Some(lit.value());
                }
                "if_attr_present" => {
                    let lit: LitStr = input.parse()?;
                    if_attr_present_span = Some(lit.span());
                    if_attr_present = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[antigen_generates] field `{other}`; expected one of: \
                             rationale, witness_template, if_attr_present",
                        ),
                    ));
                }
            }
        }

        Ok(Self {
            antigen,
            rationale,
            rationale_span,
            witness_template,
            witness_template_span,
            if_attr_present,
            if_attr_present_span,
            args_span,
        })
    }
}

impl GeneratesArgs {
    /// Trust-boundary checks per ADR-014 §Sub-clause F:
    /// - rationale required + non-empty (a generation claim without rationale
    ///   is not a claim — the macro author must justify the pattern)
    /// - optional string fields, if present, must be non-empty (empty indicates
    ///   user error, mirroring the `until = ""` rejection on tolerance)
    pub fn validate(&self) -> syn::Result<()> {
        let Some(rationale) = self.rationale.as_deref() else {
            return Err(syn::Error::new_spanned(
                &self.antigen,
                "#[antigen_generates] requires `rationale = \"...\"`. \
                 A generation declaration without rationale is not a claim — \
                 the macro author must justify what the expansion presents.",
            ));
        };
        if rationale.is_empty() {
            return Err(syn::Error::new(
                self.rationale_span.unwrap_or(self.args_span),
                "#[antigen_generates] `rationale` must not be empty",
            ));
        }
        if matches!(self.witness_template.as_deref(), Some("")) {
            return Err(syn::Error::new(
                self.witness_template_span.unwrap_or(self.args_span),
                "#[antigen_generates] `witness_template = \"\"` rejected — \
                 omit the field rather than supplying an empty path.",
            ));
        }
        if matches!(self.if_attr_present.as_deref(), Some("")) {
            return Err(syn::Error::new(
                self.if_attr_present_span.unwrap_or(self.args_span),
                "#[antigen_generates] `if_attr_present = \"\"` rejected — \
                 omit the field rather than supplying an empty guard.",
            ));
        }
        Ok(())
    }

    /// Bare type name of the antigen this generation declaration names (last
    /// path segment), for the `antigen:generates:v1:<name>` doc marker.
    pub fn antigen_name(&self) -> String {
        self.antigen
            .segments
            .last()
            .map_or_else(String::new, |s| s.ident.to_string())
    }
}

// ============================================================================
// AnegyArgs parsing (ADR-023)
// ============================================================================

/// Arguments to `#[anergy(antigen_type, reason = "...", until = "...", ...)]`.
///
/// Per ADR-023: deferred-but-muted posture with aging escalation.
/// - `reason` required, minimum 20 characters
/// - `until` REQUIRED — anergy without time-bound degrades to tolerance (A5 absorbed)
/// - `expected_co_stimulation` advisory-only free text; NOT machine-verified
/// - `signed_by` optional signer identifier
#[derive(Debug)]
pub struct AnergyArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub reason: Option<String>,
    pub reason_span: Option<Span>,
    pub until: Option<String>,
    pub until_span: Option<Span>,
    #[allow(dead_code)]
    pub expected_co_stimulation: Option<String>,
    #[allow(dead_code)]
    pub signed_by: Option<String>,
    pub args_span: Span,
}

impl Parse for AnergyArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut reason: Option<String> = None;
        let mut reason_span: Option<Span> = None;
        let mut until: Option<String> = None;
        let mut until_span: Option<Span> = None;
        let mut expected_co_stimulation: Option<String> = None;
        let mut signed_by: Option<String> = None;

        // Optional leading positional antigen type path
        if !input.is_empty() && input.peek(Ident) && !input.peek2(Token![=]) {
            antigen = Some(input.parse()?);
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "reason" => {
                    let lit: LitStr = input.parse()?;
                    reason_span = Some(lit.span());
                    reason = Some(lit.value());
                }
                "until" => {
                    let lit: LitStr = input.parse()?;
                    until_span = Some(lit.span());
                    until = Some(lit.value());
                }
                "expected_co_stimulation" => {
                    let lit: LitStr = input.parse()?;
                    expected_co_stimulation = Some(lit.value());
                }
                "signed_by" => {
                    let lit: LitStr = input.parse()?;
                    signed_by = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[anergy] field `{other}`; expected one of: \
                             reason, until, expected_co_stimulation, signed_by"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            reason,
            reason_span,
            until,
            until_span,
            expected_co_stimulation,
            signed_by,
            args_span,
        })
    }
}

impl AnergyArgs {
    /// Trust-boundary checks per ADR-023:
    /// - `reason` required and minimum 20 characters
    /// - `until` REQUIRED (A5 absorbed: anergy without time-bound = silent tolerance)
    /// - `until` must be non-empty
    pub fn validate(&self) -> syn::Result<()> {
        // reason required + 20-char minimum
        match self.reason.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[anergy] requires `reason = \"...\"`. \
                     Anergy without a stated reason is a silent suppression.",
                ));
            }
            Some(r) if r.len() < 20 => {
                return Err(syn::Error::new(
                    self.reason_span.unwrap_or(self.args_span),
                    format!(
                        "#[anergy] `reason` must be at least 20 characters \
                         (got {}); per ADR-023 loudness-as-discipline.",
                        r.len()
                    ),
                ));
            }
            Some(r) if r.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.reason_span.unwrap_or(self.args_span),
                    "#[anergy] `reason` must not be whitespace-only; \
                     a blank reason bypasses the loudness-as-discipline \
                     requirement (ADR-023).",
                ));
            }
            _ => {}
        }

        // until REQUIRED (A5)
        match self.until.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[anergy] requires `until = \"YYYY-MM-DD\"`. \
                     Anergy without a time-bound degrades to silent tolerance. \
                     Per ADR-023 A5: `until` is not optional.",
                ));
            }
            Some("") => {
                return Err(syn::Error::new(
                    self.until_span.unwrap_or(self.args_span),
                    "#[anergy] `until` must not be empty. \
                     Use a date string, e.g. `until = \"2026-12-31\"`.",
                ));
            }
            _ => {}
        }

        // Past-date rejection: an expired anergy window means the suppression
        // should have been re-evaluated but wasn't. Parallels OrientArgs (53d2bab).
        if let Some(until_str) = self.until.as_deref() {
            match parse_iso_date(until_str) {
                Ok(until_date) => {
                    let horizon_days = (until_date - today_utc()).num_days();
                    if horizon_days < 0 {
                        return Err(syn::Error::new(
                            self.until_span.unwrap_or(self.args_span),
                            format!(
                                "#[anergy] `until` ({until_str}) is {} day(s) in the past — \
                                 an already-expired anergy window is silent suppression with \
                                 no accountability. Set a future `until` date or remove the \
                                 #[anergy] marker.",
                                -horizon_days
                            ),
                        ));
                    }
                }
                Err(()) => {
                    return Err(syn::Error::new(
                        self.until_span.unwrap_or(self.args_span),
                        format!(
                            "#[anergy] `until` value {until_str:?} is not a valid ISO-8601 \
                             date. Use YYYY-MM-DD format, e.g. `until = \"2026-12-31\"`."
                        ),
                    ));
                }
            }
        }

        Ok(())
    }
}

// ============================================================================
// ImmunosuppressArgs parsing (ADR-023)
// ============================================================================

/// Arguments to `#[immunosuppress(antigen_type, rationale = "...", until = "...", ...)]`.
///
/// Per ADR-023: surgical family-of-checks silencing with hard duration cap.
/// - `rationale` required, minimum 20 characters
/// - `until` required
/// - `since` optional ISO-8601 date; defaults to "now" for cap calculation
/// - `duration_cap` optional override (days); defaults to workspace 90d cap
/// - `signed_by` optional
/// - Compile error if implied duration exceeds cap (A4 absorbed)
#[derive(Debug)]
pub struct ImmunosuppressArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub until: Option<String>,
    pub until_span: Option<Span>,
    #[allow(dead_code)]
    pub since: Option<String>,
    pub duration_cap: Option<u64>,
    pub duration_cap_span: Option<Span>,
    #[allow(dead_code)]
    pub signed_by: Option<String>,
    pub args_span: Span,
}

impl Parse for ImmunosuppressArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        use syn::LitInt;
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;
        let mut until: Option<String> = None;
        let mut until_span: Option<Span> = None;
        let mut since: Option<String> = None;
        let mut duration_cap: Option<u64> = None;
        let mut duration_cap_span: Option<Span> = None;
        let mut signed_by: Option<String> = None;

        // Optional leading positional antigen type path
        if !input.is_empty() && input.peek(Ident) && !input.peek2(Token![=]) {
            antigen = Some(input.parse()?);
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                "until" => {
                    let lit: LitStr = input.parse()?;
                    until_span = Some(lit.span());
                    until = Some(lit.value());
                }
                "since" => {
                    let lit: LitStr = input.parse()?;
                    since = Some(lit.value());
                }
                "duration_cap" => {
                    let lit: LitInt = input.parse()?;
                    duration_cap_span = Some(lit.span());
                    duration_cap = Some(lit.base10_parse::<u64>()?);
                }
                "signed_by" => {
                    let lit: LitStr = input.parse()?;
                    signed_by = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[immunosuppress] field `{other}`; expected one of: \
                             rationale, until, since, duration_cap, signed_by"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            rationale,
            rationale_span,
            until,
            until_span,
            since,
            duration_cap,
            duration_cap_span,
            signed_by,
            args_span,
        })
    }
}

/// Default immunosuppression duration cap per ADR-023 (90 days).
pub const IMMUNOSUPPRESS_DEFAULT_CAP_DAYS: u64 = 90;

/// Default `#[orient]` orientation-period horizon per ADR-023
/// (`deferred_defense_max_horizon`, 180 days). `until` dates beyond
/// `now + this` are rejected at parse time.
pub const ORIENT_DEFAULT_MAX_HORIZON_DAYS: i64 = 180;

impl ImmunosuppressArgs {
    /// Trust-boundary checks per ADR-023:
    /// - `rationale` required and minimum 20 characters
    /// - `until` required
    /// - implied duration (until - since) must not exceed cap; COMPILE ERROR if exceeded (A4)
    pub fn validate(&self) -> syn::Result<()> {
        // rationale required + 20-char minimum
        match self.rationale.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[immunosuppress] requires `rationale = \"...\"`. \
                     Immunosuppression without rationale is not a claim.",
                ));
            }
            Some(r) if r.len() < 20 => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    format!(
                        "#[immunosuppress] `rationale` must be at least 20 characters \
                         (got {}); per ADR-023 loudness-as-discipline.",
                        r.len()
                    ),
                ));
            }
            Some(r) if r.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    "#[immunosuppress] `rationale` must not be whitespace-only; \
                     a blank rationale bypasses the loudness-as-discipline \
                     requirement (ADR-023).",
                ));
            }
            _ => {}
        }

        // until required
        match self.until.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[immunosuppress] requires `until = \"YYYY-MM-DD\"`. \
                     Suppression without a deadline is indefinite suppression.",
                ));
            }
            Some("") => {
                return Err(syn::Error::new(
                    self.until_span.unwrap_or(self.args_span),
                    "#[immunosuppress] `until` must not be empty.",
                ));
            }
            _ => {}
        }

        // Duration cap enforcement (A4 absorbed): parse-time COMPILE ERROR
        // if until - since > cap days. This closes the audit-only gap.
        let cap = self.duration_cap.unwrap_or(IMMUNOSUPPRESS_DEFAULT_CAP_DAYS);
        // Use i64 throughout to avoid cast_possible_wrap: cap is workspace-configured
        // and guaranteed small (default 90); casting is safe but use i64 directly.
        let cap_i64 = i64::try_from(cap).unwrap_or(i64::MAX);
        if let Some(until_str) = self.until.as_deref() {
            match parse_iso_date(until_str) {
                Ok(until_date) => {
                    let since_date = self
                        .since
                        .as_deref()
                        .and_then(|s| parse_iso_date(s).ok())
                        .unwrap_or_else(today_utc);
                    let duration_days = (until_date - since_date).num_days();
                    if duration_days < 0 {
                        return Err(syn::Error::new(
                            self.until_span.unwrap_or(self.args_span),
                            format!(
                                "#[immunosuppress] `until` ({}) is {} day(s) in the past — \
                                 an expired suppression window is silent check-disabling with \
                                 no accountability. Set a future `until` date or remove the \
                                 #[immunosuppress] marker.",
                                until_str, -duration_days
                            ),
                        ));
                    }
                    if duration_days > cap_i64 {
                        return Err(syn::Error::new(
                            self.until_span
                                .unwrap_or_else(|| self.duration_cap_span.unwrap_or(self.args_span)),
                            format!(
                                "#[immunosuppress] duration {duration_days}d exceeds cap {cap_i64}d. \
                                 Per ADR-023: duration cap enforced at parse-time. \
                                 Reduce the `until` date or set `duration_cap = N` (workspace \
                                 default is {IMMUNOSUPPRESS_DEFAULT_CAP_DAYS}d)."
                            ),
                        ));
                    }
                }
                Err(()) => {
                    return Err(syn::Error::new(
                        self.until_span.unwrap_or(self.args_span),
                        format!(
                            "#[immunosuppress] `until` value {until_str:?} is not a valid \
                             ISO-8601 date. Use YYYY-MM-DD format, e.g. `until = \"2026-12-31\"`."
                        ),
                    ));
                }
            }
        }

        Ok(())
    }
}

// ============================================================================
// PoxpartyArgs parsing (ADR-023)
// ============================================================================

/// Arguments to `#[poxparty(antigen_type, exercise_type = "...", until = "...", ...)]`.
///
/// Per ADR-023: intentional exposure with structural compile-time isolation.
///
/// CRITICAL (A3 absorbed): the proc-macro checks `CARGO_FEATURE_ANTIGEN_POXPARTY`
/// env var at macro-expansion time and emits a COMPILE ERROR if the feature is
/// not active. This closes the production-isolation gap — poxparty code cannot
/// compile in a build where the `antigen-poxparty` Cargo feature is absent.
///
/// The `antigen-poxparty` feature MUST NOT be in the default feature set.
///
/// - `exercise_type` required, minimum 20 characters
/// - `until` required
/// - `name` optional descriptive name
/// - `rationale` optional additional context
/// - `signed_by` optional
#[derive(Debug)]
pub struct PoxpartyArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub exercise_type: Option<String>,
    pub exercise_type_span: Option<Span>,
    pub until: Option<String>,
    pub until_span: Option<Span>,
    #[allow(dead_code)]
    pub name: Option<String>,
    #[allow(dead_code)]
    pub rationale: Option<String>,
    #[allow(dead_code)]
    pub signed_by: Option<String>,
    pub args_span: Span,
}

impl Parse for PoxpartyArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut exercise_type: Option<String> = None;
        let mut exercise_type_span: Option<Span> = None;
        let mut until: Option<String> = None;
        let mut until_span: Option<Span> = None;
        let mut name: Option<String> = None;
        let mut rationale: Option<String> = None;
        let mut signed_by: Option<String> = None;

        // Optional leading positional antigen type path
        if !input.is_empty() && input.peek(Ident) && !input.peek2(Token![=]) {
            antigen = Some(input.parse()?);
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "exercise_type" => {
                    let lit: LitStr = input.parse()?;
                    exercise_type_span = Some(lit.span());
                    exercise_type = Some(lit.value());
                }
                "until" => {
                    let lit: LitStr = input.parse()?;
                    until_span = Some(lit.span());
                    until = Some(lit.value());
                }
                "name" => {
                    let lit: LitStr = input.parse()?;
                    name = Some(lit.value());
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale = Some(lit.value());
                }
                "signed_by" => {
                    let lit: LitStr = input.parse()?;
                    signed_by = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[poxparty] field `{other}`; expected one of: \
                             exercise_type, until, name, rationale, signed_by"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            exercise_type,
            exercise_type_span,
            until,
            until_span,
            name,
            rationale,
            signed_by,
            args_span,
        })
    }
}

impl PoxpartyArgs {
    /// Trust-boundary checks per ADR-023:
    /// - `exercise_type` required and minimum 20 characters
    /// - `until` required
    ///
    /// Note: structural isolation is two-layer — primary via
    /// `#[cfg(feature = "antigen-poxparty")]` on the containing module (cfg
    /// gate prevents expansion when feature absent), secondary via the
    /// `CARGO_FEATURE_ANTIGEN_POXPARTY` env var check in the entry point.
    /// Neither check is in the parser.
    pub fn validate(&self) -> syn::Result<()> {
        // exercise_type required + 20-char minimum
        match self.exercise_type.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[poxparty] requires `exercise_type = \"...\"`. \
                     Per ADR-023: describes the controlled exposure exercise.",
                ));
            }
            Some(et) if et.len() < 20 => {
                return Err(syn::Error::new(
                    self.exercise_type_span.unwrap_or(self.args_span),
                    format!(
                        "#[poxparty] `exercise_type` must be at least 20 characters \
                         (got {}); per ADR-023 loudness-as-discipline.",
                        et.len()
                    ),
                ));
            }
            Some(et) if et.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.exercise_type_span.unwrap_or(self.args_span),
                    "#[poxparty] `exercise_type` must not be whitespace-only; \
                     a blank exercise type bypasses the loudness-as-discipline \
                     requirement (ADR-023).",
                ));
            }
            _ => {}
        }

        // until required
        match self.until.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[poxparty] requires `until = \"YYYY-MM-DD\"`. \
                     A pox party without a deadline runs indefinitely.",
                ));
            }
            Some("") => {
                return Err(syn::Error::new(
                    self.until_span.unwrap_or(self.args_span),
                    "#[poxparty] `until` must not be empty.",
                ));
            }
            _ => {}
        }

        // Past-date rejection: an expired pox-party window is stale controlled
        // exposure with no accountability. Parallels OrientArgs (53d2bab).
        if let Some(until_str) = self.until.as_deref() {
            match parse_iso_date(until_str) {
                Ok(until_date) => {
                    let horizon_days = (until_date - today_utc()).num_days();
                    if horizon_days < 0 {
                        return Err(syn::Error::new(
                            self.until_span.unwrap_or(self.args_span),
                            format!(
                                "#[poxparty] `until` ({until_str}) is {} day(s) in the past — \
                                 an expired pox-party exercise is stale controlled exposure with \
                                 no accountability. Set a future `until` date or remove the \
                                 #[poxparty] marker.",
                                -horizon_days
                            ),
                        ));
                    }
                }
                Err(()) => {
                    return Err(syn::Error::new(
                        self.until_span.unwrap_or(self.args_span),
                        format!(
                            "#[poxparty] `until` value {until_str:?} is not a valid ISO-8601 \
                             date. Use YYYY-MM-DD format, e.g. `until = \"2026-12-31\"`."
                        ),
                    ));
                }
            }
        }

        Ok(())
    }
}

// ============================================================================
// OrientArgs parsing (ADR-023)
// ============================================================================

/// Arguments to `#[orient(antigen, learning_path, until)]`.
///
/// Per ADR-023 §Decision + aristotle's `orient-field-optionality-ruling`
/// (Option A, hard break): orient acknowledges a pre-immunity learning period
/// and `learning_path` + `until` are **both REQUIRED** — they are the
/// accountability fields the primitive exists to impose. Making them optional
/// would collapse `#[orient]` to structurally-identical-to-silent-tolerance,
/// the exact A5 failure the deferred-defense family was built to prevent
/// (loudness-as-discipline). A bare `#[orient]` is therefore a parse error.
///
/// The pre-restoration drift-form fields (`see`, `adr`, `attestation_optional`)
/// are NOT in the ADR-023 spec — they were the drift — and are REMOVED
/// entirely (a hard parse error, not a deprecation window).
///
/// Decisional rollback-as-triage uses are handled by `#[triage_commit]`
/// (sibling primitive per ADR-026 Amendment 1), NOT by `#[orient]`.
///
/// - `<antigen-path>` (optional positional) — failure-class antigen path
/// - `learning_path = "..."` (REQUIRED, 20-char-min, rationale-class) — the
///   explicit path forward out of the learning period
/// - `until = "YYYY-MM-DD"` (REQUIRED) — orientation-period horizon; non-empty,
///   UTC, parse-validated, rejected if beyond `now + deferred_defense_max_horizon`
///   (180d default)
#[derive(Debug)]
pub struct OrientArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    #[allow(dead_code)]
    pub learning_path: Option<String>,
    /// Span of the `learning_path` value, for anchoring validation errors.
    #[allow(dead_code)]
    pub learning_path_span: Option<Span>,
    #[allow(dead_code)]
    pub until: Option<String>,
    /// Span of the `until` value (for anchoring validation errors).
    #[allow(dead_code)]
    pub until_span: Option<Span>,
    #[allow(dead_code)]
    pub args_span: Span,
}

impl Parse for OrientArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut learning_path: Option<String> = None;
        let mut learning_path_span: Option<Span> = None;
        let mut until: Option<String> = None;
        let mut until_span: Option<Span> = None;

        // Optional leading positional antigen type path.
        if !input.is_empty() && input.peek(Ident) && !input.peek2(Token![=]) {
            antigen = Some(input.parse()?);
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "learning_path" => {
                    let lit: LitStr = input.parse()?;
                    learning_path_span = Some(lit.span());
                    learning_path = Some(lit.value());
                }
                "until" => {
                    let lit: LitStr = input.parse()?;
                    until_span = Some(lit.span());
                    until = Some(lit.value());
                }
                // The drift-form fields (see/adr/attestation_optional) are NOT
                // in the ADR-023 spec; restoration removes them. A clear error
                // names the migration target rather than silently accepting.
                "see" | "adr" | "attestation_optional" => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "#[orient] field `{key}` was removed in the ADR-023 restoration \
                             (it was never in the spec). The orient spec is \
                             `#[orient(<antigen>, learning_path = \"...\", until = \"YYYY-MM-DD\")]`. \
                             Migrate `see`/`adr` context into the `learning_path` text (or \
                             `references = [...]` on the antigen declaration); \
                             `attestation_optional` inverted loudness-as-discipline and has no \
                             replacement."
                        ),
                    ));
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[orient] field `{other}`; expected: learning_path, until"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            learning_path,
            learning_path_span,
            until,
            until_span,
            args_span,
        })
    }
}

impl OrientArgs {
    /// Trust-boundary checks per ADR-023 §Decision + the Option-A
    /// (hard-break) ruling:
    /// - `learning_path` REQUIRED, minimum 20 characters (rationale-class).
    /// - `until` REQUIRED, non-empty, UTC-parseable, and within
    ///   `now + ORIENT_DEFAULT_MAX_HORIZON_DAYS` (180d) — a horizon beyond that
    ///   is a parse-time COMPILE ERROR.
    ///
    /// A bare `#[orient]` (neither field) fails on the first check. Optionality
    /// is rejected on first principles: an orient without an explicit path-out
    /// and a time-bound is silent deferred non-immunity — exactly tolerance,
    /// which this loud primitive exists to be distinct from.
    pub fn validate(&self) -> syn::Result<()> {
        // learning_path required + 20-char minimum.
        match self.learning_path.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[orient] requires `learning_path = \"...\"`. An orientation period \
                     without an explicit path forward is silent deferred non-immunity \
                     (= tolerance); orient exists to be loud about it (ADR-023).",
                ));
            }
            Some(p) if p.len() < 20 => {
                return Err(syn::Error::new(
                    self.learning_path_span.unwrap_or(self.args_span),
                    format!(
                        "#[orient] `learning_path` must be at least 20 characters (got {}); \
                         per ADR-023 loudness-as-discipline (rationale-class field).",
                        p.len()
                    ),
                ));
            }
            Some(p) if p.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.learning_path_span.unwrap_or(self.args_span),
                    "#[orient] `learning_path` must not be whitespace-only; \
                     a blank learning path bypasses the loudness-as-discipline \
                     requirement (ADR-023).",
                ));
            }
            _ => {}
        }

        // until required + non-empty.
        let until_str = match self.until.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[orient] requires `until = \"YYYY-MM-DD\"`. An orientation period \
                     without a time-bound is indefinite; orient must escalate at a horizon.",
                ));
            }
            Some("") => {
                return Err(syn::Error::new(
                    self.until_span.unwrap_or(self.args_span),
                    "#[orient] `until` must not be empty.",
                ));
            }
            Some(s) => s,
        };

        // Horizon enforcement: until must parse as a UTC date and must not be
        // beyond now + max_horizon (180d default). Parse-time COMPILE ERROR.
        match parse_iso_date(until_str) {
            Err(()) => {
                return Err(syn::Error::new(
                    self.until_span.unwrap_or(self.args_span),
                    format!(
                        "#[orient] `until` must be an ISO-8601 date (YYYY-MM-DD); got `{until_str}`."
                    ),
                ));
            }
            Ok(until_date) => {
                let horizon_days = (until_date - today_utc()).num_days();
                // A past `until` is an already-expired orientation window: it
                // says "we never addressed this failure-class AND the
                // accountability horizon has already passed" — silent expired
                // non-immunity, the exact thing orient's loudness prevents. The
                // too-far-future check below uses `> MAX`, which is false for
                // negative values, so a past date would otherwise pass silently.
                if horizon_days < 0 {
                    return Err(syn::Error::new(
                        self.until_span.unwrap_or(self.args_span),
                        format!(
                            "#[orient] `until` ({until_str}) is {} day(s) in the past — an \
                             already-expired orientation window. Set a future horizon, or if \
                             the period has genuinely lapsed, resolve the failure-class \
                             (declare immunity/tolerance) rather than leave an expired orient.",
                            -horizon_days
                        ),
                    ));
                }
                if horizon_days > ORIENT_DEFAULT_MAX_HORIZON_DAYS {
                    return Err(syn::Error::new(
                        self.until_span.unwrap_or(self.args_span),
                        format!(
                            "#[orient] `until` is {horizon_days}d out, beyond the \
                             {ORIENT_DEFAULT_MAX_HORIZON_DAYS}d orientation-period horizon \
                             (deferred_defense_max_horizon). An orientation period this long \
                             is not orientation — shorten `until` or address the failure-class."
                        ),
                    ));
                }
            }
        }

        Ok(())
    }
}

// ============================================================================
// MacroTriageDecision — local mirror of antigen::TriageDecision (ADR-026)
//
// proc-macro crates cannot depend on the `antigen` library crate (circular
// dependency), so we maintain a local parse-time mirror — same pattern as
// MacroAntigenCategory for ADR-028. The two enums stay in sync; extending
// either requires an ADR amendment per ADR-001 Amendment 1 C6.
// ============================================================================

/// Parse-time triage-decision variant (mirrors `antigen::vcs::TriageDecision`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroTriageDecision {
    /// System-down / data-loss imminent / catastrophic regression confirmed.
    Black,
    /// Vital-metric regression confirmed; tight-time-window rollback.
    Red,
    /// Concerning signal; investigation pending; rollback decision deferred.
    Yellow,
    /// No functional regression; analysis chain attests non-regression.
    Green,
    /// Out of scope for this triage event; explicit non-action chart entry.
    White,
}

impl MacroTriageDecision {
    /// Parse from path-style expression strings and common aliases.
    fn from_path_str(s: &str) -> Option<Self> {
        match s {
            "Black" | "TriageDecision::Black" | "black" => Some(Self::Black),
            "Red" | "TriageDecision::Red" | "red" => Some(Self::Red),
            "Yellow" | "TriageDecision::Yellow" | "yellow" => Some(Self::Yellow),
            "Green" | "TriageDecision::Green" | "green" => Some(Self::Green),
            "White" | "TriageDecision::White" | "white" => Some(Self::White),
            _ => None,
        }
    }

    /// Kebab-case string form mirroring `antigen::vcs::TriageDecision::as_str()`.
    ///
    /// Reserved for future audit-hint emission paths — kept on the parse-time
    /// mirror so the proc-macro crate doesn't need to import `antigen`
    /// (circular dep) when hint detail strings grow.
    #[allow(dead_code)]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Black => "black",
            Self::Red => "red",
            Self::Yellow => "yellow",
            Self::Green => "green",
            Self::White => "white",
        }
    }
}

// ============================================================================
// TriageCommitArgs parsing (ADR-026 §Rollback-as-triage primitive)
//
// `#[triage_commit]` is the rollback-as-triage primitive ratified by ADR-026
// §Decision. Per aristotle's fixup-orient-dual-signature F1-F5 resolution
// (camp note 55a161e7), `#[triage_commit]` is a SIBLING primitive to
// `#[orient]`, NOT an extension — orient names a failure-class (acknowledged
// pre-immunity); triage_commit names a system-state-classification + commit
// to a rollback action within a time-bound. The clinical-medicine grounding
// (chart documentation + informed consent before procedure) is dual-axis-
// acknowledged per ADR-024 + ADR-026 dual-axis discipline.
// ============================================================================

/// Arguments to `#[triage_commit(triage_decision = ..., rollback_target = ...,
/// triaged_by = ..., rationale = ..., rollback_due_within_minutes = ...)]`.
///
/// All five fields are REQUIRED per ADR-026 §Decision rollback-as-triage
/// primitive. Per ADR-026 §Rollback-as-triage discipline (NON-NEGOTIABLE
/// per naturalist): the chart-documentation cognate demands the rationale +
/// `triaged_by` + time-bound be present before the action commits, NOT after.
///
/// Loudness-as-discipline (ADR-023 central pattern applied here): missing
/// fields are compile-time errors so a triage commit that elides documentation
/// cannot reach `git push`.
#[derive(Debug)]
pub struct TriageCommitArgs {
    pub triage_decision: Option<MacroTriageDecision>,
    /// Span of the `triage_decision` value (path expression). Reserved for
    /// future audit-hint emission paths that need to point error reports at
    /// the variant token; presently unused.
    #[allow(dead_code)]
    pub triage_decision_span: Option<Span>,
    pub rollback_target: Option<String>,
    pub rollback_target_span: Option<Span>,
    pub triaged_by: Option<String>,
    pub triaged_by_span: Option<Span>,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub rollback_due_within_minutes: Option<u32>,
    pub rollback_due_within_minutes_span: Option<Span>,
    pub args_span: Span,
}

/// Parse `triage_decision = TriageDecision::X` from a path expression.
/// Extracted from `Parse for TriageCommitArgs` to keep that impl under 100 lines.
fn parse_triage_decision_expr(
    input: syn::parse::ParseStream,
    expr: &Expr,
) -> syn::Result<(MacroTriageDecision, Span)> {
    let expr_span = match expr {
        Expr::Path(p) => p
            .path
            .segments
            .first()
            .map_or_else(|| input.span(), |s| s.ident.span()),
        _ => input.span(),
    };
    let s = match expr {
        Expr::Path(p) => {
            let segs: Vec<String> = p
                .path
                .segments
                .iter()
                .map(|seg| seg.ident.to_string())
                .collect();
            segs.join("::")
        }
        _ => {
            return Err(syn::Error::new_spanned(
                expr,
                "expected `TriageDecision::Black`, `TriageDecision::Red`, \
                 `TriageDecision::Yellow`, `TriageDecision::Green`, or \
                 `TriageDecision::White`",
            ));
        }
    };
    let decision = MacroTriageDecision::from_path_str(&s).ok_or_else(|| {
        syn::Error::new_spanned(
            expr,
            format!(
                "unknown TriageDecision `{s}`; expected one of: Black, Red, \
                 Yellow, Green, White"
            ),
        )
    })?;
    Ok((decision, expr_span))
}

impl Parse for TriageCommitArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut triage_decision: Option<MacroTriageDecision> = None;
        let mut triage_decision_span: Option<Span> = None;
        let mut rollback_target: Option<String> = None;
        let mut rollback_target_span: Option<Span> = None;
        let mut triaged_by: Option<String> = None;
        let mut triaged_by_span: Option<Span> = None;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;
        let mut rollback_due_within_minutes: Option<u32> = None;
        let mut rollback_due_within_minutes_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "triage_decision" => {
                    let expr: Expr = input.parse()?;
                    let (decision, span) = parse_triage_decision_expr(input, &expr)?;
                    triage_decision = Some(decision);
                    triage_decision_span = Some(span);
                }
                "rollback_target" => {
                    let lit: LitStr = input.parse()?;
                    rollback_target_span = Some(lit.span());
                    rollback_target = Some(lit.value());
                }
                "triaged_by" => {
                    let lit: LitStr = input.parse()?;
                    triaged_by_span = Some(lit.span());
                    triaged_by = Some(lit.value());
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                "rollback_due_within_minutes" => {
                    let lit: syn::LitInt = input.parse()?;
                    rollback_due_within_minutes_span = Some(lit.span());
                    rollback_due_within_minutes = Some(lit.base10_parse::<u32>()?);
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[triage_commit] field `{other}`; expected one of: \
                             triage_decision, rollback_target, triaged_by, rationale, \
                             rollback_due_within_minutes"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            triage_decision,
            triage_decision_span,
            rollback_target,
            rollback_target_span,
            triaged_by,
            triaged_by_span,
            rationale,
            rationale_span,
            rollback_due_within_minutes,
            rollback_due_within_minutes_span,
            args_span,
        })
    }
}

impl TriageCommitArgs {
    /// Trust-boundary checks per ADR-026 §Decision rollback-as-triage:
    /// - `triage_decision` REQUIRED — the loud-acknowledgment IS the discipline
    /// - `rollback_target` REQUIRED, non-empty — sha pointer to last-known-good
    /// - `triaged_by` REQUIRED, non-empty — informed-consent author identity
    /// - `rationale` REQUIRED, minimum 20 characters — chart-documentation
    ///   discipline per naturalist's clinical-medicine grounding
    ///   (parallel to `#[anergy]` 20-char floor)
    /// - `rollback_due_within_minutes` REQUIRED, positive — tight time-bound
    ///   carrier; 0 would mean immediate-or-never and degrades discipline
    pub fn validate(&self) -> syn::Result<()> {
        if self.triage_decision.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[triage_commit] requires `triage_decision = TriageDecision::X` \
                 (one of Black, Red, Yellow, Green, White). Per ADR-026 \
                 §Rollback-as-triage, the loud-acknowledgment IS the discipline.",
            ));
        }
        match self.rollback_target.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[triage_commit] requires `rollback_target = \"<sha>\"` \
                     (commit sha pointing to last-known-good state).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.rollback_target_span.unwrap_or(self.args_span),
                    "#[triage_commit] `rollback_target` cannot be empty or whitespace-only. \
                     A rollback without a target is not a rollback.",
                ));
            }
            Some(_) => {}
        }
        match self.triaged_by.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[triage_commit] requires `triaged_by = \"<role|name>\"`. \
                     Per ADR-026 §Rollback-as-triage clinical-medicine \
                     grounding, informed-consent requires an authoring identity.",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.triaged_by_span.unwrap_or(self.args_span),
                    "#[triage_commit] `triaged_by` cannot be empty or whitespace-only.",
                ));
            }
            Some(_) => {}
        }
        match self.rationale.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[triage_commit] requires `rationale = \"...\"` \
                     (chart-documentation; minimum 20 characters). Per ADR-026 \
                     §Rollback-as-triage: rationale before action, not after.",
                ));
            }
            Some(s) if s.len() < 20 => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    format!(
                        "#[triage_commit] `rationale` must be at least 20 \
                         characters (got {}); per ADR-023 loudness-as-discipline \
                         applied to clinical-medicine chart-documentation.",
                        s.len()
                    ),
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    "#[triage_commit] `rationale` must not be whitespace-only; \
                     a blank rationale bypasses chart-documentation discipline \
                     (ADR-026 §Rollback-as-triage: rationale before action, not after).",
                ));
            }
            Some(_) => {}
        }
        match self.rollback_due_within_minutes {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[triage_commit] requires `rollback_due_within_minutes = N` \
                     (positive integer; e.g., 30 for a Red triage per ADR-026 example).",
                ));
            }
            Some(0) => {
                return Err(syn::Error::new(
                    self.rollback_due_within_minutes_span
                        .unwrap_or(self.args_span),
                    "#[triage_commit] `rollback_due_within_minutes` must be > 0. \
                     A zero deadline degrades to no-deadline; per ADR-026 \
                     §Rollback-as-triage the time-bound carries discipline.",
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

// ============================================================================
// Convergent-Evidence Family argument parsers (ADR-024)
// ============================================================================

/// Arguments to `#[diagnostic(modalities = [...], min_independent = N)]`.
///
/// Per ADR-024 §Decision + adversarial C1:
/// - `modalities` is a list of `WitnessClass::X` paths
/// - `min_independent` is REQUIRED and measured in distinct CLASSES
#[derive(Debug)]
pub struct DiagnosticArgs {
    /// The witness-class paths, captured as their final ident only.
    /// E.g., `WitnessClass::StaticAnalysis` → `"StaticAnalysis"`.
    pub modality_classes: Vec<String>,
    /// The list of modality spans for span-anchored error messages.
    pub modality_span: Option<Span>,
    /// Required minimum distinct classes.
    pub min_independent: Option<u64>,
    /// Span anchor for `min_independent` for span-anchored error messages.
    pub min_independent_span: Option<Span>,
    /// Span of the macro's argument list.
    pub args_span: Span,
}

impl Parse for DiagnosticArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        use syn::LitInt;
        let args_span = input.span();
        let mut modality_classes: Vec<String> = Vec::new();
        let mut modality_span: Option<Span> = None;
        let mut min_independent: Option<u64> = None;
        let mut min_independent_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "modalities" => {
                    let arr: syn::ExprArray = input.parse()?;
                    modality_span = Some(arr.bracket_token.span.join());
                    for elem in &arr.elems {
                        if let Expr::Path(p) = elem {
                            if let Some(seg) = p.path.segments.last() {
                                modality_classes.push(seg.ident.to_string());
                                continue;
                            }
                        }
                        return Err(syn::Error::new_spanned(
                            elem,
                            "expected a `WitnessClass::*` path in `modalities` array",
                        ));
                    }
                }
                "min_independent" => {
                    let lit: LitInt = input.parse()?;
                    min_independent_span = Some(lit.span());
                    min_independent = Some(lit.base10_parse::<u64>()?);
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[diagnostic] field `{other}`; expected: modalities, min_independent"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            modality_classes,
            modality_span,
            min_independent,
            min_independent_span,
            args_span,
        })
    }
}

/// The `WitnessClass` variant names this crate recognizes for `#[diagnostic]`
/// `modalities`. Mirrors `antigen::convergent::WitnessClass` (the sealed enum).
///
/// Held as a LOCAL allowlist because `antigen-macros` cannot depend on
/// `antigen` (circular: `antigen` depends on `antigen-macros`), so the macro
/// crate can't name the real enum at parse time. If `WitnessClass` gains a
/// variant, this list must grow in lockstep — itself a
/// `ParallelStateTrackersDiverge` site (two hand-maintained copies of one
/// variant set); the divergence surfaces the first time a new variant is used
/// in `modalities` and rejected here.
const KNOWN_WITNESS_CLASSES: &[&str] = &[
    "StaticAnalysis",
    "PropertyTest",
    "FormalVerification",
    "ManualReview",
    "RuntimeFuzz",
    "SubstrateWitness",
];

impl DiagnosticArgs {
    /// Per ADR-024 + adversarial C1: `min_independent` is REQUIRED;
    /// `modalities` must be non-empty; `min_independent` must not exceed
    /// the number of distinct modality classes (otherwise the claim is
    /// vacuously unsatisfiable). Each modality must also name a real
    /// `WitnessClass` variant — a sealed enum accepted as an arbitrary ident
    /// is `UnvalidatedSealedEnumAcceptance` (sub-clause F: validate the
    /// trust-boundary input against the closed set it claims to be).
    pub fn validate(&self) -> syn::Result<()> {
        if self.modality_classes.is_empty() {
            return Err(syn::Error::new(
                self.modality_span.unwrap_or(self.args_span),
                "#[diagnostic] requires non-empty `modalities = [WitnessClass::X, ...]` \
                 (ADR-024 §Decision; an empty modality set has no evidence to converge).",
            ));
        }
        // Sub-clause F: reject idents that don't name a real WitnessClass
        // variant. Without this, `modalities = [WitnessClass::Nonsense]` (or
        // any `Foo::Bar`) is silently captured as a bogus class string and the
        // distinct-count math runs on garbage.
        for class in &self.modality_classes {
            if !KNOWN_WITNESS_CLASSES.contains(&class.as_str()) {
                return Err(syn::Error::new(
                    self.modality_span.unwrap_or(self.args_span),
                    format!(
                        "#[diagnostic] `modalities` entry `{class}` is not a known \
                         WitnessClass variant; expected one of: {}. \
                         (A modality that names no real witness class is dead evidence — \
                         it can never converge.)",
                        KNOWN_WITNESS_CLASSES.join(", ")
                    ),
                ));
            }
        }
        let Some(min) = self.min_independent else {
            return Err(syn::Error::new(
                self.args_span,
                "#[diagnostic] requires `min_independent = N` (ADR-024 §Decision; \
                 N counts distinct WitnessClass categories per adversarial C1).",
            ));
        };
        if min == 0 {
            return Err(syn::Error::new(
                self.min_independent_span.unwrap_or(self.args_span),
                "#[diagnostic] `min_independent` must be at least 1 (a 0-floor is \
                 vacuously true and structurally meaningless).",
            ));
        }
        // Count distinct classes (per C1: classes, not raw count)
        let mut distinct: Vec<&String> = Vec::new();
        for c in &self.modality_classes {
            if !distinct.contains(&c) {
                distinct.push(c);
            }
        }
        if u64::try_from(distinct.len()).unwrap_or(u64::MAX) < min {
            return Err(syn::Error::new(
                self.min_independent_span.unwrap_or(self.args_span),
                format!(
                    "#[diagnostic] `min_independent = {min}` exceeds the number of \
                     distinct WitnessClass categories supplied ({}). Per ADR-024 \
                     adversarial C1, min_independent counts CLASSES not witnesses — \
                     duplicate classes don't add independence. Increase distinct \
                     modalities or lower the floor.",
                    distinct.len()
                ),
            ));
        }
        Ok(())
    }
}

/// Arguments to `#[clonal(witness = ..., iterations = N, seed = SeedKind::...)]`.
///
/// Per ADR-024 §Decision + adversarial C2:
/// - `witness` is REQUIRED — references the per-iteration function/test
/// - `iterations` is REQUIRED — explicit non-zero count
/// - `seed = SeedKind::Fixed(_)` is REJECTED at parse time
#[derive(Debug)]
pub struct ClonalArgs {
    #[allow(dead_code)]
    pub witness: Option<Expr>,
    pub witness_span: Option<Span>,
    pub iterations: Option<u64>,
    pub iterations_span: Option<Span>,
    /// The final ident of the `seed = SeedKind::X(...)` path. `None` if
    /// no seed argument supplied (defaults to `Random`). Captured for
    /// scan-side introspection / future audit-hint refinement.
    #[allow(dead_code)]
    pub seed_kind: Option<String>,
    pub seed_span: Option<Span>,
    /// True if the seed expression was `SeedKind::Fixed(...)`.
    pub seed_is_fixed: bool,
    pub args_span: Span,
}

impl Parse for ClonalArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        use syn::LitInt;
        let args_span = input.span();
        let mut witness: Option<Expr> = None;
        let mut witness_span: Option<Span> = None;
        let mut iterations: Option<u64> = None;
        let mut iterations_span: Option<Span> = None;
        let mut seed_kind: Option<String> = None;
        let mut seed_span: Option<Span> = None;
        let mut seed_is_fixed = false;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "witness" => {
                    let e: Expr = input.parse()?;
                    witness_span = Some(syn::spanned::Spanned::span(&e));
                    witness = Some(e);
                }
                "iterations" => {
                    let lit: LitInt = input.parse()?;
                    iterations_span = Some(lit.span());
                    iterations = Some(lit.base10_parse::<u64>()?);
                }
                "seed" => {
                    let e: Expr = input.parse()?;
                    seed_span = Some(syn::spanned::Spanned::span(&e));
                    // Extract the final ident: SeedKind::Random / SeedKind::Fixed(...).
                    if let Expr::Path(p) = &e {
                        if let Some(seg) = p.path.segments.last() {
                            let name = seg.ident.to_string();
                            seed_kind = Some(name);
                        }
                    } else if let Expr::Call(c) = &e {
                        if let Expr::Path(p) = &*c.func {
                            if let Some(seg) = p.path.segments.last() {
                                let name = seg.ident.to_string();
                                if name == "Fixed" {
                                    seed_is_fixed = true;
                                }
                                seed_kind = Some(name);
                            }
                        }
                    }
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[clonal] field `{other}`; expected: witness, iterations, seed"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            witness,
            witness_span,
            iterations,
            iterations_span,
            seed_kind,
            seed_span,
            seed_is_fixed,
            args_span,
        })
    }
}

impl ClonalArgs {
    /// Trust-boundary checks per ADR-024:
    /// - `witness` REQUIRED
    /// - `iterations` REQUIRED and > 0
    /// - `seed = SeedKind::Fixed(_)` REJECTED with COMPILE ERROR (C2)
    pub fn validate(&self) -> syn::Result<()> {
        if self.witness.is_none() {
            return Err(syn::Error::new(
                self.witness_span.unwrap_or(self.args_span),
                "#[clonal] requires `witness = <identifier>` referencing the \
                 per-iteration function/test (ADR-024 §Decision).",
            ));
        }
        let Some(iters) = self.iterations else {
            return Err(syn::Error::new(
                self.args_span,
                "#[clonal] requires `iterations = N` (ADR-024 §Decision; \
                 explicit iteration count is the structural memory of how \
                 much independence the witness is claiming).",
            ));
        };
        if iters == 0 {
            return Err(syn::Error::new(
                self.iterations_span.unwrap_or(self.args_span),
                "#[clonal] `iterations` must be > 0 (zero iterations means \
                 no evidence).",
            ));
        }
        if self.seed_is_fixed {
            return Err(syn::Error::new(
                self.seed_span.unwrap_or(self.args_span),
                "#[clonal] rejects `seed = SeedKind::Fixed(_)` — a fixed seed \
                 makes 'iterations' a misnomer (every iteration replays the same \
                 RNG state). Use SeedKind::Random, SeedKind::EntropyFromCi, or \
                 SeedKind::TimestampSeeded. \
                 Per ADR-024 adversarial C2: COMPILE-TIME enforcement.",
            ));
        }
        Ok(())
    }
}

/// Arguments to `#[igg(witnesses = [...], historical_span = N, min_reattestations = N)]`.
///
/// Per ADR-024 §Decision + adversarial C3:
/// - `witnesses` REQUIRED non-empty
/// - `historical_span` REQUIRED (days)
/// - `min_reattestations` REQUIRED
/// - Source-independence is NOMINAL — different signer-identity strings
///   don't structurally prove independent sources (named limitation)
#[derive(Debug)]
pub struct IggArgs {
    #[allow(dead_code)]
    pub witnesses: Vec<Expr>,
    pub witnesses_span: Option<Span>,
    pub historical_span: Option<u64>,
    pub historical_span_span: Option<Span>,
    pub min_reattestations: Option<u64>,
    pub min_reattestations_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for IggArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        use syn::LitInt;
        let args_span = input.span();
        let mut witnesses: Vec<Expr> = Vec::new();
        let mut witnesses_span: Option<Span> = None;
        let mut historical_span: Option<u64> = None;
        let mut historical_span_span: Option<Span> = None;
        let mut min_reattestations: Option<u64> = None;
        let mut min_reattestations_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "witnesses" => {
                    let arr: syn::ExprArray = input.parse()?;
                    witnesses_span = Some(arr.bracket_token.span.join());
                    for elem in &arr.elems {
                        witnesses.push(elem.clone());
                    }
                }
                "historical_span" => {
                    let lit: LitInt = input.parse()?;
                    historical_span_span = Some(lit.span());
                    historical_span = Some(lit.base10_parse::<u64>()?);
                }
                "min_reattestations" => {
                    let lit: LitInt = input.parse()?;
                    min_reattestations_span = Some(lit.span());
                    min_reattestations = Some(lit.base10_parse::<u64>()?);
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[igg] field `{other}`; expected: \
                             witnesses, historical_span, min_reattestations"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            witnesses,
            witnesses_span,
            historical_span,
            historical_span_span,
            min_reattestations,
            min_reattestations_span,
            args_span,
        })
    }
}

impl IggArgs {
    pub fn validate(&self) -> syn::Result<()> {
        if self.witnesses.is_empty() {
            return Err(syn::Error::new(
                self.witnesses_span.unwrap_or(self.args_span),
                "#[igg] requires non-empty `witnesses = [...]` (ADR-024 §Decision).",
            ));
        }
        let Some(span) = self.historical_span else {
            return Err(syn::Error::new(
                self.args_span,
                "#[igg] requires `historical_span = N` (days; ADR-024 §Decision).",
            ));
        };
        if span == 0 {
            return Err(syn::Error::new(
                self.historical_span_span.unwrap_or(self.args_span),
                "#[igg] `historical_span` must be > 0 days.",
            ));
        }
        let Some(min) = self.min_reattestations else {
            return Err(syn::Error::new(
                self.args_span,
                "#[igg] requires `min_reattestations = N` (ADR-024 §Decision).",
            ));
        };
        if min == 0 {
            return Err(syn::Error::new(
                self.min_reattestations_span.unwrap_or(self.args_span),
                "#[igg] `min_reattestations` must be > 0.",
            ));
        }
        Ok(())
    }
}

/// Arguments to `#[crossreactive(fingerprints = [...])]`.
///
/// Declares one defense addresses multiple related antigens (cross-
/// reactive immune response).
#[derive(Debug)]
pub struct CrossreactiveArgs {
    #[allow(dead_code)]
    pub fingerprints: Vec<String>,
    pub fingerprints_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for CrossreactiveArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut fingerprints: Vec<String> = Vec::new();
        let mut fingerprints_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "fingerprints" => {
                    let arr: syn::ExprArray = input.parse()?;
                    fingerprints_span = Some(arr.bracket_token.span.join());
                    for elem in &arr.elems {
                        if let Expr::Lit(syn::ExprLit {
                            lit: Lit::Str(s), ..
                        }) = elem
                        {
                            fingerprints.push(s.value());
                        } else {
                            return Err(syn::Error::new_spanned(
                                elem,
                                "expected a string literal fingerprint in `fingerprints` array",
                            ));
                        }
                    }
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!("unknown #[crossreactive] field `{other}`; expected: fingerprints"),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            fingerprints,
            fingerprints_span,
            args_span,
        })
    }
}

impl CrossreactiveArgs {
    pub fn validate(&self) -> syn::Result<()> {
        if self.fingerprints.is_empty() {
            return Err(syn::Error::new(
                self.fingerprints_span.unwrap_or(self.args_span),
                "#[crossreactive] requires non-empty `fingerprints = [...]` \
                 (a defense that covers no related antigens isn't crossreactive).",
            ));
        }
        for f in &self.fingerprints {
            if f.is_empty() {
                return Err(syn::Error::new(
                    self.fingerprints_span.unwrap_or(self.args_span),
                    "#[crossreactive] `fingerprints` entries must be non-empty strings.",
                ));
            }
        }
        Ok(())
    }
}

/// Arguments to `#[polyclonal]` — many independent lineages.
/// No required fields per ADR-024 §Decision.
#[derive(Debug)]
pub struct PolyclonalArgs {
    #[allow(dead_code)]
    pub args_span: Span,
}

impl Parse for PolyclonalArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        // Accept arbitrary trailing args for forward compat — discard them.
        while !input.is_empty() {
            let _: proc_macro2::TokenTree = input.parse()?;
        }
        Ok(Self { args_span })
    }
}

impl PolyclonalArgs {
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    pub const fn validate(&self) -> syn::Result<()> {
        Ok(())
    }
}

/// Arguments to `#[monoclonal]` — single independent lineage. No required
/// fields per ADR-024 §Decision.
#[derive(Debug)]
pub struct MonoclonalArgs {
    #[allow(dead_code)]
    pub args_span: Span,
}

impl Parse for MonoclonalArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        while !input.is_empty() {
            let _: proc_macro2::TokenTree = input.parse()?;
        }
        Ok(Self { args_span })
    }
}

impl MonoclonalArgs {
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    pub const fn validate(&self) -> syn::Result<()> {
        Ok(())
    }
}

/// Arguments to `#[adcc]` — antibody + cellular effector (multi-mechanism).
/// No required fields per ADR-024 §Decision.
#[derive(Debug)]
pub struct AdccArgs {
    #[allow(dead_code)]
    pub args_span: Span,
}

impl Parse for AdccArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        while !input.is_empty() {
            let _: proc_macro2::TokenTree = input.parse()?;
        }
        Ok(Self { args_span })
    }
}

impl AdccArgs {
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    pub const fn validate(&self) -> syn::Result<()> {
        Ok(())
    }
}

// ============================================================================
// Recurrent-Emergence Family argument parsers (ADR-024 + scientist HOW-spec
// cf2a2317 + aristotle Reading-A pre-authorization 744471a3)
//
// Six present-looking primitives per ADR-024 §Family 2: #[itch],
// #[recurrence_anchor], #[crystallize], #[chronic], #[saturate], #[strand].
// Cognitive-organizational grounding for itch/saturate/crystallize/strand;
// immunology-proper for chronic; clinical-medicine for recurrence_anchor.
// All members declare antigen-category = SubstrateAlignment per ADR-028
// (representation of recurring pattern diverges from actual state).
// ============================================================================

/// Arguments to `#[itch(name, antigen?, description, threshold?)]`.
///
/// Cognitive-organizational primitive: "pattern noticed below threshold;
/// no commitment yet" per ADR-024 §Disambiguation table. Distinct from
/// `#[anergy]` (ADR-023, intentional non-defense while waiting): itch is
/// a pre-commitment NOTICING, anergy is a deliberate DEFER.
#[derive(Debug)]
pub struct ItchArgs {
    pub name: Option<String>,
    pub name_span: Option<Span>,
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub description: Option<String>,
    pub description_span: Option<Span>,
    #[allow(dead_code)]
    pub threshold: Option<String>,
    pub args_span: Span,
}

impl Parse for ItchArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut name: Option<String> = None;
        let mut name_span: Option<Span> = None;
        let mut antigen: Option<syn::Path> = None;
        let mut description: Option<String> = None;
        let mut description_span: Option<Span> = None;
        let mut threshold: Option<String> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "name" => {
                    let lit: LitStr = input.parse()?;
                    name_span = Some(lit.span());
                    name = Some(lit.value());
                }
                "antigen" => {
                    antigen = Some(input.parse()?);
                }
                "description" => {
                    let lit: LitStr = input.parse()?;
                    description_span = Some(lit.span());
                    description = Some(lit.value());
                }
                "threshold" => {
                    let lit: LitStr = input.parse()?;
                    threshold = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[itch] field `{other}`; expected one of: \
                             name, antigen, description, threshold"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            name,
            name_span,
            antigen,
            description,
            description_span,
            threshold,
            args_span,
        })
    }
}

impl ItchArgs {
    /// Per scientist HOW-spec: name + description required; description ≥10 chars.
    pub fn validate(&self) -> syn::Result<()> {
        match self.name.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[itch] requires `name = \"<slug>\"` (kebab-case identifier).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.name_span.unwrap_or(self.args_span),
                    "#[itch] `name` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        match self.description.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[itch] requires `description = \"...\"` (what is being noticed; \
                     minimum 10 characters).",
                ));
            }
            Some(s) if s.len() < 10 => {
                return Err(syn::Error::new(
                    self.description_span.unwrap_or(self.args_span),
                    format!(
                        "#[itch] `description` must be at least 10 characters \
                         (got {}); per cognitive-organizational discipline a noticing \
                         needs enough text to be useful next-time.",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[recurrence_anchor(antigen, instances, since, rationale)]`.
///
/// Clinical-medicine primitive: "cross-substrate recurrence; threshold
/// reached; want to surface for action" per ADR-024 §Disambiguation. The
/// recurrence-anchor commits to FORMAL recognition of a pattern that has
/// crossed the substrate-evidence threshold — analogous to a clinical
/// diagnosis after recurrent symptoms.
#[derive(Debug)]
pub struct RecurrenceAnchorArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub instances: Option<u32>,
    pub instances_span: Option<Span>,
    pub since: Option<String>,
    pub since_span: Option<Span>,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for RecurrenceAnchorArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut instances: Option<u32> = None;
        let mut instances_span: Option<Span> = None;
        let mut since: Option<String> = None;
        let mut since_span: Option<Span> = None;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;

        // Optional leading positional antigen path
        if !input.is_empty() && input.peek(Ident) && !input.peek2(Token![=]) {
            antigen = Some(input.parse()?);
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "antigen" => {
                    antigen = Some(input.parse()?);
                }
                "instances" => {
                    let lit: syn::LitInt = input.parse()?;
                    instances_span = Some(lit.span());
                    instances = Some(lit.base10_parse::<u32>()?);
                }
                "since" => {
                    let lit: LitStr = input.parse()?;
                    since_span = Some(lit.span());
                    since = Some(lit.value());
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[recurrence_anchor] field `{other}`; expected \
                             one of: antigen, instances, since, rationale"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            instances,
            instances_span,
            since,
            since_span,
            rationale,
            rationale_span,
            args_span,
        })
    }
}

impl RecurrenceAnchorArgs {
    /// Per scientist HOW-spec: antigen + instances (> 0) + since + rationale
    /// (≥20 chars) all REQUIRED.
    pub fn validate(&self) -> syn::Result<()> {
        if self.antigen.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[recurrence_anchor] requires an `antigen` path (the failure-class \
                 being formally anchored as a cross-substrate recurrence).",
            ));
        }
        match self.instances {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[recurrence_anchor] requires `instances = N` (positive \
                     integer; how many recurrences have been observed).",
                ));
            }
            Some(0) => {
                return Err(syn::Error::new(
                    self.instances_span.unwrap_or(self.args_span),
                    "#[recurrence_anchor] `instances` must be > 0; an anchor at \
                     zero observed instances is structurally premature.",
                ));
            }
            Some(_) => {}
        }
        match self.since.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[recurrence_anchor] requires `since = \"<date-or-version>\"` \
                     (first detected instance anchor).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.since_span.unwrap_or(self.args_span),
                    "#[recurrence_anchor] `since` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        match self.rationale.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[recurrence_anchor] requires `rationale = \"...\"` \
                     (≥20 characters; why this recurrence warrants action).",
                ));
            }
            Some(s) if s.len() < 20 => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    format!(
                        "#[recurrence_anchor] `rationale` must be at least 20 \
                         characters (got {}); clinical-diagnosis-grade rationale \
                         per ADR-024 clinical-medicine grounding.",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[crystallize(name, from_itches?, antigen?, summary)]`.
///
/// Cognitive-organizational primitive: "itch cluster crosses threshold
/// into named failure-class." The promotion event from below-threshold
/// noticing to formal recognition; parallel to `crystallize` in the camp
/// field-track substrate.
#[derive(Debug)]
pub struct CrystallizeArgs {
    pub name: Option<String>,
    pub name_span: Option<Span>,
    #[allow(dead_code)]
    pub from_itches: Vec<syn::Path>,
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub summary: Option<String>,
    pub summary_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for CrystallizeArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut name: Option<String> = None;
        let mut name_span: Option<Span> = None;
        let mut from_itches: Vec<syn::Path> = Vec::new();
        let mut antigen: Option<syn::Path> = None;
        let mut summary: Option<String> = None;
        let mut summary_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "name" => {
                    let lit: LitStr = input.parse()?;
                    name_span = Some(lit.span());
                    name = Some(lit.value());
                }
                "from_itches" => {
                    let arr: syn::ExprArray = input.parse()?;
                    for elem in &arr.elems {
                        if let Expr::Path(p) = elem {
                            from_itches.push(p.path.clone());
                        } else {
                            return Err(syn::Error::new_spanned(
                                elem,
                                "expected a path expression in `from_itches` array",
                            ));
                        }
                    }
                }
                "antigen" => {
                    antigen = Some(input.parse()?);
                }
                "summary" => {
                    let lit: LitStr = input.parse()?;
                    summary_span = Some(lit.span());
                    summary = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[crystallize] field `{other}`; expected \
                             one of: name, from_itches, antigen, summary"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            name,
            name_span,
            from_itches,
            antigen,
            summary,
            summary_span,
            args_span,
        })
    }
}

impl CrystallizeArgs {
    /// Per scientist HOW-spec: name + summary required; summary ≥10 chars.
    pub fn validate(&self) -> syn::Result<()> {
        match self.name.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[crystallize] requires `name = \"<slug>\"`.",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.name_span.unwrap_or(self.args_span),
                    "#[crystallize] `name` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        match self.summary.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[crystallize] requires `summary = \"...\"` (≥10 characters).",
                ));
            }
            Some(s) if s.len() < 10 => {
                return Err(syn::Error::new(
                    self.summary_span.unwrap_or(self.args_span),
                    format!(
                        "#[crystallize] `summary` must be at least 10 characters \
                         (got {}); per cognitive-organizational discipline a \
                         crystallization event needs enough text to be useful.",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[chronic(antigen, since, status?, managed_by?)]`.
///
/// Immunology-proper primitive: "low-level persistent signal NOT
/// cross-substrate" per ADR-024 §Disambiguation. Distinct from
/// `#[recurrence_anchor]` (cross-substrate, threshold reached): chronic
/// is a SUSTAINED single-substrate signal — analogous to a chronic
/// inflammatory state without acute recurrence.
#[derive(Debug)]
pub struct ChronicArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    pub since: Option<String>,
    pub since_span: Option<Span>,
    #[allow(dead_code)]
    pub status: Option<String>,
    #[allow(dead_code)]
    pub managed_by: Option<String>,
    pub args_span: Span,
}

impl Parse for ChronicArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut since: Option<String> = None;
        let mut since_span: Option<Span> = None;
        let mut status: Option<String> = None;
        let mut managed_by: Option<String> = None;

        // Optional leading positional antigen path
        if !input.is_empty() && input.peek(Ident) && !input.peek2(Token![=]) {
            antigen = Some(input.parse()?);
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "antigen" => {
                    antigen = Some(input.parse()?);
                }
                "since" => {
                    let lit: LitStr = input.parse()?;
                    since_span = Some(lit.span());
                    since = Some(lit.value());
                }
                "status" => {
                    let lit: LitStr = input.parse()?;
                    status = Some(lit.value());
                }
                "managed_by" => {
                    let lit: LitStr = input.parse()?;
                    managed_by = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[chronic] field `{other}`; expected one of: \
                             antigen, since, status, managed_by"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            since,
            since_span,
            status,
            managed_by,
            args_span,
        })
    }
}

impl ChronicArgs {
    /// Per scientist HOW-spec: antigen + since both REQUIRED.
    pub fn validate(&self) -> syn::Result<()> {
        if self.antigen.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[chronic] requires an `antigen` path (the failure-class \
                 being marked chronic).",
            ));
        }
        match self.since.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[chronic] requires `since = \"<date-or-version>\"` (when \
                     the chronic signal was first observed).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.since_span.unwrap_or(self.args_span),
                    "#[chronic] `since` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[saturate(antigen?, contributing_to?, description)]`.
///
/// Cognitive-organizational primitive: "accumulating saturation evidence
/// toward a recurrence threshold." A saturation event names a contribution
/// to a recognized recurrence pattern; without a `contributing_to` target
/// the audit emits `saturate-no-anchor`.
#[derive(Debug)]
pub struct SaturateArgs {
    #[allow(dead_code)]
    pub antigen: Option<syn::Path>,
    #[allow(dead_code)]
    pub contributing_to: Option<String>,
    pub description: Option<String>,
    pub description_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for SaturateArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut antigen: Option<syn::Path> = None;
        let mut contributing_to: Option<String> = None;
        let mut description: Option<String> = None;
        let mut description_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "antigen" => {
                    antigen = Some(input.parse()?);
                }
                "contributing_to" => {
                    let lit: LitStr = input.parse()?;
                    contributing_to = Some(lit.value());
                }
                "description" => {
                    let lit: LitStr = input.parse()?;
                    description_span = Some(lit.span());
                    description = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[saturate] field `{other}`; expected one of: \
                             antigen, contributing_to, description"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            antigen,
            contributing_to,
            description,
            description_span,
            args_span,
        })
    }
}

impl SaturateArgs {
    /// Per scientist HOW-spec: description required (≥10 chars).
    pub fn validate(&self) -> syn::Result<()> {
        match self.description.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[saturate] requires `description = \"...\"` (≥10 characters; \
                     what evidence is saturating).",
                ));
            }
            Some(s) if s.len() < 10 => {
                return Err(syn::Error::new(
                    self.description_span.unwrap_or(self.args_span),
                    format!(
                        "#[saturate] `description` must be at least 10 characters \
                         (got {}).",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[strand(name, anchored_by?, description)]`.
///
/// Cognitive-organizational primitive: "thread of related noticing; may
/// spawn `#[itch]` or `#[recurrence_anchor]`." A strand groups noticings
/// across multiple substrates that share a structural rhyme but haven't
/// yet crystallized.
#[derive(Debug)]
pub struct StrandArgs {
    pub name: Option<String>,
    pub name_span: Option<Span>,
    #[allow(dead_code)]
    pub anchored_by: Vec<syn::Path>,
    pub description: Option<String>,
    pub description_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for StrandArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut name: Option<String> = None;
        let mut name_span: Option<Span> = None;
        let mut anchored_by: Vec<syn::Path> = Vec::new();
        let mut description: Option<String> = None;
        let mut description_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "name" => {
                    let lit: LitStr = input.parse()?;
                    name_span = Some(lit.span());
                    name = Some(lit.value());
                }
                "anchored_by" => {
                    let arr: syn::ExprArray = input.parse()?;
                    for elem in &arr.elems {
                        if let Expr::Path(p) = elem {
                            anchored_by.push(p.path.clone());
                        } else {
                            return Err(syn::Error::new_spanned(
                                elem,
                                "expected a path expression in `anchored_by` array",
                            ));
                        }
                    }
                }
                "description" => {
                    let lit: LitStr = input.parse()?;
                    description_span = Some(lit.span());
                    description = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[strand] field `{other}`; expected one of: \
                             name, anchored_by, description"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            name,
            name_span,
            anchored_by,
            description,
            description_span,
            args_span,
        })
    }
}

impl StrandArgs {
    /// Per scientist HOW-spec: name + description both REQUIRED (≥10 chars).
    pub fn validate(&self) -> syn::Result<()> {
        match self.name.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[strand] requires `name = \"<slug>\"`.",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.name_span.unwrap_or(self.args_span),
                    "#[strand] `name` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        match self.description.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[strand] requires `description = \"...\"` (≥10 characters; \
                     what threads of noticing this strand groups).",
                ));
            }
            Some(s) if s.len() < 10 => {
                return Err(syn::Error::new(
                    self.description_span.unwrap_or(self.args_span),
                    format!(
                        "#[strand] `description` must be at least 10 characters \
                         (got {}).",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

// ============================================================================
// MacroMucosalKind — local mirror of antigen::MucosalKind (ADR-027 + Amd 1)
//
// proc-macro crates cannot depend on the `antigen` library crate (circular
// dependency); local parse-time mirror — same pattern as MacroAntigenCategory
// (ADR-028) and MacroTriageDecision (ADR-026). Sealed 13-variant set; extending
// requires an ADR amendment per ADR-001 Amendment 1 C6.
// ============================================================================

/// Parse-time mucosal-kind variant (mirrors `antigen::mucosal::MucosalKind`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroMucosalKind {
    ApiRequest,
    ApiResponse,
    McpInvocation,
    ExternalLink,
    Iframe,
    DatabaseQuery,
    CrossService,
    SubprocessLaunch,
    DependencyImport,
    UserInput,
    FilesystemPath,
    EnvironmentVariable,
    ShellArgument,
}

impl MacroMucosalKind {
    /// Parse from path-style expression strings and common aliases. Strips
    /// an optional `MucosalKind::` prefix.
    fn from_path_str(s: &str) -> Option<Self> {
        let bare = s.strip_prefix("MucosalKind::").unwrap_or(s);
        match bare {
            "ApiRequest" | "api-request" | "api_request" => Some(Self::ApiRequest),
            "ApiResponse" | "api-response" | "api_response" => Some(Self::ApiResponse),
            "McpInvocation" | "mcp-invocation" | "mcp_invocation" => Some(Self::McpInvocation),
            "ExternalLink" | "external-link" | "external_link" => Some(Self::ExternalLink),
            "Iframe" | "iframe" => Some(Self::Iframe),
            "DatabaseQuery" | "database-query" | "database_query" => Some(Self::DatabaseQuery),
            "CrossService" | "cross-service" | "cross_service" => Some(Self::CrossService),
            "SubprocessLaunch" | "subprocess-launch" | "subprocess_launch" => {
                Some(Self::SubprocessLaunch)
            }
            "DependencyImport" | "dependency-import" | "dependency_import" => {
                Some(Self::DependencyImport)
            }
            "UserInput" | "user-input" | "user_input" => Some(Self::UserInput),
            "FilesystemPath" | "filesystem-path" | "filesystem_path" => Some(Self::FilesystemPath),
            "EnvironmentVariable" | "environment-variable" | "environment_variable" => {
                Some(Self::EnvironmentVariable)
            }
            "ShellArgument" | "shell-argument" | "shell_argument" => Some(Self::ShellArgument),
            _ => None,
        }
    }
}

/// Shared helper: parse a `kind = MucosalKind::X` value (path expr, not
/// string literal) into a `MacroMucosalKind`. Used by all three mucosal
/// parsers per ADR-027 Amendment 1 path-expression discipline.
fn parse_mucosal_kind_expr(expr: &Expr) -> syn::Result<MacroMucosalKind> {
    let s = match expr {
        Expr::Path(p) => p
            .path
            .segments
            .iter()
            .map(|seg| seg.ident.to_string())
            .collect::<Vec<_>>()
            .join("::"),
        _ => {
            return Err(syn::Error::new_spanned(
                expr,
                "expected a `MucosalKind::X` path expression (e.g., \
                 `MucosalKind::UserInput`), not a string literal",
            ));
        }
    };
    MacroMucosalKind::from_path_str(&s).ok_or_else(|| {
        syn::Error::new_spanned(
            expr,
            format!(
                "unknown MucosalKind `{s}`; expected one of the 13 sealed-set \
                 variants (ApiRequest, ApiResponse, McpInvocation, ExternalLink, \
                 Iframe, DatabaseQuery, CrossService, SubprocessLaunch, \
                 DependencyImport, UserInput, FilesystemPath, EnvironmentVariable, \
                 ShellArgument). Note: PrBoundary + Import were removed in ADR-027 \
                 Amendment 1."
            ),
        )
    })
}

// ============================================================================
// Mucosal Boundary Family argument parsers (ADR-027 + Amendment 1)
//
// Three primitives: #[mucosal], #[mucosal_delegate], #[mucosal_tolerant].
// All declare antigen-category = SubstrateAlignment per ADR-028.
// ============================================================================

/// Arguments to `#[mucosal(kind, rationale)]`.
///
/// Declares a trust boundary is actively defended at this site. Per ADR-027
/// the biology grounds the tier-claim (mucosal surfaces are a distinct
/// immune tier) + the prevention-at-boundary discipline (secretory-IgA-style
/// exclusion).
#[derive(Debug)]
pub struct MucosalArgs {
    pub kind: Option<MacroMucosalKind>,
    #[allow(dead_code)]
    pub kind_span: Option<Span>,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for MucosalArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut kind: Option<MacroMucosalKind> = None;
        let mut kind_span: Option<Span> = None;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "kind" => {
                    let expr: Expr = input.parse()?;
                    kind_span = Some(input.span());
                    kind = Some(parse_mucosal_kind_expr(&expr)?);
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[mucosal] field `{other}`; expected one of: \
                             kind, rationale"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            kind,
            kind_span,
            rationale,
            rationale_span,
            args_span,
        })
    }
}

impl MucosalArgs {
    /// Per ADR-027: kind + rationale REQUIRED; rationale ≥20 chars.
    pub fn validate(&self) -> syn::Result<()> {
        if self.kind.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[mucosal] requires `kind = MucosalKind::X` (the boundary type \
                 being defended).",
            ));
        }
        match self.rationale.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[mucosal] requires `rationale = \"...\"` (≥20 characters; \
                     why this boundary is defended).",
                ));
            }
            Some(s) if s.len() < 20 => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    format!(
                        "#[mucosal] `rationale` must be at least 20 characters \
                         (got {}); per ADR-027 boundary-defense discipline.",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[mucosal_delegate(boundary, handled_by, rationale)]`.
///
/// Declares the boundary discipline is delegated to a named handler. Per
/// ADR-027 Amendment 1 Change 4, `handled_by` is a `syn::Path` (not a
/// string), so typos are caught at parse-time and resolution follows
/// standard Rust visibility rules at audit-time. Per Change 5, the handler
/// must carry a `#[mucosal(kind = X)]` where X matches `boundary`.
#[derive(Debug)]
pub struct MucosalDelegateArgs {
    pub boundary: Option<MacroMucosalKind>,
    #[allow(dead_code)]
    pub boundary_span: Option<Span>,
    #[allow(dead_code)]
    pub handled_by: Option<syn::Path>,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for MucosalDelegateArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut boundary: Option<MacroMucosalKind> = None;
        let mut boundary_span: Option<Span> = None;
        let mut handled_by: Option<syn::Path> = None;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "boundary" => {
                    let expr: Expr = input.parse()?;
                    boundary_span = Some(input.span());
                    boundary = Some(parse_mucosal_kind_expr(&expr)?);
                }
                "handled_by" => {
                    // ADR-027 Amendment 1 Change 4: handled_by is a path
                    // expression, not a string literal.
                    handled_by = Some(input.parse()?);
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[mucosal_delegate] field `{other}`; expected \
                             one of: boundary, handled_by, rationale"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            boundary,
            boundary_span,
            handled_by,
            rationale,
            rationale_span,
            args_span,
        })
    }
}

impl MucosalDelegateArgs {
    /// Per ADR-027 Amendment 1: boundary + `handled_by` + rationale REQUIRED;
    /// rationale ≥20 chars. Kind-matching against the handler's `#[mucosal]`
    /// is an audit-time check (Change 5), not parse-time.
    pub fn validate(&self) -> syn::Result<()> {
        if self.boundary.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[mucosal_delegate] requires `boundary = MucosalKind::X` (the \
                 boundary kind being delegated).",
            ));
        }
        if self.handled_by.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[mucosal_delegate] requires `handled_by = <path>` (the handler \
                 function that carries the matching `#[mucosal(kind = X)]`). Per \
                 ADR-027 Amendment 1 this is a path expression, not a string.",
            ));
        }
        match self.rationale.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[mucosal_delegate] requires `rationale = \"...\"` (≥20 chars).",
                ));
            }
            Some(s) if s.len() < 20 => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    format!(
                        "#[mucosal_delegate] `rationale` must be at least 20 \
                         characters (got {}).",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

/// Arguments to `#[mucosal_tolerant(kind, rationale, accepts, reviewed_by?,
/// until?)]`.
///
/// Declares a boundary is INTENTIONALLY permitted — active tolerance, not
/// absence of defense (ADR-027 Amendment 1 Change 6). The biology cognate is
/// Treg-mediated active tolerance (oral tolerance, fetal-maternal interface).
/// Parallel to ADR-016 `#[antigen_tolerance]` but at the boundary tier. The
/// rationale floor is ≥40 chars (higher than `#[mucosal]`'s ≥20) — tolerance
/// errors are silent/latent (no acute signal catches a bad tolerance decision),
/// so the up-front declaration carries a higher loudness floor to compensate
/// for the detection asymmetry.
#[derive(Debug)]
pub struct MucosalTolerantArgs {
    pub kind: Option<MacroMucosalKind>,
    #[allow(dead_code)]
    pub kind_span: Option<Span>,
    pub rationale: Option<String>,
    pub rationale_span: Option<Span>,
    pub accepts: Option<String>,
    pub accepts_span: Option<Span>,
    #[allow(dead_code)]
    pub reviewed_by: Option<String>,
    #[allow(dead_code)]
    pub until: Option<String>,
    pub args_span: Span,
}

impl Parse for MucosalTolerantArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut kind: Option<MacroMucosalKind> = None;
        let mut kind_span: Option<Span> = None;
        let mut rationale: Option<String> = None;
        let mut rationale_span: Option<Span> = None;
        let mut accepts: Option<String> = None;
        let mut accepts_span: Option<Span> = None;
        let mut reviewed_by: Option<String> = None;
        let mut until: Option<String> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            input.parse::<Token![=]>()?;
            match key.to_string().as_str() {
                "kind" => {
                    let expr: Expr = input.parse()?;
                    kind_span = Some(input.span());
                    kind = Some(parse_mucosal_kind_expr(&expr)?);
                }
                "rationale" => {
                    let lit: LitStr = input.parse()?;
                    rationale_span = Some(lit.span());
                    rationale = Some(lit.value());
                }
                "accepts" => {
                    let lit: LitStr = input.parse()?;
                    accepts_span = Some(lit.span());
                    accepts = Some(lit.value());
                }
                "reviewed_by" => {
                    let lit: LitStr = input.parse()?;
                    reviewed_by = Some(lit.value());
                }
                "until" => {
                    let lit: LitStr = input.parse()?;
                    until = Some(lit.value());
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!(
                            "unknown #[mucosal_tolerant] field `{other}`; expected \
                             one of: kind, rationale, accepts, reviewed_by, until. \
                             (For failure-class-tier tolerance see \
                             `#[antigen_tolerance]`; this is the BOUNDARY-tier \
                             tolerance primitive.)"
                        ),
                    ));
                }
            }
            if !input.is_empty() {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            kind,
            kind_span,
            rationale,
            rationale_span,
            accepts,
            accepts_span,
            reviewed_by,
            until,
            args_span,
        })
    }
}

impl MucosalTolerantArgs {
    /// Per ADR-027 Amendment 1 Change 6: kind + rationale (≥40) + accepts
    /// (non-empty) REQUIRED; `reviewed_by` + until optional v0.2.
    pub fn validate(&self) -> syn::Result<()> {
        if self.kind.is_none() {
            return Err(syn::Error::new(
                self.args_span,
                "#[mucosal_tolerant] requires `kind = MucosalKind::X`. (For \
                 failure-class-tier tolerance see `#[antigen_tolerance]`; this \
                 is the BOUNDARY-tier tolerance primitive.)",
            ));
        }
        match self.rationale.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[mucosal_tolerant] requires `rationale = \"...\"` (≥40 \
                     characters — tolerance errors are silent/latent, so the \
                     up-front declaration carries a higher loudness floor than \
                     #[mucosal]'s ≥20 to compensate for the detection asymmetry).",
                ));
            }
            Some(s) if s.len() < 40 => {
                return Err(syn::Error::new(
                    self.rationale_span.unwrap_or(self.args_span),
                    format!(
                        "#[mucosal_tolerant] `rationale` must be at least 40 \
                         characters (got {}); per ADR-027 Amendment 1 the floor \
                         is higher than #[mucosal]'s ≥20 because tolerance errors \
                         are silent/latent — no acute signal catches a bad \
                         tolerance decision.",
                        s.len()
                    ),
                ));
            }
            Some(_) => {}
        }
        match self.accepts.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[mucosal_tolerant] requires `accepts = \"...\"` (non-empty; \
                     description of what the boundary accepts as legitimate input).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.accepts_span.unwrap_or(self.args_span),
                    "#[mucosal_tolerant] `accepts` cannot be empty. Audit emits \
                     mucosal-tolerant-accepts-empty.",
                ));
            }
            Some(_) => {}
        }
        Ok(())
    }
}

// ============================================================================
// Date helpers for ADR-023 parse-time enforcement
// ============================================================================

/// Parse an ISO-8601 date string (`YYYY-MM-DD`) into a `chrono::NaiveDate`.
/// Returns `Err` if the string is not a valid date — callers treat parse
/// failure as "cannot validate; skip cap check" to avoid false compile errors
/// on non-date `until` strings (e.g., version tags like `"v2.0"`).
///
/// UTC mandate per ADR-023 §Enforcement-Surface.
fn parse_iso_date(s: &str) -> Result<chrono::NaiveDate, ()> {
    chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|_| ())
}

/// Return today's UTC date for cap calculations when `since` is absent.
fn today_utc() -> chrono::NaiveDate {
    chrono::Utc::now().date_naive()
}

// ============================================================================
// Helpers
// ============================================================================

struct MetaPair {
    key: Ident,
    value: Expr,
}

impl Parse for MetaPair {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let key: Ident = input.parse()?;
        input.parse::<Token![=]>()?;
        let value: Expr = input.parse()?;
        Ok(Self { key, value })
    }
}

impl MetaPair {
    fn expect_string(&self) -> syn::Result<String> {
        if let Expr::Lit(syn::ExprLit {
            lit: Lit::Str(s), ..
        }) = &self.value
        {
            Ok(s.value())
        } else {
            Err(syn::Error::new_spanned(
                &self.value,
                format!("expected a string literal for `{}`", self.key),
            ))
        }
    }

    /// Like [`Self::expect_string`] but also returns the span of the string
    /// literal so validation errors can point at the literal itself.
    fn expect_string_spanned(&self) -> syn::Result<(String, Span)> {
        if let Expr::Lit(syn::ExprLit {
            lit: Lit::Str(s), ..
        }) = &self.value
        {
            Ok((s.value(), s.span()))
        } else {
            Err(syn::Error::new_spanned(
                &self.value,
                format!("expected a string literal for `{}`", self.key),
            ))
        }
    }

    fn expect_string_array(&self) -> syn::Result<Vec<String>> {
        if let Expr::Array(arr) = &self.value {
            let mut out = Vec::new();
            for elem in &arr.elems {
                if let Expr::Lit(syn::ExprLit {
                    lit: Lit::Str(s), ..
                }) = elem
                {
                    out.push(s.value());
                } else {
                    return Err(syn::Error::new_spanned(
                        elem,
                        "expected a string literal in references array",
                    ));
                }
            }
            Ok(out)
        } else {
            Err(syn::Error::new_spanned(
                &self.value,
                format!("expected a string array for `{}`", self.key),
            ))
        }
    }

    /// Parse `category = AntigenCategory::X` (single) or
    /// `category = [AntigenCategory::X, AntigenCategory::Y]` (hybrid).
    ///
    /// Accepts path expressions like `AntigenCategory::SubstrateAlignment` or
    /// plain idents like `SubstrateAlignment`. String literals are NOT
    /// accepted — the category must be a path expression for compile-time
    /// discoverability.
    fn expect_antigen_category(&self) -> syn::Result<Vec<MacroAntigenCategory>> {
        fn parse_single(expr: &Expr) -> syn::Result<MacroAntigenCategory> {
            // Convert the expression to a string representation and then match
            let s = match expr {
                Expr::Path(p) => {
                    // Reconstruct the path string: "AntigenCategory::SubstrateAlignment"
                    // or just "SubstrateAlignment"
                    let segments: Vec<String> = p
                        .path
                        .segments
                        .iter()
                        .map(|seg| seg.ident.to_string())
                        .collect();
                    segments.join("::")
                }
                _ => {
                    return Err(syn::Error::new_spanned(
                        expr,
                        "expected `AntigenCategory::SubstrateAlignment` or \
                         `AntigenCategory::FunctionalCorrectness`",
                    ));
                }
            };
            MacroAntigenCategory::from_path_str(&s).ok_or_else(|| {
                syn::Error::new_spanned(
                    expr,
                    format!(
                        "unknown AntigenCategory `{s}`; expected \
                         `AntigenCategory::SubstrateAlignment` or \
                         `AntigenCategory::FunctionalCorrectness`"
                    ),
                )
            })
        }

        match &self.value {
            Expr::Array(arr) => {
                let mut out = Vec::new();
                for elem in &arr.elems {
                    out.push(parse_single(elem)?);
                }
                if out.is_empty() {
                    return Err(syn::Error::new_spanned(
                        &self.value,
                        "`category` array must not be empty",
                    ));
                }
                Ok(out)
            }
            single => Ok(vec![parse_single(single)?]),
        }
    }

    /// Parse `provenance = Provenance::Heuristic` (single path expression).
    /// Accepts the qualified path (`Provenance::Heuristic`) or the plain Pascal
    /// ident (`Heuristic`). String literals are NOT accepted — provenance must be
    /// a path expression for compile-time discoverability (same as `category`).
    fn expect_provenance(&self) -> syn::Result<MacroProvenance> {
        let s = path_expr_to_string(&self.value).ok_or_else(|| {
            syn::Error::new_spanned(
                &self.value,
                "expected a provenance path like `Provenance::Heuristic` \
                 (Encountered | Constructable | Heuristic | Imagined)",
            )
        })?;
        MacroProvenance::from_path_str(&s).ok_or_else(|| {
            syn::Error::new_spanned(
                &self.value,
                format!(
                    "unknown Provenance `{s}`; expected one of \
                     `Provenance::Encountered`, `Provenance::Constructable`, \
                     `Provenance::Heuristic`, `Provenance::Imagined`"
                ),
            )
        })
    }

    /// Parse `presentation = Presentation::Passive` (single path expression).
    /// Accepts the qualified path or the plain Pascal ident.
    fn expect_presentation(&self) -> syn::Result<MacroPresentation> {
        let s = path_expr_to_string(&self.value).ok_or_else(|| {
            syn::Error::new_spanned(
                &self.value,
                "expected a presentation path like `Presentation::Passive` \
                 (Passive | Active)",
            )
        })?;
        MacroPresentation::from_path_str(&s).ok_or_else(|| {
            syn::Error::new_spanned(
                &self.value,
                format!(
                    "unknown Presentation `{s}`; expected \
                     `Presentation::Passive` or `Presentation::Active`"
                ),
            )
        })
    }
}

/// Reconstruct a `::`-joined path string from a path expression
/// (`Provenance::Heuristic` → `"Provenance::Heuristic"`, `Heuristic` →
/// `"Heuristic"`). Returns `None` for non-path expressions (string literals,
/// arrays, etc.). Shared by the single-value path-enum parsers.
fn path_expr_to_string(expr: &Expr) -> Option<String> {
    match expr {
        Expr::Path(p) => Some(
            p.path
                .segments
                .iter()
                .map(|seg| seg.ident.to_string())
                .collect::<Vec<_>>()
                .join("::"),
        ),
        _ => None,
    }
}

fn is_kebab_case(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        && !s.starts_with('-')
        && !s.ends_with('-')
        && !s.contains("--")
}

// ============================================================================
// Prescriptive Work-Orchestration Family arg-parsers (ADR-033, extends ADR-024)
//
// Eight clinical-named macros route to four structural shapes. These seven
// (panel/rx/refer/biopsy/ddx/culture/quarantine) are unambiguous; `#[triage]`
// (S3 Ordering) is held pending a ratified-ADR-vs-test-corpus arg-shape
// divergence (camp question fc2e1677). All field shapes follow ADR-033
// §Proc-Macro-Surface tables S1/S2/S4 exactly. Parse uses the `MetaPair` +
// `parse_terminated` idiom (the cleaner of the two in-file conventions); the
// who-ref `Vec<String>` fields are ADR-020 role-refs; frame fields are ISO-8601
// date strings (advisory parse, audit-time evaluated).
// ============================================================================

/// Arguments to `#[panel(needs, filled_by?, reviewed_by?, ordered_by?, due?)]`
/// (ADR-033 S1 Role-workflow). `needs` is the battery's checklist (required,
/// non-empty); satisfaction is collective coverage over the need-set attested
/// per role-step (ADR-033 §Witness-binding), NOT a positional pairing.
#[derive(Debug)]
pub struct PanelArgs {
    pub needs: Vec<String>,
    pub needs_present: bool,
    #[allow(dead_code)]
    pub filled_by: Vec<String>,
    #[allow(dead_code)]
    pub reviewed_by: Vec<String>,
    #[allow(dead_code)]
    pub ordered_by: Option<String>,
    #[allow(dead_code)]
    pub due: Option<String>,
    pub args_span: Span,
}

impl Parse for PanelArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut needs: Vec<String> = Vec::new();
        let mut needs_present = false;
        let mut filled_by: Vec<String> = Vec::new();
        let mut reviewed_by: Vec<String> = Vec::new();
        let mut ordered_by: Option<String> = None;
        let mut due: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "needs" => {
                    needs = pair.expect_string_array()?;
                    needs_present = true;
                }
                "filled_by" => filled_by = pair.expect_string_array()?,
                "reviewed_by" => reviewed_by = pair.expect_string_array()?,
                "ordered_by" => ordered_by = Some(pair.expect_string()?),
                "due" => due = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[panel] field `{other}`; expected one of: \
                             needs, filled_by, reviewed_by, ordered_by, due"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            needs,
            needs_present,
            filled_by,
            reviewed_by,
            ordered_by,
            due,
            args_span,
        })
    }
}

impl PanelArgs {
    /// `needs` is required and non-empty (empty = vacuous work-need; the
    /// `EmptySignersList` vacuous-guard class, ADR-033 §Proc-Macro-Surface +
    /// ATK-PRES-1).
    pub fn validate(&self) -> syn::Result<()> {
        if !self.needs_present {
            return Err(syn::Error::new(
                self.args_span,
                "#[panel] requires `needs = [\"...\", ...]` (the battery's checklist).",
            ));
        }
        if self.needs.iter().all(|n| n.trim().is_empty()) {
            return Err(syn::Error::new(
                self.args_span,
                "#[panel] `needs` must be non-empty — an empty checklist is a vacuous \
                 work-need (it would always read as satisfied).",
            ));
        }
        Ok(())
    }
}

/// Arguments to `#[rx(treatment, diagnosis?, filled_by?, reviewed_by?, due?)]`
/// (ADR-033 S1 Role-workflow).
#[derive(Debug)]
pub struct RxArgs {
    pub treatment: Option<String>,
    pub treatment_span: Option<Span>,
    #[allow(dead_code)]
    pub diagnosis: Option<String>,
    #[allow(dead_code)]
    pub filled_by: Vec<String>,
    #[allow(dead_code)]
    pub reviewed_by: Vec<String>,
    #[allow(dead_code)]
    pub due: Option<String>,
    pub args_span: Span,
}

impl Parse for RxArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut treatment: Option<String> = None;
        let mut treatment_span: Option<Span> = None;
        let mut diagnosis: Option<String> = None;
        let mut filled_by: Vec<String> = Vec::new();
        let mut reviewed_by: Vec<String> = Vec::new();
        let mut due: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "treatment" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    treatment = Some(s);
                    treatment_span = Some(span);
                }
                "diagnosis" => diagnosis = Some(pair.expect_string()?),
                "filled_by" => filled_by = pair.expect_string_array()?,
                "reviewed_by" => reviewed_by = pair.expect_string_array()?,
                "due" => due = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[rx] field `{other}`; expected one of: \
                             treatment, diagnosis, filled_by, reviewed_by, due"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            treatment,
            treatment_span,
            diagnosis,
            filled_by,
            reviewed_by,
            due,
            args_span,
        })
    }
}

impl RxArgs {
    /// `treatment` is required and non-empty.
    pub fn validate(&self) -> syn::Result<()> {
        match self.treatment.as_deref() {
            None => Err(syn::Error::new(
                self.args_span,
                "#[rx] requires `treatment = \"...\"` (what must be done).",
            )),
            Some(s) if s.trim().is_empty() => Err(syn::Error::new(
                self.treatment_span.unwrap_or(self.args_span),
                "#[rx] `treatment` cannot be empty.",
            )),
            Some(_) => Ok(()),
        }
    }
}

/// Arguments to `#[refer(to, response_due?)]` (ADR-033 S1 Role-workflow).
#[derive(Debug)]
pub struct ReferArgs {
    pub to: Option<String>,
    pub to_span: Option<Span>,
    #[allow(dead_code)]
    pub response_due: Option<String>,
    pub args_span: Span,
}

impl Parse for ReferArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut to: Option<String> = None;
        let mut to_span: Option<Span> = None;
        let mut response_due: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "to" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    to = Some(s);
                    to_span = Some(span);
                }
                "response_due" => response_due = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[refer] field `{other}`; expected one of: \
                             to, response_due"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            to,
            to_span,
            response_due,
            args_span,
        })
    }
}

impl ReferArgs {
    /// `to` is required and non-empty (the external owner who-ref).
    pub fn validate(&self) -> syn::Result<()> {
        match self.to.as_deref() {
            None => Err(syn::Error::new(
                self.args_span,
                "#[refer] requires `to = \"who\"` (the external owner this work is referred to).",
            )),
            Some(s) if s.trim().is_empty() => Err(syn::Error::new(
                self.to_span.unwrap_or(self.args_span),
                "#[refer] `to` cannot be empty.",
            )),
            Some(_) => Ok(()),
        }
    }
}

/// Arguments to `#[biopsy(location, request_text, deep_investigation_by?)]`
/// (ADR-033 S1 Role-workflow).
#[derive(Debug)]
pub struct BiopsyArgs {
    pub location: Option<String>,
    pub location_span: Option<Span>,
    pub request_text: Option<String>,
    pub request_text_span: Option<Span>,
    #[allow(dead_code)]
    pub deep_investigation_by: Option<String>,
    pub args_span: Span,
}

impl Parse for BiopsyArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut location: Option<String> = None;
        let mut location_span: Option<Span> = None;
        let mut request_text: Option<String> = None;
        let mut request_text_span: Option<Span> = None;
        let mut deep_investigation_by: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "location" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    location = Some(s);
                    location_span = Some(span);
                }
                "request_text" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    request_text = Some(s);
                    request_text_span = Some(span);
                }
                "deep_investigation_by" => deep_investigation_by = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[biopsy] field `{other}`; expected one of: \
                             location, request_text, deep_investigation_by"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            location,
            location_span,
            request_text,
            request_text_span,
            deep_investigation_by,
            args_span,
        })
    }
}

impl BiopsyArgs {
    /// Both `location` and `request_text` are required; `request_text` non-empty.
    pub fn validate(&self) -> syn::Result<()> {
        match self.location.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[biopsy] requires `location = \"...\"` (the sub-site to investigate).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.location_span.unwrap_or(self.args_span),
                    "#[biopsy] `location` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        match self.request_text.as_deref() {
            None => Err(syn::Error::new(
                self.args_span,
                "#[biopsy] requires `request_text = \"...\"` (what to investigate).",
            )),
            Some(s) if s.trim().is_empty() => Err(syn::Error::new(
                self.request_text_span.unwrap_or(self.args_span),
                "#[biopsy] `request_text` cannot be empty.",
            )),
            Some(_) => Ok(()),
        }
    }
}

/// Arguments to `#[ddx(symptom, rule_out, investigator?, reviewer?)]`
/// (ADR-033 S2 Elimination).
#[derive(Debug)]
pub struct DdxArgs {
    pub symptom: Option<String>,
    pub symptom_span: Option<Span>,
    pub rule_out: Vec<String>,
    pub rule_out_present: bool,
    #[allow(dead_code)]
    pub investigator: Option<String>,
    #[allow(dead_code)]
    pub reviewer: Option<String>,
    pub args_span: Span,
}

impl Parse for DdxArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut symptom: Option<String> = None;
        let mut symptom_span: Option<Span> = None;
        let mut rule_out: Vec<String> = Vec::new();
        let mut rule_out_present = false;
        let mut investigator: Option<String> = None;
        let mut reviewer: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "symptom" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    symptom = Some(s);
                    symptom_span = Some(span);
                }
                "rule_out" => {
                    rule_out = pair.expect_string_array()?;
                    rule_out_present = true;
                }
                "investigator" => investigator = Some(pair.expect_string()?),
                "reviewer" => reviewer = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[ddx] field `{other}`; expected one of: \
                             symptom, rule_out, investigator, reviewer"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            symptom,
            symptom_span,
            rule_out,
            rule_out_present,
            investigator,
            reviewer,
            args_span,
        })
    }
}

impl DdxArgs {
    /// `symptom` required + non-empty; `rule_out` required + non-empty (an empty
    /// alternative-set is no differential diagnosis; ATK-PRES-2).
    pub fn validate(&self) -> syn::Result<()> {
        match self.symptom.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[ddx] requires `symptom = \"...\"` (the observed problem).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.symptom_span.unwrap_or(self.args_span),
                    "#[ddx] `symptom` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        if !self.rule_out_present {
            return Err(syn::Error::new(
                self.args_span,
                "#[ddx] requires `rule_out = [\"...\", ...]` (the alternatives to eliminate).",
            ));
        }
        if self.rule_out.iter().all(|r| r.trim().is_empty()) {
            return Err(syn::Error::new(
                self.args_span,
                "#[ddx] `rule_out` must be non-empty — an empty alternative-set is no \
                 differential diagnosis.",
            ));
        }
        Ok(())
    }
}

/// Arguments to `#[culture(test_kind, duration?, runs_until?)]`
/// (ADR-033 S4 Frame-only).
#[derive(Debug)]
pub struct CultureArgs {
    pub test_kind: Option<String>,
    pub test_kind_span: Option<Span>,
    #[allow(dead_code)]
    pub duration: Option<String>,
    #[allow(dead_code)]
    pub runs_until: Option<String>,
    pub args_span: Span,
}

impl Parse for CultureArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut test_kind: Option<String> = None;
        let mut test_kind_span: Option<Span> = None;
        let mut duration: Option<String> = None;
        let mut runs_until: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "test_kind" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    test_kind = Some(s);
                    test_kind_span = Some(span);
                }
                "duration" => duration = Some(pair.expect_string()?),
                "runs_until" => runs_until = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[culture] field `{other}`; expected one of: \
                             test_kind, duration, runs_until"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            test_kind,
            test_kind_span,
            duration,
            runs_until,
            args_span,
        })
    }
}

impl CultureArgs {
    /// `test_kind` is required and non-empty.
    pub fn validate(&self) -> syn::Result<()> {
        match self.test_kind.as_deref() {
            None => Err(syn::Error::new(
                self.args_span,
                "#[culture] requires `test_kind = \"...\"` (what is being cultured/observed).",
            )),
            Some(s) if s.trim().is_empty() => Err(syn::Error::new(
                self.test_kind_span.unwrap_or(self.args_span),
                "#[culture] `test_kind` cannot be empty.",
            )),
            Some(_) => Ok(()),
        }
    }
}

/// Arguments to `#[quarantine(scope, until?, reason)]` (ADR-033 S4 Frame-only).
/// `reason` is required per ADR-005 Amendment 2 (rationale-as-required for every
/// suppression-shaped primitive).
#[derive(Debug)]
pub struct QuarantineArgs {
    pub scope: Option<String>,
    pub scope_span: Option<Span>,
    #[allow(dead_code)]
    pub until: Option<String>,
    pub reason: Option<String>,
    pub reason_span: Option<Span>,
    pub args_span: Span,
}

impl Parse for QuarantineArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut scope: Option<String> = None;
        let mut scope_span: Option<Span> = None;
        let mut until: Option<String> = None;
        let mut reason: Option<String> = None;
        let mut reason_span: Option<Span> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "scope" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    scope = Some(s);
                    scope_span = Some(span);
                }
                "until" => until = Some(pair.expect_string()?),
                "reason" => {
                    let (s, span) = pair.expect_string_spanned()?;
                    reason = Some(s);
                    reason_span = Some(span);
                }
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[quarantine] field `{other}`; expected one of: \
                             scope, until, reason"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            scope,
            scope_span,
            until,
            reason,
            reason_span,
            args_span,
        })
    }
}

impl QuarantineArgs {
    /// `scope` required + non-empty; `reason` required + non-empty (ADR-005
    /// Amendment 2 rationale-as-required; ATK-PRES-3).
    pub fn validate(&self) -> syn::Result<()> {
        match self.scope.as_deref() {
            None => {
                return Err(syn::Error::new(
                    self.args_span,
                    "#[quarantine] requires `scope = \"...\"` (the isolated region).",
                ));
            }
            Some(s) if s.trim().is_empty() => {
                return Err(syn::Error::new(
                    self.scope_span.unwrap_or(self.args_span),
                    "#[quarantine] `scope` cannot be empty.",
                ));
            }
            Some(_) => {}
        }
        match self.reason.as_deref() {
            None => Err(syn::Error::new(
                self.args_span,
                "#[quarantine] requires `reason = \"...\"` (why the hold; ADR-005 Amendment 2 \
                 rationale-as-required).",
            )),
            Some(s) if s.trim().is_empty() => Err(syn::Error::new(
                self.reason_span.unwrap_or(self.args_span),
                "#[quarantine] `reason` cannot be empty (ADR-005 Amendment 2).",
            )),
            Some(_) => Ok(()),
        }
    }
}

/// Arguments to `#[triage(priority_order, triaged_by?, re_triage_due?)]`
/// (ADR-033 S3 Ordering). Per the 2026-06-01 post-ratification fixup, `campsites`
/// was DROPPED (transcription drift); `priority_order` entries are **code-site
/// references** (file/item-path), in priority order — NOT camp campsites (anchor
/// #3: the audit never reads camp). Resolution is at audit-time (ADR-017
/// Amendment 1): an unresolvable ref ⇒ `out-of-frame`, never silent-satisfied.
#[derive(Debug)]
pub struct TriageArgs {
    pub priority_order: Vec<String>,
    pub priority_order_present: bool,
    #[allow(dead_code)]
    pub triaged_by: Option<String>,
    #[allow(dead_code)]
    pub re_triage_due: Option<String>,
    pub args_span: Span,
}

impl Parse for TriageArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let args_span = input.span();
        let mut priority_order: Vec<String> = Vec::new();
        let mut priority_order_present = false;
        let mut triaged_by: Option<String> = None;
        let mut re_triage_due: Option<String> = None;

        let pairs: Punctuated<MetaPair, Token![,]> =
            input.parse_terminated(MetaPair::parse, Token![,])?;
        for pair in pairs {
            match pair.key.to_string().as_str() {
                "priority_order" => {
                    priority_order = pair.expect_string_array()?;
                    priority_order_present = true;
                }
                "triaged_by" => triaged_by = Some(pair.expect_string()?),
                "re_triage_due" => re_triage_due = Some(pair.expect_string()?),
                other => {
                    return Err(syn::Error::new(
                        pair.key.span(),
                        format!(
                            "unknown #[triage] field `{other}`; expected one of: \
                             priority_order, triaged_by, re_triage_due (note: `campsites` was \
                             dropped — `priority_order` entries are code-site references)"
                        ),
                    ));
                }
            }
        }
        Ok(Self {
            priority_order,
            priority_order_present,
            triaged_by,
            re_triage_due,
            args_span,
        })
    }
}

impl TriageArgs {
    /// `priority_order` is required and non-empty (an empty ordering is a vacuous
    /// work-need; joins the `EmptySignersList` vacuous-guard class — ADR-033
    /// §Enforcement-Surface).
    pub fn validate(&self) -> syn::Result<()> {
        if !self.priority_order_present {
            return Err(syn::Error::new(
                self.args_span,
                "#[triage] requires `priority_order = [\"...\", ...]` (code-site references in \
                 priority order).",
            ));
        }
        if self.priority_order.iter().all(|p| p.trim().is_empty()) {
            return Err(syn::Error::new(
                self.args_span,
                "#[triage] `priority_order` must be non-empty — an empty ordering is a vacuous \
                 work-need.",
            ));
        }
        Ok(())
    }
}

// The `requires_json_tests` module previously lived here; it moved with the
// parser into `antigen_attestation::parser` (run via
// `cargo test -p antigen-attestation --features parser`). Keeping the tests
// next to the implementation prevents drift and removes the
// circular-dependency-by-test-coupling that used to live in this file.

// ============================================================================
// Cross-parser equivalence fixtures
//
// These fixtures define the invariant: for any input the macro side accepts as
// valid, the scan side must produce equivalent semantic content for the four
// overlapping fields (name, fingerprint, family, summary). The same fixture
// table appears in `antigen/src/scan.rs` (ScanAntigenArgs tests) — keeping the
// inputs and expected outputs literally identical is what makes the
// equivalence inspectable.
//
// ATK-001-2 lesson: the brittle string-manipulation parser corrupted
// fingerprints with inner double-quotes silently. Property tests over both
// parsers prevent that class of drift from re-emerging.
//
// When adding a fixture here, add the matching one to scan.rs. When adding a
// new field to the antigen attribute grammar, add fixtures here AND to scan.rs
// to lock the equivalence.
// ============================================================================

/// Fixture tuple shape: `(input, expected_name, expected_fingerprint,
/// expected_family, expected_summary)`.
#[cfg(test)]
type AntigenFixture = (
    &'static str,
    &'static str,
    &'static str,
    Option<&'static str>,
    Option<&'static str>,
);

#[cfg(test)]
const ANTIGEN_PARSER_FIXTURES: &[AntigenFixture] = &[
    // 1. Smoke test: just the two required fields.
    (
        r#"name = "panicking-in-drop", fingerprint = "impl Drop with panic""#,
        "panicking-in-drop",
        "impl Drop with panic",
        None,
        None,
    ),
    // 2. All four fields populated.
    (
        r#"name = "frame-translation", fingerprint = "class enum + meet", family = "semantic-drift", summary = "Polarity inverts at the frame boundary""#,
        "frame-translation",
        "class enum + meet",
        Some("semantic-drift"),
        Some("Polarity inverts at the frame boundary"),
    ),
    // 3. Inner-quoted fingerprint (the ATK-001-2 regression case).
    (
        r#"name = "x", fingerprint = "item: enum, has_method(\"meet\", \"(Self, Self) -> Self\")""#,
        "x",
        r#"item: enum, has_method("meet", "(Self, Self) -> Self")"#,
        None,
        None,
    ),
    // 4. Reordered fields (order-invariance check).
    (
        r#"summary = "S", family = "F", fingerprint = "FP", name = "n""#,
        "n",
        "FP",
        Some("F"),
        Some("S"),
    ),
    // 5. References array present (macro stores; scan ignores; both must
    //    accept without error).
    (
        r#"name = "x", fingerprint = "y", references = ["GAP-1", "DEC-2"]"#,
        "x",
        "y",
        None,
        None,
    ),
    // 6. Multi-line whitespace (tab + newline) — common rustfmt output shape.
    (
        "name = \"multi-line\",\n\tfingerprint = \"shape\",\n\tfamily = \"family\"",
        "multi-line",
        "shape",
        Some("family"),
        None,
    ),
];

#[cfg(test)]
mod tests {
    use super::*;
    use proc_macro2::TokenStream;

    #[test]
    fn antigen_parser_accepts_all_fixtures() {
        for (input, exp_name, exp_fp, exp_family, exp_summary) in ANTIGEN_PARSER_FIXTURES {
            let tokens: TokenStream = input
                .parse()
                .unwrap_or_else(|e| panic!("fixture failed to tokenize: {input:?}: {e}"));
            let args = syn::parse2::<AntigenArgs>(tokens)
                .unwrap_or_else(|e| panic!("macro parser rejected fixture {input:?}: {e}"));
            assert_eq!(&args.name, exp_name, "name mismatch for fixture: {input:?}");
            assert_eq!(
                args.fingerprint.as_deref(),
                Some(*exp_fp),
                "fingerprint mismatch for fixture: {input:?}"
            );
            assert_eq!(
                args.family.as_deref(),
                *exp_family,
                "family mismatch for fixture: {input:?}"
            );
            assert_eq!(
                args.summary.as_deref(),
                *exp_summary,
                "summary mismatch for fixture: {input:?}"
            );
        }
    }

    #[test]
    fn antigen_parser_rejects_missing_name() {
        let tokens: TokenStream = r#"fingerprint = "x""#.parse().unwrap();
        assert!(syn::parse2::<AntigenArgs>(tokens).is_err());
    }

    #[test]
    fn antigen_parser_accepts_missing_fingerprint_as_verify_only() {
        // ADR-009 Amendment 1: a missing `fingerprint` is no longer an error —
        // it declares a verify-only antigen (external-substrate detection-model,
        // no syn-scan surface). Parse succeeds with `fingerprint: None`, and
        // validate() does not require it.
        let tokens: TokenStream = r#"name = "verify-only-class""#.parse().unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens)
            .expect("a fingerprint-less #[antigen] is a valid verify-only declaration");
        assert!(
            args.fingerprint.is_none(),
            "absent fingerprint must parse as None, not a placeholder"
        );
        assert!(
            args.validate().is_ok(),
            "validate() must accept a verify-only antigen (no fingerprint to check)"
        );
    }

    #[test]
    fn antigen_parser_rejects_unknown_field() {
        let tokens: TokenStream = r#"name = "x", fingerprint = "y", bogus = "z""#.parse().unwrap();
        match syn::parse2::<AntigenArgs>(tokens) {
            Ok(_) => panic!("expected parse to reject unknown field `bogus`"),
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    msg.contains("unknown") && msg.contains("bogus"),
                    "expected unknown-field error mentioning `bogus`, got: {msg}"
                );
            }
        }
    }

    /// Construct an `AntigenArgs` with the given name + a valid DSL fingerprint.
    /// Used by direct-construction tests that bypass `Parse` to exercise
    /// name-validation paths in `validate()`. Tests that need to exercise
    /// fingerprint-validation paths build their own `AntigenArgs` literal
    /// with the specific fingerprint they want to assert against.
    fn args_with(name: &str, fingerprint: &str) -> AntigenArgs {
        AntigenArgs {
            name: name.to_string(),
            fingerprint: Some(fingerprint.to_string()),
            family: None,
            summary: None,
            references: Vec::new(),
            category: Vec::new(),
            provenance: None,
            presentation: None,
            name_span: Some(proc_macro2::Span::call_site()),
            fingerprint_span: Some(proc_macro2::Span::call_site()),
            args_span: proc_macro2::Span::call_site(),
        }
    }

    /// Minimal DSL fingerprint string accepted by the W6a parser. Tests that
    /// don't care about fingerprint content but DO want `validate()` to succeed
    /// use this to keep their assertions focused on name validation.
    const VALID_DSL: &str = r#"name = matches("*")"#;

    #[test]
    fn validate_rejects_empty_name() {
        assert!(args_with("", VALID_DSL).validate().is_err());
    }

    #[test]
    fn validate_rejects_non_kebab_name() {
        assert!(args_with("FooBar", VALID_DSL).validate().is_err());
    }

    #[test]
    fn validate_accepts_kebab_name_with_digits() {
        assert!(args_with("frame-2-translation", VALID_DSL)
            .validate()
            .is_ok());
    }

    #[test]
    fn validate_rejects_name_with_double_hyphen() {
        assert!(args_with("frame--translation", VALID_DSL)
            .validate()
            .is_err());
    }

    #[test]
    fn validate_rejects_name_starting_with_hyphen() {
        assert!(args_with("-frame", VALID_DSL).validate().is_err());
    }

    #[test]
    fn validate_rejects_malformed_dsl_fingerprint() {
        let args = args_with("ok-name", "this is not the dsl");
        let err = args.validate().unwrap_err().to_string();
        assert!(err.contains("fingerprint"), "got: {err}");
    }

    #[test]
    fn immune_parser_requires_witness() {
        let tokens: TokenStream = r"PanickingInDrop".parse().unwrap();
        let args = syn::parse2::<ImmuneArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn immune_parser_accepts_witness_path() {
        let tokens: TokenStream = r"PanickingInDrop, witness = my::module::test_fn"
            .parse()
            .unwrap();
        let args = syn::parse2::<ImmuneArgs>(tokens).unwrap();
        assert!(args.witness.is_some());
        assert!(args.validate().is_ok());
    }

    #[test]
    fn immune_parser_accepts_rationale() {
        let tokens: TokenStream = r#"X, witness = my_test, rationale = "checked manually""#
            .parse()
            .unwrap();
        let args = syn::parse2::<ImmuneArgs>(tokens).unwrap();
        assert_eq!(args.rationale.as_deref(), Some("checked manually"));
    }

    // Witness for #[immune(UnvalidatedSealedEnumAcceptance, ...)] on
    // DiagnosticArgs::validate — the sealed WitnessClass set is enforced at
    // parse/validate time; a non-variant ident must be rejected, not silently
    // counted as a valid modality.

    #[test]
    fn diagnostic_validate_rejects_unknown_witness_class() {
        // `WitnessClass::Nonsense` is not one of the 6 ratified variants.
        // Before the fix, this was captured as the string "Nonsense" and
        // counted toward the distinctness check (UnvalidatedSealedEnumAcceptance).
        let tokens: TokenStream = r"modalities = [WitnessClass::Nonsense], min_independent = 1"
            .parse()
            .unwrap();
        let args = syn::parse2::<DiagnosticArgs>(tokens).unwrap();
        let err = args
            .validate()
            .expect_err("an unknown WitnessClass variant must be rejected")
            .to_string();
        assert!(
            err.contains("Nonsense") && err.contains("WitnessClass"),
            "error must name the offending ident + the valid set: {err}"
        );
    }

    #[test]
    fn diagnostic_validate_rejects_non_witness_class_path() {
        // Any `Foo::Bar` path is captured as its last ident; it must not pass
        // as a modality just because it parses as a path.
        let tokens: TokenStream = r"modalities = [Foo::Bar], min_independent = 1"
            .parse()
            .unwrap();
        let args = syn::parse2::<DiagnosticArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "a non-WitnessClass path must be rejected, not counted as a modality"
        );
    }

    #[test]
    fn diagnostic_validate_accepts_all_known_witness_classes() {
        // The 6 ratified variants must all pass — the allowlist must not be
        // narrower than the real WitnessClass enum (a too-strict allowlist
        // would reject valid modalities).
        let tokens: TokenStream = "modalities = [WitnessClass::StaticAnalysis, \
             WitnessClass::PropertyTest, WitnessClass::FormalVerification, \
             WitnessClass::ManualReview, WitnessClass::RuntimeFuzz, \
             WitnessClass::SubstrateWitness], min_independent = 6"
            .parse()
            .unwrap();
        let args = syn::parse2::<DiagnosticArgs>(tokens).unwrap();
        args.validate()
            .expect("all 6 ratified WitnessClass variants must validate");
    }

    #[test]
    fn requires_expr_depth_guard_rejects_excessive_nesting() {
        // Build a RequiresExpr at depth MAX_DEPTH+1 programmatically (bypassing
        // the proc-macro parse path, which would stack-overflow for truly pathological
        // depth). The validate() path runs the depth check post-parse.
        const MAX_DEPTH: usize = 64;
        let leaf = RequiresExpr::Leaf(LeafExpr::FreshWithinDays { days: 90 });
        let mut pred = leaf;
        // Wrap in MAX_DEPTH+1 levels of Not — one too many.
        for _ in 0..=MAX_DEPTH {
            pred = RequiresExpr::Not(Box::new(pred));
        }
        let err = pred
            .validate(proc_macro2::Span::call_site())
            .expect_err("depth exceeding MAX_DEPTH must be rejected by validate()");
        assert!(
            err.to_string().contains("depth") || err.to_string().contains("nesting"),
            "error must mention depth/nesting: {err}"
        );
    }

    #[test]
    fn requires_expr_depth_guard_accepts_at_max_depth() {
        // A predicate at exactly MAX_DEPTH nesting must be accepted.
        const MAX_DEPTH: usize = 64;
        let leaf = RequiresExpr::Leaf(LeafExpr::FreshWithinDays { days: 90 });
        let mut pred = leaf;
        for _ in 0..MAX_DEPTH {
            pred = RequiresExpr::Not(Box::new(pred));
        }
        assert!(
            pred.validate(proc_macro2::Span::call_site()).is_ok(),
            "predicate at exactly MAX_DEPTH must be accepted"
        );
    }

    // ========================================================================
    // AntigenCategory parsing tests (ADR-028)
    // ========================================================================

    #[test]
    fn antigen_parser_accepts_category_single_substrate_alignment() {
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", category = AntigenCategory::SubstrateAlignment"#
                .parse()
                .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(
            args.category,
            vec![MacroAntigenCategory::SubstrateAlignment]
        );
    }

    #[test]
    fn antigen_parser_accepts_category_single_functional_correctness() {
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", category = AntigenCategory::FunctionalCorrectness"#
                .parse()
                .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(
            args.category,
            vec![MacroAntigenCategory::FunctionalCorrectness]
        );
    }

    #[test]
    fn antigen_parser_accepts_category_hybrid_array() {
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn", category = [AntigenCategory::SubstrateAlignment, AntigenCategory::FunctionalCorrectness]"#
            .parse()
            .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(
            args.category,
            vec![
                MacroAntigenCategory::SubstrateAlignment,
                MacroAntigenCategory::FunctionalCorrectness
            ]
        );
    }

    #[test]
    fn antigen_parser_accepts_bare_path_without_type_prefix() {
        // Accept `SubstrateAlignment` without `AntigenCategory::` prefix
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", category = SubstrateAlignment"#
                .parse()
                .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(
            args.category,
            vec![MacroAntigenCategory::SubstrateAlignment]
        );
    }

    #[test]
    fn antigen_parser_accepts_absent_category_for_compat() {
        // v0.1 backward-compat: absent category is fine at parse time
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn""#.parse().unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert!(
            args.category.is_empty(),
            "absent category should yield empty vec"
        );
    }

    #[test]
    fn antigen_parser_rejects_unknown_category_variant() {
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", category = AntigenCategory::Unknown"#
                .parse()
                .unwrap();
        let result = syn::parse2::<AntigenArgs>(tokens);
        assert!(
            result.is_err(),
            "unknown category variant should be rejected"
        );
    }

    #[test]
    fn antigen_parser_rejects_empty_category_array() {
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn", category = []"#
            .parse()
            .unwrap();
        let result = syn::parse2::<AntigenArgs>(tokens);
        assert!(result.is_err(), "empty category array should be rejected");
    }

    // ========================================================================
    // ADR-039 §C — authored `provenance` + `presentation` fields (the
    // families-foundation increment). The provenance ladder + passive/active
    // axis (already in finding.rs) becomes the AUTHORED claim the audit
    // tier-VERIFIER checks; the confidence tier (suspected/named) is NOT
    // authored (dial-derived) — an author writing `tier =` is a helpful error.
    // ========================================================================

    #[test]
    fn antigen_parser_accepts_provenance_qualified_path() {
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", provenance = Provenance::Heuristic"#
                .parse()
                .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(args.provenance, Some(MacroProvenance::Heuristic));
    }

    #[test]
    fn antigen_parser_accepts_provenance_bare_pascal() {
        // Bare Pascal ident (no `Provenance::` prefix), mirroring category.
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", provenance = Constructable"#
                .parse()
                .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(args.provenance, Some(MacroProvenance::Constructable));
    }

    #[test]
    fn antigen_parser_accepts_all_four_provenance_tiers() {
        for (src, want) in [
            ("Provenance::Encountered", MacroProvenance::Encountered),
            ("Provenance::Constructable", MacroProvenance::Constructable),
            ("Provenance::Heuristic", MacroProvenance::Heuristic),
            ("Provenance::Imagined", MacroProvenance::Imagined),
        ] {
            let tokens: TokenStream =
                format!(r#"name = "x", fingerprint = "item = fn", provenance = {src}"#)
                    .parse()
                    .unwrap();
            let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
            assert_eq!(args.provenance, Some(want), "provenance {src}");
        }
    }

    #[test]
    fn antigen_parser_accepts_presentation_passive_and_active() {
        for (src, want) in [
            ("Presentation::Passive", MacroPresentation::Passive),
            ("Active", MacroPresentation::Active),
        ] {
            let tokens: TokenStream =
                format!(r#"name = "x", fingerprint = "item = fn", presentation = {src}"#)
                    .parse()
                    .unwrap();
            let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
            assert_eq!(args.presentation, Some(want), "presentation {src}");
        }
    }

    #[test]
    fn antigen_parser_absent_provenance_and_presentation_are_none() {
        // Absent ⇒ None at parse time. The audit defaults them
        // (provenance → Imagined, presentation → Passive); parse stays permissive
        // (backward-compat, same posture as absent category).
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn""#.parse().unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        assert_eq!(args.provenance, None, "absent provenance is None");
        assert_eq!(args.presentation, None, "absent presentation is None");
    }

    #[test]
    fn antigen_parser_rejects_unknown_provenance_variant() {
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", provenance = Provenance::Bogus"#
                .parse()
                .unwrap();
        let result = syn::parse2::<AntigenArgs>(tokens);
        assert!(
            result.is_err(),
            "an unknown Provenance variant must be rejected (the verified ladder is closed)"
        );
    }

    #[test]
    fn antigen_parser_rejects_authored_tier_with_helpful_error() {
        // There is NO authored confidence tier — it is dial-derived (ADR-039 §B).
        // An author reaching for `tier =`/`named =` gets a helpful error pointing
        // to `provenance =` (the verified claim that sets the tier floor).
        for key in ["tier", "confidence", "named", "suspected"] {
            let tokens: TokenStream =
                format!(r#"name = "x", fingerprint = "item = fn", {key} = Named"#)
                    .parse()
                    .unwrap();
            let result = syn::parse2::<AntigenArgs>(tokens);
            let err = result.expect_err("an authored tier field must be rejected");
            let msg = err.to_string();
            assert!(
                msg.contains("provenance") && msg.contains("dial-derived"),
                "the `{key}` rejection must point the author at provenance + name dial-derivation; got: {msg}"
            );
        }
    }

    #[test]
    fn macro_provenance_and_presentation_str_forms() {
        // as_str renders kebab (the serde/CLI form); from_path_str takes the
        // Pascal/path macro-input forms. The two are intentionally different
        // input/output surfaces (same split as MacroAntigenCategory).
        assert_eq!(MacroProvenance::Encountered.as_str(), "encountered");
        assert_eq!(MacroProvenance::Constructable.as_str(), "constructable");
        assert_eq!(MacroProvenance::Heuristic.as_str(), "heuristic");
        assert_eq!(MacroProvenance::Imagined.as_str(), "imagined");
        assert_eq!(MacroPresentation::Passive.as_str(), "passive");
        assert_eq!(MacroPresentation::Active.as_str(), "active");
        // from_path_str accepts Pascal + qualified; rejects kebab (not a path token).
        assert_eq!(
            MacroProvenance::from_path_str("Heuristic"),
            Some(MacroProvenance::Heuristic)
        );
        assert_eq!(
            MacroProvenance::from_path_str("Provenance::Heuristic"),
            Some(MacroProvenance::Heuristic)
        );
        assert_eq!(MacroProvenance::from_path_str("heuristic"), None);
    }

    // ========================================================================
    // MarkerArgs (ADR-041 — the marked-unknown plane). The KEYSTONE is the
    // required-trigger parse-reject (guard 3): a triggerless / empty-trigger
    // marker must fail, because a marked-unknown with no stated trigger is the
    // contentless "this seems off" graffiti the primitive exists to prevent.
    // ========================================================================

    fn marker(src: &str) -> syn::Result<MarkerArgs> {
        let tokens: TokenStream = src.parse().unwrap();
        syn::parse2::<MarkerArgs>(tokens)
    }

    #[test]
    fn marker_accepts_a_stated_trigger() {
        let m = marker(r#"trigger = "the teardown drops the guard before the flush""#)
            .expect("a marker with a stated trigger parses")
            .with_marker("dread");
        m.validate().expect("a stated non-empty trigger validates");
        assert_eq!(
            m.trigger_str(),
            "the teardown drops the guard before the flush"
        );
    }

    #[test]
    fn marker_rejects_missing_trigger() {
        // KEYSTONE (guard 3): a triggerless marker must be rejected at validate.
        // Parse succeeds (no args is syntactically fine); validate is the gate.
        let m = marker("").expect("empty args parse").with_marker("dread");
        let err = m
            .validate()
            .expect_err("a triggerless #[dread] must be rejected (guard 3)");
        let msg = err.to_string();
        assert!(
            msg.contains("dread") && msg.contains("trigger"),
            "the rejection must name the marker + the required trigger; got: {msg}"
        );
    }

    #[test]
    fn marker_rejects_empty_trigger() {
        // An empty (or whitespace-only) trigger is the same graffiti hole.
        for src in [r#"trigger = """#, r#"trigger = "   ""#] {
            let m = marker(src).expect("parses").with_marker("aura");
            assert!(
                m.validate().is_err(),
                "an empty/whitespace trigger must be rejected: {src}"
            );
        }
    }

    #[test]
    fn marker_rejects_authored_plane_corner() {
        // The plane corner (magnitude × existence-certainty) is FIXED by which
        // marker macro is used, NEVER authored — so magnitude=/existence_certainty=
        // are unknown fields that reject with a helpful message.
        for key in ["magnitude", "existence_certainty", "certainty"] {
            let result = marker(&format!(r#"{key} = "high", trigger = "x""#));
            let err = result.expect_err("an authored plane-corner field must be rejected");
            assert!(
                err.to_string().contains("FIXED"),
                "the `{key}` rejection must explain the corner is marker-fixed"
            );
        }
    }

    #[test]
    fn marker_rejects_unknown_field() {
        let result = marker(r#"trigger = "x", bogus = "y""#);
        let err = result.expect_err("an unknown marker field must be rejected");
        assert!(err.to_string().contains("trigger"));
    }

    #[test]
    fn marker_takes_no_positional_antigen() {
        // A marked-unknown names NOTHING — a positional path (as #[antigen_tolerance]
        // takes) is NOT accepted here. `SomeAntigen, trigger = "x"` must fail.
        let result = marker(r#"SomeAntigen, trigger = "x""#);
        assert!(
            result.is_err(),
            "a marked-unknown must not accept a positional antigen (it names nothing)"
        );
    }

    #[test]
    fn macro_antigen_category_as_str() {
        assert_eq!(
            MacroAntigenCategory::SubstrateAlignment.as_str(),
            "substrate-alignment"
        );
        assert_eq!(
            MacroAntigenCategory::FunctionalCorrectness.as_str(),
            "functional-correctness"
        );
    }

    #[test]
    fn macro_antigen_category_from_path_str_accepts_path_forms() {
        // from_path_str handles macro-input path tokens (Pascal or qualified path).
        // Kebab is NOT valid Rust path syntax — no macro author writes it.
        for s in ["SubstrateAlignment", "AntigenCategory::SubstrateAlignment"] {
            assert_eq!(
                MacroAntigenCategory::from_path_str(s),
                Some(MacroAntigenCategory::SubstrateAlignment),
                "expected SubstrateAlignment from {s:?}"
            );
        }
        for s in [
            "FunctionalCorrectness",
            "AntigenCategory::FunctionalCorrectness",
        ] {
            assert_eq!(
                MacroAntigenCategory::from_path_str(s),
                Some(MacroAntigenCategory::FunctionalCorrectness),
                "expected FunctionalCorrectness from {s:?}"
            );
        }
        // Kebab and snake are rejected.
        for s in [
            "substrate-alignment",
            "substrate_alignment",
            "functional-correctness",
            "functional_correctness",
        ] {
            assert_eq!(
                MacroAntigenCategory::from_path_str(s),
                None,
                "expected None (not a valid macro-input path token) for {s:?}"
            );
        }
    }

    // -------------------------------------------------------------------------
    // Adversarial tests (added by adversarial role)
    // -------------------------------------------------------------------------

    #[test]
    fn antigen_parser_duplicate_category_in_array_is_rejected() {
        // [SubstrateAlignment, SubstrateAlignment] must be rejected by validate():
        // duplicate entries look like hybrid (len == 2) but contain only one
        // distinct variant. Fixed by dedup-check in AntigenArgs::validate() per
        // aristotle Phase 1-8 ratification (ADR-028).
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn", category = [AntigenCategory::SubstrateAlignment, AntigenCategory::SubstrateAlignment]"#
            .parse()
            .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        let err = args.validate().unwrap_err().to_string();
        assert!(
            err.contains("duplicate") && err.contains("category"),
            "validate() must reject duplicate category entries; got: {err:?}"
        );
    }

    #[test]
    fn antigen_parser_three_element_category_array_with_duplicate_is_rejected() {
        // [SA, FC, SA] must be rejected: SA appears twice.
        // Even though FC is present (making it look hybrid), the duplicate SA
        // is structurally incorrect.
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn", category = [AntigenCategory::SubstrateAlignment, AntigenCategory::FunctionalCorrectness, AntigenCategory::SubstrateAlignment]"#
            .parse()
            .unwrap();
        let args = syn::parse2::<AntigenArgs>(tokens).unwrap();
        let err = args.validate().unwrap_err().to_string();
        assert!(
            err.contains("duplicate") && err.contains("category"),
            "validate() must reject duplicate category entries; got: {err:?}"
        );
    }

    #[test]
    fn antigen_parser_rejects_string_literal_as_category() {
        // String literals are NOT accepted as category values; path expressions
        // are required for compile-time discoverability (per expect_antigen_category).
        let tokens: TokenStream =
            r#"name = "x", fingerprint = "item = fn", category = "substrate-alignment""#
                .parse()
                .unwrap();
        let result = syn::parse2::<AntigenArgs>(tokens);
        assert!(
            result.is_err(),
            "string literal category should be rejected; got Ok"
        );
    }

    #[test]
    fn antigen_parser_rejects_integer_as_category() {
        // Non-path non-array expressions (integers, etc.) should be rejected.
        let tokens: TokenStream = r#"name = "x", fingerprint = "item = fn", category = 42"#
            .parse()
            .unwrap();
        let result = syn::parse2::<AntigenArgs>(tokens);
        assert!(
            result.is_err(),
            "integer category should be rejected; got Ok"
        );
    }

    // -------------------------------------------------------------------------
    // #[triage_commit] tests (ADR-026 §Rollback-as-triage primitive)
    // -------------------------------------------------------------------------

    fn valid_triage_commit_tokens() -> TokenStream {
        r#"triage_decision = TriageDecision::Red,
           rollback_target = "abc1234",
           triaged_by = "navigator",
           rationale = "vital metric regression confirmed via #84; rolling back",
           rollback_due_within_minutes = 30"#
            .parse()
            .unwrap()
    }

    #[test]
    fn triage_commit_parser_accepts_canonical_form() {
        let args = syn::parse2::<TriageCommitArgs>(valid_triage_commit_tokens()).unwrap();
        assert_eq!(args.triage_decision, Some(MacroTriageDecision::Red));
        assert_eq!(args.rollback_target.as_deref(), Some("abc1234"));
        assert_eq!(args.triaged_by.as_deref(), Some("navigator"));
        assert_eq!(args.rollback_due_within_minutes, Some(30));
        args.validate().unwrap();
    }

    #[test]
    fn triage_commit_parser_accepts_bare_variant_ident() {
        let tokens: TokenStream = r#"triage_decision = Black,
            rollback_target = "deadbeef",
            triaged_by = "oncall",
            rationale = "system-down: payment processor pod crashlooping",
            rollback_due_within_minutes = 5"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert_eq!(args.triage_decision, Some(MacroTriageDecision::Black));
        args.validate().unwrap();
    }

    #[test]
    fn triage_commit_parser_accepts_all_five_variants() {
        for (variant_text, expected) in [
            ("TriageDecision::Black", MacroTriageDecision::Black),
            ("TriageDecision::Red", MacroTriageDecision::Red),
            ("TriageDecision::Yellow", MacroTriageDecision::Yellow),
            ("TriageDecision::Green", MacroTriageDecision::Green),
            ("TriageDecision::White", MacroTriageDecision::White),
        ] {
            let src = format!(
                r#"triage_decision = {variant_text},
                   rollback_target = "abc1234",
                   triaged_by = "navigator",
                   rationale = "twenty-character-rationale-text-here",
                   rollback_due_within_minutes = 30"#
            );
            let tokens: TokenStream = src.parse().unwrap();
            let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
            assert_eq!(args.triage_decision, Some(expected));
            args.validate().unwrap();
        }
    }

    #[test]
    fn triage_commit_parser_rejects_unknown_variant() {
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Purple,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let result = syn::parse2::<TriageCommitArgs>(tokens);
        assert!(result.is_err(), "unknown variant should be rejected");
    }

    #[test]
    fn triage_commit_parser_rejects_string_literal_triage_decision() {
        let tokens: TokenStream = r#"triage_decision = "red",
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let result = syn::parse2::<TriageCommitArgs>(tokens);
        assert!(
            result.is_err(),
            "string literal triage_decision should be rejected"
        );
    }

    #[test]
    fn triage_commit_validate_rejects_missing_triage_decision() {
        let tokens: TokenStream = r#"rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn triage_commit_validate_rejects_empty_rollback_target() {
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn triage_commit_validate_rejects_empty_triaged_by() {
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn triage_commit_validate_rejects_short_rationale() {
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "too short",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn triage_commit_validate_rejects_zero_minutes() {
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 0"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn triage_commit_parser_rejects_unknown_field() {
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text-here",
            rollback_due_within_minutes = 30,
            bogus = "value""#
            .parse()
            .unwrap();
        let result = syn::parse2::<TriageCommitArgs>(tokens);
        assert!(result.is_err(), "unknown field should be rejected");
    }

    #[test]
    fn macro_triage_decision_as_str_roundtrip() {
        for (variant, expected) in [
            (MacroTriageDecision::Black, "black"),
            (MacroTriageDecision::Red, "red"),
            (MacroTriageDecision::Yellow, "yellow"),
            (MacroTriageDecision::Green, "green"),
            (MacroTriageDecision::White, "white"),
        ] {
            assert_eq!(variant.as_str(), expected);
        }
    }

    // -------------------------------------------------------------------------
    // Adversarial tests for #[triage_commit] (added by adversarial role)
    // -------------------------------------------------------------------------

    #[test]
    fn triage_commit_validate_rationale_exactly_20_chars_passes() {
        // Boundary case: rationale of EXACTLY 20 chars must pass (>= 20, not > 20).
        // "20characterrational!" is exactly 20 chars.
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "20characterrationale",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert_eq!(
            args.rationale.as_deref().map(str::len),
            Some(20),
            "fixture must be exactly 20 chars"
        );
        assert!(
            args.validate().is_ok(),
            "exactly 20 chars should pass rationale validation"
        );
    }

    #[test]
    fn triage_commit_validate_rationale_19_chars_fails() {
        // Just below the 20-char minimum: must fail.
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "19characterrational",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert_eq!(
            args.rationale.as_deref().map(str::len),
            Some(19),
            "fixture must be exactly 19 chars"
        );
        assert!(
            args.validate().is_err(),
            "19-char rationale should fail validation"
        );
    }

    #[test]
    fn triage_commit_validate_absurdly_large_deadline_is_currently_accepted() {
        // ADVERSARIAL FINDING: rollback_due_within_minutes = u32::MAX is accepted.
        // Semantically absurd (5.3 million hours = 600 years). The validate()
        // method only checks for 0; there is no upper cap. This test PINS the
        // current behavior. A future check could warn/error on deadline > 10080
        // (one week in minutes) per operational discipline.
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Yellow,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text",
            rollback_due_within_minutes = 4294967295"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert_eq!(args.rollback_due_within_minutes, Some(4_294_967_295));
        assert!(
            args.validate().is_ok(),
            "u32::MAX deadline currently accepted (no upper cap); this pins that behavior"
        );
    }

    #[test]
    fn triage_commit_validate_whitespace_only_rollback_target_is_rejected() {
        // ATK-VCS-5 fix: rollback_target = "   " (whitespace-only) is now
        // caught by trim().is_empty() check. A whitespace-only string is not
        // a valid git ref.
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "   ",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert_eq!(args.rollback_target.as_deref(), Some("   "));
        let err = args.validate().unwrap_err();
        assert!(
            err.to_string().contains("rollback_target"),
            "error should mention rollback_target field"
        );
    }

    #[test]
    fn triage_commit_validate_whitespace_only_rationale_of_20_chars_should_fail() {
        // ATK-TRIAGE-WHITESPACE-RATIONALE: the rationale length check uses
        // s.len() < 20 — a 20-space string has len == 20 and passes. But 20
        // spaces contains zero meaningful content. The rationale check should
        // also verify that the string is not all-whitespace (trim().is_empty()).
        //
        // This is the same gap as the pre-fix parse_doc_contains: is_empty() vs
        // trim().is_empty(). A blank rationale bypasses the chart-documentation
        // discipline (ADR-026 §Rollback-as-triage: rationale before action, not after).
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "                    ",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert_eq!(
            args.rationale.as_deref().map(str::len),
            Some(20),
            "fixture must be exactly 20 spaces"
        );
        assert!(
            args.validate().is_err(),
            "ATK-TRIAGE-WHITESPACE-RATIONALE: rationale of 20 spaces must fail validation. \
             The 20-char length check (s.len() < 20) passes for '                    ' because \
             len==20. But trim().is_empty() reveals it contains no meaningful content. \
             A blank rationale bypasses chart-documentation discipline. \
             Fix: after the len < 20 check, add trim().is_empty() check — same pattern as \
             rollback_target's whitespace guard."
        );
    }

    #[test]
    fn triage_commit_validate_non_sha_rollback_target_is_currently_accepted() {
        // ADVERSARIAL FINDING: rollback_target accepts arbitrary non-SHA strings.
        // ADR-026 says "commit sha" but no format validation is enforced.
        // "not-a-sha-at-all" is accepted. This is intentional forward-compat
        // (refs like branch names may also be valid rollback targets), but
        // the gap is that completely arbitrary text passes.
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Red,
            rollback_target = "not-a-sha-at-all-just-text",
            triaged_by = "navigator",
            rationale = "twenty-character-rationale-text",
            rollback_due_within_minutes = 30"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(
            args.validate().is_ok(),
            "non-SHA rollback_target currently accepted; pins that no format validation exists"
        );
    }

    #[test]
    fn triage_commit_validate_green_triage_with_tight_deadline_is_accepted() {
        // Green means "no regression detected" — no rollback planned.
        // A tight rollback_due_within_minutes = 1 on a Green triage is
        // semantically odd (no rollback needed but one is mandated within 1 min).
        // The validator does NOT check for this semantic inconsistency.
        let tokens: TokenStream = r#"triage_decision = TriageDecision::Green,
            rollback_target = "abc1234",
            triaged_by = "navigator",
            rationale = "no regression detected in twenty chars",
            rollback_due_within_minutes = 1"#
            .parse()
            .unwrap();
        let args = syn::parse2::<TriageCommitArgs>(tokens).unwrap();
        assert!(
            args.validate().is_ok(),
            "Green triage with tight deadline currently accepted; no semantic inconsistency check"
        );
    }

    // -------------------------------------------------------------------------
    // #[orient] tests (ADR-023 + fixup-orient-dual-signature STEP 2-3 fields)
    // -------------------------------------------------------------------------

    // Helper: an `until` date safely inside the 180d horizon (today + ~90d),
    // computed at test time so the suite never goes stale as the clock advances.
    fn orient_until_within_horizon() -> String {
        (today_utc() + chrono::Duration::days(90))
            .format("%Y-%m-%d")
            .to_string()
    }

    #[test]
    fn orient_parser_bare_form_is_a_validate_error() {
        // Option-A hard break: bare #[orient] is invalid — learning_path + until
        // are REQUIRED (an orient without them is silent deferred non-immunity).
        let tokens: TokenStream = "".parse().unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "bare #[orient] must fail validation (learning_path + until required)"
        );
    }

    #[test]
    fn orient_parser_accepts_canonical_adr023_form() {
        // ADR-023 §Decision spec: #[orient(antigen, learning_path, until)],
        // both fields REQUIRED. learning_path >= 20 chars; until within horizon.
        let until = orient_until_within_horizon();
        let tokens: TokenStream = format!(
            r#"PanickingInDrop,
            learning_path = "Audit Drop impls before alpha tag",
            until = "{until}""#
        )
        .parse()
        .unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(args.antigen.is_some());
        assert_eq!(
            args.learning_path.as_deref(),
            Some("Audit Drop impls before alpha tag")
        );
        assert_eq!(args.until.as_deref(), Some(until.as_str()));
        args.validate().unwrap();
    }

    #[test]
    fn orient_parser_requires_learning_path() {
        let until = orient_until_within_horizon();
        let tokens: TokenStream = format!(r#"until = "{until}""#).parse().unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "until without learning_path must fail validation"
        );
    }

    #[test]
    fn orient_parser_requires_until() {
        let tokens: TokenStream = r#"learning_path = "Audit Drop impls before the alpha tag""#
            .parse()
            .unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "learning_path without until must fail validation"
        );
    }

    #[test]
    fn orient_parser_learning_path_min_20_chars() {
        let until = orient_until_within_horizon();
        let tokens: TokenStream = format!(r#"learning_path = "too short", until = "{until}""#)
            .parse()
            .unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "learning_path under 20 chars must fail (rationale-class minimum)"
        );
    }

    #[test]
    fn orient_parser_rejects_until_beyond_horizon() {
        // until far beyond now + 180d is a parse-time (validate) error.
        let far = (today_utc() + chrono::Duration::days(400))
            .format("%Y-%m-%d")
            .to_string();
        let tokens: TokenStream =
            format!(r#"learning_path = "Audit Drop impls before the alpha tag", until = "{far}""#)
                .parse()
                .unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "until beyond the 180d orientation horizon must fail validation"
        );
    }

    #[test]
    fn orient_parser_rejects_until_in_the_past() {
        // A past `until` date is an already-expired orientation window — it
        // silently represents "we never dealt with this failure-class AND the
        // accountability horizon already passed."  validate() must reject it.
        //
        // ATK: horizon_days = (past_date - today) < 0 — the existing check is
        // `if horizon_days > 180` which is false for negative values, so a past
        // date passes validation silently.  This test FAILS until the check
        // `if horizon_days < 0` is added.
        let yesterday = (today_utc() - chrono::Duration::days(1))
            .format("%Y-%m-%d")
            .to_string();
        let tokens: TokenStream = format!(
            r#"learning_path = "Audit Drop impls before the alpha tag", until = "{yesterday}""#
        )
        .parse()
        .unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-ORIENT-PAST-DATE: until in the past must fail validation — \
             an already-expired orientation period represents hidden unresolved \
             deferred non-immunity with no accountability; got Ok(()) for until={yesterday}"
        );
    }

    #[test]
    fn orient_parser_drift_fields_are_parse_errors() {
        // The pre-restoration drift-form fields (see/adr/attestation_optional)
        // are removed entirely — a hard parse error, not a deprecation warning.
        for drift in [
            r#"see = ["ADR-023"]"#,
            r#"adr = "ADR-023""#,
            "attestation_optional = true",
        ] {
            let tokens: TokenStream = drift.parse().unwrap();
            assert!(
                syn::parse2::<OrientArgs>(tokens).is_err(),
                "drift-form field must be a parse error: {drift}"
            );
        }
    }

    #[test]
    fn orient_parser_rejects_unknown_field() {
        let tokens: TokenStream = r#"bogus = "value""#.parse().unwrap();
        let result = syn::parse2::<OrientArgs>(tokens);
        assert!(result.is_err(), "unknown field should still be rejected");
    }

    // -------------------------------------------------------------------------
    // Recurrent-Emergence Family tests (ADR-024 + scientist HOW-spec cf2a2317)
    // -------------------------------------------------------------------------

    #[test]
    fn itch_parser_accepts_minimal() {
        let tokens: TokenStream =
            r#"name = "drop-panic-rhyme", description = "noticed Drop panics rhyming with unwrap-in-cleanup""#
                .parse()
                .unwrap();
        let args = syn::parse2::<ItchArgs>(tokens).unwrap();
        assert_eq!(args.name.as_deref(), Some("drop-panic-rhyme"));
        args.validate().unwrap();
    }

    #[test]
    fn itch_validate_rejects_missing_name() {
        let tokens: TokenStream = r#"description = "noticed something worth ten chars""#
            .parse()
            .unwrap();
        let args = syn::parse2::<ItchArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn itch_validate_rejects_short_description() {
        let tokens: TokenStream = r#"name = "x", description = "short""#.parse().unwrap();
        let args = syn::parse2::<ItchArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn itch_parser_rejects_unknown_field() {
        let tokens: TokenStream = r#"name = "x", description = "long enough text", bogus = 1"#
            .parse()
            .unwrap();
        assert!(syn::parse2::<ItchArgs>(tokens).is_err());
    }

    #[test]
    fn recurrence_anchor_parser_accepts_canonical() {
        let tokens: TokenStream = r#"MsrvCreep, instances = 3, since = "v0.1.0", rationale = "MSRV crept three times across major bumps""#
            .parse()
            .unwrap();
        let args = syn::parse2::<RecurrenceAnchorArgs>(tokens).unwrap();
        assert!(args.antigen.is_some());
        assert_eq!(args.instances, Some(3));
        args.validate().unwrap();
    }

    #[test]
    fn recurrence_anchor_validate_rejects_zero_instances() {
        let tokens: TokenStream =
            r#"X, instances = 0, since = "v1", rationale = "twenty character rationale here""#
                .parse()
                .unwrap();
        let args = syn::parse2::<RecurrenceAnchorArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn recurrence_anchor_validate_rejects_missing_antigen() {
        let tokens: TokenStream =
            r#"instances = 2, since = "v1", rationale = "twenty character rationale here""#
                .parse()
                .unwrap();
        let args = syn::parse2::<RecurrenceAnchorArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn recurrence_anchor_validate_rejects_short_rationale() {
        let tokens: TokenStream = r#"X, instances = 2, since = "v1", rationale = "too short""#
            .parse()
            .unwrap();
        let args = syn::parse2::<RecurrenceAnchorArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn crystallize_parser_accepts_with_from_itches() {
        let tokens: TokenStream = r#"name = "drop-panic", from_itches = [DropPanicItch, CleanupUnwrapItch], summary = "crystallized from two itches""#
            .parse()
            .unwrap();
        let args = syn::parse2::<CrystallizeArgs>(tokens).unwrap();
        assert_eq!(args.from_itches.len(), 2);
        args.validate().unwrap();
    }

    #[test]
    fn crystallize_validate_rejects_missing_summary() {
        let tokens: TokenStream = r#"name = "x""#.parse().unwrap();
        let args = syn::parse2::<CrystallizeArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn chronic_parser_accepts_canonical() {
        let tokens: TokenStream = r#"FlakeyCiStep, since = "v0.2.0", managed_by = "ci-team""#
            .parse()
            .unwrap();
        let args = syn::parse2::<ChronicArgs>(tokens).unwrap();
        assert!(args.antigen.is_some());
        args.validate().unwrap();
    }

    #[test]
    fn chronic_validate_rejects_missing_since() {
        let tokens: TokenStream = "X".parse().unwrap();
        let args = syn::parse2::<ChronicArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn chronic_validate_rejects_missing_antigen() {
        let tokens: TokenStream = r#"since = "v1""#.parse().unwrap();
        let args = syn::parse2::<ChronicArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn saturate_parser_accepts_minimal() {
        let tokens: TokenStream =
            r#"description = "evidence accumulating toward MSRV-creep anchor""#
                .parse()
                .unwrap();
        let args = syn::parse2::<SaturateArgs>(tokens).unwrap();
        args.validate().unwrap();
    }

    #[test]
    fn saturate_validate_rejects_short_description() {
        let tokens: TokenStream = r#"description = "short""#.parse().unwrap();
        let args = syn::parse2::<SaturateArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn strand_parser_accepts_with_anchored_by() {
        let tokens: TokenStream = r#"name = "vcs-loss-thread", anchored_by = [ForcePushItch, SquashMergeItch], description = "thread of history-loss noticings""#
            .parse()
            .unwrap();
        let args = syn::parse2::<StrandArgs>(tokens).unwrap();
        assert_eq!(args.anchored_by.len(), 2);
        args.validate().unwrap();
    }

    #[test]
    fn strand_validate_rejects_missing_name() {
        let tokens: TokenStream = r#"description = "thread of related noticings here""#
            .parse()
            .unwrap();
        let args = syn::parse2::<StrandArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    // -------------------------------------------------------------------------
    // Mucosal Boundary Family tests (ADR-027 + Amendment 1)
    // -------------------------------------------------------------------------

    #[test]
    fn mucosal_parser_accepts_canonical() {
        let tokens: TokenStream =
            r#"kind = MucosalKind::UserInput, rationale = "public comment form; XSS sanitized at render""#
                .parse()
                .unwrap();
        let args = syn::parse2::<MucosalArgs>(tokens).unwrap();
        assert_eq!(args.kind, Some(MacroMucosalKind::UserInput));
        args.validate().unwrap();
    }

    #[test]
    fn mucosal_parser_accepts_bare_variant() {
        let tokens: TokenStream =
            r#"kind = DatabaseQuery, rationale = "parameterized queries only at this layer""#
                .parse()
                .unwrap();
        let args = syn::parse2::<MucosalArgs>(tokens).unwrap();
        assert_eq!(args.kind, Some(MacroMucosalKind::DatabaseQuery));
        args.validate().unwrap();
    }

    #[test]
    fn mucosal_validate_rejects_missing_kind() {
        let tokens: TokenStream = r#"rationale = "twenty character rationale here padding""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn mucosal_validate_rejects_short_rationale() {
        let tokens: TokenStream = r#"kind = MucosalKind::UserInput, rationale = "short""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn mucosal_parser_rejects_removed_pr_boundary_variant() {
        // PrBoundary was removed in ADR-027 Amendment 1.
        let tokens: TokenStream =
            r#"kind = MucosalKind::PrBoundary, rationale = "twenty character rationale text""#
                .parse()
                .unwrap();
        assert!(syn::parse2::<MucosalArgs>(tokens).is_err());
    }

    #[test]
    fn mucosal_parser_rejects_string_literal_kind() {
        let tokens: TokenStream =
            r#"kind = "user-input", rationale = "twenty character rationale text""#
                .parse()
                .unwrap();
        assert!(syn::parse2::<MucosalArgs>(tokens).is_err());
    }

    #[test]
    fn mucosal_delegate_parser_accepts_canonical() {
        let tokens: TokenStream = r#"boundary = MucosalKind::UserInput, handled_by = crate::sanitize::user_input, rationale = "delegated to central sanitizer module""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalDelegateArgs>(tokens).unwrap();
        assert_eq!(args.boundary, Some(MacroMucosalKind::UserInput));
        assert!(args.handled_by.is_some());
        args.validate().unwrap();
    }

    #[test]
    fn mucosal_delegate_validate_rejects_missing_handled_by() {
        let tokens: TokenStream =
            r#"boundary = MucosalKind::UserInput, rationale = "twenty character rationale text""#
                .parse()
                .unwrap();
        let args = syn::parse2::<MucosalDelegateArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn mucosal_delegate_rejects_string_handled_by() {
        // handled_by is a path expression, not a string (Amendment 1 Change 4).
        // A string literal where a syn::Path is expected fails to parse.
        let tokens: TokenStream = r#"boundary = MucosalKind::UserInput, handled_by = "sanitize_fn", rationale = "twenty character rationale text""#
            .parse()
            .unwrap();
        assert!(
            syn::parse2::<MucosalDelegateArgs>(tokens).is_err(),
            "string-literal handled_by must be rejected (path expression required)"
        );
    }

    #[test]
    fn mucosal_tolerant_parser_accepts_canonical() {
        let tokens: TokenStream = r#"kind = MucosalKind::UserInput, rationale = "public firehose intake endpoint accepts anonymous submissions by design", accepts = "anonymous JSON payloads up to 64KB""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalTolerantArgs>(tokens).unwrap();
        assert_eq!(args.kind, Some(MacroMucosalKind::UserInput));
        args.validate().unwrap();
    }

    #[test]
    fn mucosal_tolerant_validate_rejects_rationale_under_40() {
        // Tolerance floor is ≥40 (vs #[mucosal]'s ≥20).
        let tokens: TokenStream = r#"kind = MucosalKind::UserInput, rationale = "twenty-five char rationale", accepts = "anything""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalTolerantArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "25-char rationale must fail the ≥40 tolerance floor"
        );
    }

    #[test]
    fn mucosal_tolerant_validate_rejects_empty_accepts() {
        let tokens: TokenStream = r#"kind = MucosalKind::UserInput, rationale = "this rationale is definitely longer than forty characters", accepts = "   ""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalTolerantArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn mucosal_tolerant_validate_rejects_missing_accepts() {
        let tokens: TokenStream = r#"kind = MucosalKind::UserInput, rationale = "this rationale is definitely longer than forty characters""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalTolerantArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    // ---- GeneratesArgs (ADR-014) ----

    #[test]
    fn generates_parser_accepts_canonical() {
        let tokens: TokenStream =
            r#"PanickingInDrop, rationale = "the emitted Drop impl may panic; verify inner types""#
                .parse()
                .unwrap();
        let args = syn::parse2::<GeneratesArgs>(tokens).unwrap();
        assert!(args.validate().is_ok());
        assert_eq!(args.antigen_name(), "PanickingInDrop");
    }

    #[test]
    fn generates_parser_uses_last_path_segment_for_name() {
        let tokens: TokenStream =
            r#"antigen::stdlib::PanickingInDrop, rationale = "qualified path resolves to last seg""#
                .parse()
                .unwrap();
        let args = syn::parse2::<GeneratesArgs>(tokens).unwrap();
        assert_eq!(args.antigen_name(), "PanickingInDrop");
    }

    #[test]
    fn generates_validate_rejects_missing_rationale() {
        let tokens: TokenStream = "PanickingInDrop".parse().unwrap();
        let args = syn::parse2::<GeneratesArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "a generation claim without rationale is not a claim"
        );
    }

    #[test]
    fn generates_validate_rejects_empty_rationale() {
        let tokens: TokenStream = r#"PanickingInDrop, rationale = """#.parse().unwrap();
        let args = syn::parse2::<GeneratesArgs>(tokens).unwrap();
        assert!(args.validate().is_err(), "empty rationale must be rejected");
    }

    #[test]
    fn generates_validate_rejects_empty_optional_fields() {
        let tokens: TokenStream = r#"PanickingInDrop, rationale = "valid", witness_template = """#
            .parse()
            .unwrap();
        let args = syn::parse2::<GeneratesArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "an empty witness_template indicates user error (mirror until=\"\" rejection)"
        );
    }

    #[test]
    fn generates_parser_rejects_unknown_field() {
        let tokens: TokenStream = r#"PanickingInDrop, rationale = "valid", bogus_field = "x""#
            .parse()
            .unwrap();
        assert!(
            syn::parse2::<GeneratesArgs>(tokens).is_err(),
            "unknown field must be a parse error (strict macro-side surface)"
        );
    }

    #[test]
    fn generates_parser_accepts_v2_optional_fields() {
        let tokens: TokenStream = r#"PanickingInDrop, rationale = "valid", witness_template = "tests/drop_panic.rs", if_attr_present = "skip_drop""#
            .parse()
            .unwrap();
        let args = syn::parse2::<GeneratesArgs>(tokens).unwrap();
        assert!(args.validate().is_ok());
        assert_eq!(
            args.witness_template.as_deref(),
            Some("tests/drop_panic.rs")
        );
        assert_eq!(args.if_attr_present.as_deref(), Some("skip_drop"));
    }

    #[test]
    fn mucosal_tolerant_accepts_optional_reviewed_by_and_until() {
        let tokens: TokenStream = r#"kind = MucosalKind::ApiRequest, rationale = "internal admin endpoint behind VPN; trusted-network assumption documented", accepts = "admin-panel form posts", reviewed_by = "security-team", until = "2026-12-31""#
            .parse()
            .unwrap();
        let args = syn::parse2::<MucosalTolerantArgs>(tokens).unwrap();
        assert_eq!(args.reviewed_by.as_deref(), Some("security-team"));
        assert_eq!(args.until.as_deref(), Some("2026-12-31"));
        args.validate().unwrap();
    }

    // -------------------------------------------------------------------------
    // Adversarial tests for #[immunosuppress] and #[anergy] — past until date
    // -------------------------------------------------------------------------

    #[test]
    fn immunosuppress_validate_rejects_until_in_the_past() {
        // ATK-IMMUNOSUPPRESS-PAST-DATE: #[immunosuppress] with `until` in the
        // past should fail validation — the suppression window has expired.
        //
        // FIXED: validate() now rejects past dates (duration_days < 0 check added).
        let yesterday = (today_utc() - chrono::Duration::days(1))
            .format("%Y-%m-%d")
            .to_string();
        let tokens: TokenStream = format!(
            r#"PanickingInDrop,
            rationale = "Suppressing while we wait for proptest infrastructure build",
            until = "{yesterday}""#
        )
        .parse()
        .unwrap();
        let args = syn::parse2::<ImmunosuppressArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-IMMUNOSUPPRESS-PAST-DATE: #[immunosuppress] with until in the past must fail \
             validation — expired suppression is silent check-disabling with no accountability. \
             Got Ok(()) for until={yesterday}. \
             Fix: add duration_days < 0 check in ImmunosuppressArgs::validate() at ~line 856."
        );
    }

    #[test]
    fn poxparty_validate_rejects_until_in_the_past() {
        // ATK-POXPARTY-PAST-DATE: #[poxparty] with `until` in the past should fail
        // validation — an expired pox-party window means a controlled-exposure exercise
        // is still referenced in code but its deadline has passed. Silent expired
        // poxparty is the same class as expired immunosuppress and anergy.
        //
        // FIXED: validate() now rejects past dates (parse_iso_date() + horizon_days < 0 check added).
        let yesterday = (today_utc() - chrono::Duration::days(1))
            .format("%Y-%m-%d")
            .to_string();
        let tokens: TokenStream = format!(
            r#"PanickingInDrop,
            exercise_type = "Trigger deliberate Drop panic and measure detection lag",
            until = "{yesterday}""#
        )
        .parse()
        .unwrap();
        let args = syn::parse2::<PoxpartyArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-POXPARTY-PAST-DATE: #[poxparty] with until in the past must fail validation — \
             an expired pox-party exercise represents stale controlled-exposure with no accountability. \
             Got Ok(()) for until={yesterday}. \
             Fix: add parse_iso_date() + horizon_days < 0 check to PoxpartyArgs::validate()."
        );
    }

    #[test]
    fn anergy_validate_rejects_until_in_the_past() {
        // ATK-ANERGY-PAST-DATE: #[anergy] with `until` in the past should fail
        // validation — an already-expired anergy window means the suppression
        // should have been re-evaluated but wasn't. Silent expired anergy is
        // worse than orient: it silently suppresses checks for a failure-class
        // on an item where the anergy contract has lapsed.
        //
        // FIXED: validate() now rejects past dates (parse_iso_date() + horizon_days < 0 check added).
        let yesterday = (today_utc() - chrono::Duration::days(1))
            .format("%Y-%m-%d")
            .to_string();
        let tokens: TokenStream = format!(
            r#"PanickingInDrop,
            reason = "Suppressing until we audit all Drop impls in the codebase",
            until = "{yesterday}""#
        )
        .parse()
        .unwrap();
        let args = syn::parse2::<AnergyArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-ANERGY-PAST-DATE: #[anergy] with until in the past must fail validation — \
             an expired anergy window represents silent check-suppression with no accountability. \
             Got Ok(()) for until={yesterday}. \
             Fix: add parse_iso_date() + horizon_days < 0 check to AnergyArgs::validate() \
             parallel to OrientArgs commit 53d2bab."
        );
    }

    #[test]
    fn anergy_validate_rejects_invalid_date_format() {
        // ATK-ANERGY-INVALID-DATE: #[anergy] with a syntactically invalid `until`
        // date silently passes validation. When parse_iso_date returns Err(()),
        // the `if let Ok(...)` arm is not entered and no error is produced.
        //
        // A user who writes `until = "not-a-date"` or `until = "v2.0"` gets a
        // silently accepted macro — the anergy window is unbounded (no parseable
        // date means no past-date check, no expiry). This is worse than a past date.
        //
        // validate() must reject unparseable `until` values explicitly.
        let tokens: TokenStream =
            r#"PanickingInDrop, reason = "Suppressing until we audit all Drop impls in the codebase", until = "not-a-date""#
                .parse()
                .unwrap();
        let args = syn::parse2::<AnergyArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-ANERGY-INVALID-DATE: #[anergy] with until = 'not-a-date' must fail validation. \
             parse_iso_date returns Err(()), so the if-let-Ok arm is skipped — no error returned. \
             An unparseable until date is an unbounded anergy window (no expiry ever fires). \
             Fix: after the parse_iso_date call, also return Err if parsing FAILED — \
             invalid dates should be rejected, not silently accepted."
        );
    }

    #[test]
    fn immunosuppress_validate_rejects_invalid_date_format() {
        // ATK-IMMUNOSUPPRESS-INVALID-DATE: same gap as anergy — unparseable `until`
        // silently passes. ImmunosuppressArgs::validate() uses the same if-let-Ok pattern.
        let tokens: TokenStream =
            r#"PanickingInDrop, rationale = "Suppressing this check until we audit all Drop impls", until = "2999-13-01""#
                .parse()
                .unwrap();
        let args = syn::parse2::<ImmunosuppressArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-IMMUNOSUPPRESS-INVALID-DATE: #[immunosuppress] with until = '2999-13-01' \
             (invalid month 13) must fail validation. parse_iso_date returns Err(()), \
             so the if-let-Ok arm is skipped — no error returned. \
             An unparseable until date is an unbounded suppression window. \
             Fix: treat parse_iso_date failure as a validation error."
        );
    }

    #[test]
    fn poxparty_validate_rejects_invalid_date_format() {
        // ATK-POXPARTY-INVALID-DATE: same gap as anergy/immunosuppress. PoxpartyArgs
        // uses the same if-let-Ok(parse_iso_date) pattern — invalid dates silently pass.
        let tokens: TokenStream =
            r#"PanickingInDrop, exercise_type = "Trigger deliberate Drop panic and measure detection lag", until = "v2.0-release""#
                .parse()
                .unwrap();
        let args = syn::parse2::<PoxpartyArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "ATK-POXPARTY-INVALID-DATE: #[poxparty] with until = 'v2.0-release' \
             must fail validation. parse_iso_date returns Err(()), so the if-let-Ok \
             arm is skipped — no error returned. A version tag as until date creates \
             an unbounded poxparty window that never expires. \
             Fix: treat parse_iso_date failure as a validation error."
        );
    }

    // -------------------------------------------------------------------------
    // ATK-WHITESPACE-RATIONALE: deferred-defense macros (anergy/immunosuppress/
    // poxparty/orient) have the same whitespace-stuffing gap as triage_commit did
    // (which was fixed at line 1640). The len() < 20 check passes for all-space
    // strings. These tests will FAIL until the trim().is_empty() guards are added
    // to the four deferred-defense validate() methods.
    //
    // The systemic root: ADR-023 loudness-as-discipline implemented as min-length
    // but whitespace-stuffing was not considered. triage_commit got fixed first
    // (via the hook in response to adversarial's failing test); these four remain.
    // -------------------------------------------------------------------------

    #[test]
    fn anergy_validate_rejects_whitespace_only_reason_of_20_chars() {
        let tokens: TokenStream =
            r#"PanickingInDrop, reason = "                    ", until = "2099-12-31""#
                .parse()
                .unwrap();
        let args = syn::parse2::<AnergyArgs>(tokens).unwrap();
        assert_eq!(args.reason.as_deref().map(str::len), Some(20));
        assert!(
            args.validate().is_err(),
            "ATK-WHITESPACE-RATIONALE: #[anergy] reason of 20 spaces must fail validation. \
             AnergyArgs::validate() line 643 uses r.len() < 20 but not trim().is_empty(). \
             Fix: add 'Some(r) if r.trim().is_empty() => Err(...)' arm to the reason match, \
             parallel to triage_commit's fix at line 1640."
        );
    }

    #[test]
    fn immunosuppress_validate_rejects_whitespace_only_rationale_of_20_chars() {
        let tokens: TokenStream =
            r#"PanickingInDrop, rationale = "                    ", until = "2099-12-31""#
                .parse()
                .unwrap();
        let args = syn::parse2::<ImmunosuppressArgs>(tokens).unwrap();
        assert_eq!(args.rationale.as_deref().map(str::len), Some(20));
        assert!(
            args.validate().is_err(),
            "ATK-WHITESPACE-RATIONALE: #[immunosuppress] rationale of 20 spaces must fail. \
             ImmunosuppressArgs::validate() line 843 uses r.len() < 20 without trim(). \
             Fix: add trim().is_empty() arm parallel to triage_commit fix at line 1640."
        );
    }

    #[test]
    fn poxparty_validate_rejects_whitespace_only_exercise_type_of_20_chars() {
        let tokens: TokenStream =
            r#"PanickingInDrop, exercise_type = "                    ", until = "2099-12-31""#
                .parse()
                .unwrap();
        let args = syn::parse2::<PoxpartyArgs>(tokens).unwrap();
        assert_eq!(args.exercise_type.as_deref().map(str::len), Some(20));
        assert!(
            args.validate().is_err(),
            "ATK-WHITESPACE-RATIONALE: #[poxparty] exercise_type of 20 spaces must fail. \
             PoxpartyArgs::validate() line 1062 uses et.len() < 20 without trim(). \
             Fix: add trim().is_empty() arm parallel to triage_commit fix at line 1640."
        );
    }

    #[test]
    fn orient_validate_rejects_whitespace_only_learning_path_of_20_chars() {
        let until = (today_utc() + chrono::Duration::days(90))
            .format("%Y-%m-%d")
            .to_string();
        let src = format!(
            r#"PanickingInDrop, learning_path = "                    ", until = "{until}""#
        );
        let tokens: TokenStream = src.parse().unwrap();
        let args = syn::parse2::<OrientArgs>(tokens).unwrap();
        assert_eq!(args.learning_path.as_deref().map(str::len), Some(20));
        assert!(
            args.validate().is_err(),
            "ATK-WHITESPACE-RATIONALE: #[orient] learning_path of 20 spaces must fail. \
             OrientArgs::validate() line 1269 uses p.len() < 20 without trim(). \
             Fix: add trim().is_empty() arm parallel to triage_commit fix at line 1640."
        );
    }
}

// ============================================================================
// Property tests (W1) — proptest invariants over the macro-side parser surface.
//
// These proptests are the macro-side half of the cross-parser equivalence
// story. The matching scan-side proptests live in
// `antigen/src/scan.rs::tests::scan_parser_props`. The two test modules share:
//
//   - the same `valid_*` strategies (literal-copied; if you change one,
//     change the other in the same commit); and
//   - the same expected-outcome assertions for inputs both parsers accept.
//
// Because `proc-macro = true` crates cannot be linked as libraries, the two
// parsers cannot be invoked from a single test binary. The fixture-table
// approach in the same file (`ANTIGEN_PARSER_FIXTURES`) provides
// by-construction cross-parser checks at six concrete points; the proptest
// strategies fuzz the input space around the same grammar shape from each
// side independently. Drift between the two manifests as one side accepting
// inputs the other rejects — caught here on the macro side, caught there on
// the scan side.
//
// Cross-parser invariants asserted (per ADR-001 Amendment 1 C5
// drift-detection-at-scan-time, and the ATK-001-2 lesson):
//
//   I1 — equivalence-on-intersection: for any input the macro side accepts,
//        the scan side accepts and produces equivalent semantic content for
//        name/fingerprint/family/summary. (Macro side checks "I accept";
//        scan side checks "I accept and the result matches what I'd render
//        back into the macro grammar.")
//
//   I2 — strict-superset-of-rejection: the macro side strictly rejects more
//        than the scan side (asymmetric by design — see scan.rs comments on
//        unknown-field tolerance and missing-required-field tolerance).
//        Rejecting more is fine; accepting where the macro rejects is not.
//
// Adversarial input shapes worth fuzzing (per W1's adversarial-pass plan):
// Unicode in names, nested macros / inner-quoted strings in fingerprints,
// extremely long string literals, malformed array literals, multi-line
// rustfmt output, all-whitespace edge cases, kebab-case boundary inputs.
// ============================================================================

#[cfg(test)]
mod parser_props {
    use super::*;
    use proc_macro2::TokenStream;
    use proptest::prelude::*;

    // Rust reserved words that cannot appear as path segments. Generated by
    // strategy `[a-z][a-z_0-9]{0,8}` without this filter, causing syn to reject
    // inputs that are otherwise syntactically correct `#[immune]` bodies.
    const RUST_KEYWORDS: &[&str] = &[
        "as", "async", "await", "box", "break", "const", "continue", "crate", "do", "dyn", "else",
        "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "macro",
        "match", "mod", "move", "mut", "pub", "ref", "return", "self", "static", "struct", "super",
        "trait", "true", "type", "union", "unsafe", "use", "where", "while", "yield", "abstract",
        "become", "final", "override", "priv", "try",
    ];

    // --- Strategies (shared shape with antigen/src/scan.rs::tests) ---

    /// Generate a kebab-case name: `[a-z][a-z0-9]*(-[a-z0-9]+)*`. The
    /// substrate's `is_kebab_case` rule rejects leading/trailing hyphens
    /// and consecutive double-hyphens; this strategy generates only legal
    /// shapes so we can lock the validate-accepts side. (Rejection of
    /// non-kebab is tested by the existing fixture tests.)
    fn valid_kebab() -> impl Strategy<Value = String> {
        // 1-4 segments, each 1-8 chars from [a-z0-9] and starting with [a-z].
        proptest::collection::vec(
            (
                proptest::char::range('a', 'z'),
                proptest::collection::vec(
                    prop_oneof![
                        proptest::char::range('a', 'z'),
                        proptest::char::range('0', '9')
                    ],
                    0..8usize,
                ),
            )
                .prop_map(|(first, rest)| {
                    let mut s = String::with_capacity(rest.len() + 1);
                    s.push(first);
                    for c in rest {
                        s.push(c);
                    }
                    s
                }),
            1..5usize,
        )
        .prop_map(|segments| segments.join("-"))
    }

    /// Generate a non-empty string suitable for use as a fingerprint /
    /// summary / family content. Avoids characters that would close the
    /// outer `"..."` literal at the token level (since these end up
    /// embedded in a Rust source-text string literal we synthesize). We
    /// allow inner content that includes escaped quotes via the
    /// fixture-style escape `\"` — the serialization layer handles
    /// escaping.
    fn valid_text(max_len: usize) -> impl Strategy<Value = String> {
        // Keep characters in a printable-ASCII range that can be safely
        // round-tripped through `Debug` formatting (which is how we emit
        // string literals into the synthetic source). Excludes: backslash
        // (escape complications), null bytes, raw quotes (the encoder will
        // escape them anyway, but we keep the strategy simple here).
        proptest::collection::vec(
            prop_oneof![
                proptest::char::range(' ', '~').prop_filter("excluded chars", |c| {
                    *c != '\\' && *c != '"' && *c != '\0'
                }),
            ],
            1..=max_len,
        )
        .prop_map(|chars| chars.into_iter().collect())
    }

    /// Encode a Rust string literal: wrap in double-quotes and escape
    /// inner quotes/backslashes via `format!("{:?}", s)`, which is the
    /// canonical Debug-encoding for `String` and matches what
    /// `syn::LitStr` accepts/produces.
    fn lit(s: &str) -> String {
        format!("{s:?}")
    }

    /// Render a `(name, fingerprint, family, summary)` tuple as the
    /// canonical `#[antigen(...)]` body in name-first order.
    fn render_antigen_body(
        name: &str,
        fingerprint: &str,
        family: Option<&str>,
        summary: Option<&str>,
    ) -> String {
        let mut parts = vec![
            format!("name = {}", lit(name)),
            format!("fingerprint = {}", lit(fingerprint)),
        ];
        if let Some(f) = family {
            parts.push(format!("family = {}", lit(f)));
        }
        if let Some(s) = summary {
            parts.push(format!("summary = {}", lit(s)));
        }
        parts.join(", ")
    }

    proptest! {
        // P1 — round-trip: any valid set of args parses, and re-rendering it
        // produces a body that re-parses to the same args.
        #[test]
        fn antigen_parser_round_trip(
            name in valid_kebab(),
            fingerprint in valid_text(64),
            family in proptest::option::of(valid_text(32)),
            summary in proptest::option::of(valid_text(64)),
        ) {
            let body = render_antigen_body(&name, &fingerprint, family.as_deref(), summary.as_deref());
            let tokens: TokenStream = body.parse().expect("body must tokenize");
            let args = syn::parse2::<AntigenArgs>(tokens).expect("body must parse");
            prop_assert_eq!(&args.name, &name);
            prop_assert_eq!(args.fingerprint.as_deref(), Some(fingerprint.as_str()));
            prop_assert_eq!(args.family.as_deref(), family.as_deref());
            prop_assert_eq!(args.summary.as_deref(), summary.as_deref());
            // W6a: validate() now invokes antigen_fingerprint::Fingerprint::parse,
            // which rejects arbitrary text. The round-trip property is about
            // parse-render-parse idempotency for the value fields, not about
            // DSL validity; drop the validate() assertion here. A separate
            // proptest with a valid_dsl() strategy is future work.

            // Round-trip: re-render the parsed args and re-parse. Result
            // must be identical (idempotency under the canonical rendering).
            let re_rendered = render_antigen_body(&args.name, args.fingerprint.as_deref().unwrap_or(""), args.family.as_deref(), args.summary.as_deref());
            let re_tokens: TokenStream = re_rendered.parse().expect("re-rendered body must tokenize");
            let args2 = syn::parse2::<AntigenArgs>(re_tokens).expect("re-rendered body must parse");
            prop_assert_eq!(&args.name, &args2.name);
            prop_assert_eq!(&args.fingerprint, &args2.fingerprint);
            prop_assert_eq!(args.family, args2.family);
            prop_assert_eq!(args.summary, args2.summary);
        }

        // P2 — order-invariance: shuffling the order of valid fields does
        // not change the parsed result.
        #[test]
        fn antigen_parser_order_invariant(
            name in valid_kebab(),
            fingerprint in valid_text(48),
            family in valid_text(24),
            summary in valid_text(48),
        ) {
            // Two orderings: name-first (canonical) and reversed.
            let canonical = format!(
                "name = {}, fingerprint = {}, family = {}, summary = {}",
                lit(&name), lit(&fingerprint), lit(&family), lit(&summary),
            );
            let reversed = format!(
                "summary = {}, family = {}, fingerprint = {}, name = {}",
                lit(&summary), lit(&family), lit(&fingerprint), lit(&name),
            );
            let a: AntigenArgs = syn::parse2(canonical.parse::<TokenStream>().unwrap()).unwrap();
            let b: AntigenArgs = syn::parse2(reversed.parse::<TokenStream>().unwrap()).unwrap();
            prop_assert_eq!(&a.name, &b.name);
            prop_assert_eq!(&a.fingerprint, &b.fingerprint);
            prop_assert_eq!(&a.family, &b.family);
            prop_assert_eq!(&a.summary, &b.summary);
        }

        // P3 — kebab-case validator accepts every kebab-case string our
        // generator produces. (Negative shapes are tested by the fixture
        // tests — `validate_rejects_*` — already.)
        #[test]
        fn is_kebab_case_accepts_generator(name in valid_kebab()) {
            prop_assert!(is_kebab_case(&name), "is_kebab_case rejected generator output: {name:?}");
        }

        // P4 — required-field enforcement: any input missing `name` is
        // rejected with an error mentioning `name`. Same for `fingerprint`.
        #[test]
        fn antigen_parser_requires_name(
            fingerprint in valid_text(32),
            family in proptest::option::of(valid_text(16)),
        ) {
            let mut parts = vec![format!("fingerprint = {}", lit(&fingerprint))];
            if let Some(f) = &family {
                parts.push(format!("family = {}", lit(f)));
            }
            let body = parts.join(", ");
            let tokens: TokenStream = body.parse().expect("body tokenizes");
            let result = syn::parse2::<AntigenArgs>(tokens);
            prop_assert!(result.is_err(), "expected parser to reject input missing `name`: {body:?}");
            let err = result.unwrap_err().to_string();
            prop_assert!(err.contains("name"), "error must mention `name`, got: {err:?}");
        }

        // ADR-009 Amendment 1: a missing `fingerprint` is no longer rejected —
        // it parses as a verify-only antigen (fingerprint: None) whose detection
        // is external-substrate. The invariant flipped: missing-fingerprint ⇒
        // parses + validates, with fingerprint None.
        #[test]
        fn antigen_parser_accepts_missing_fingerprint_verify_only(
            name in valid_kebab(),
            family in proptest::option::of(valid_text(16)),
        ) {
            let mut parts = vec![format!("name = {}", lit(&name))];
            if let Some(f) = &family {
                parts.push(format!("family = {}", lit(f)));
            }
            let body = parts.join(", ");
            let tokens: TokenStream = body.parse().expect("body tokenizes");
            let args = syn::parse2::<AntigenArgs>(tokens)
                .expect("a fingerprint-less #[antigen] is a valid verify-only declaration");
            prop_assert!(args.fingerprint.is_none(), "absent fingerprint must be None");
            prop_assert!(args.validate().is_ok(), "verify-only antigen must validate");
        }

        // P5 — unknown-field rejection (macro-side strictness; the scan
        // side tolerates these — that's the documented asymmetry).
        #[test]
        fn antigen_parser_rejects_unknown_field(
            name in valid_kebab(),
            fingerprint in valid_text(32),
            // Generate an unknown field name that doesn't collide with any
            // of the known field names.
            unknown in "[a-z][a-z_]{2,12}".prop_filter(
                "must not collide with known fields or Rust keywords",
                |s| {
                    !matches!(s.as_str(), "name" | "fingerprint" | "family" | "summary" | "references")
                        && !RUST_KEYWORDS.contains(&s.as_str())
                },
            ),
        ) {
            let body = format!(
                "name = {}, fingerprint = {}, {} = \"x\"",
                lit(&name), lit(&fingerprint), unknown,
            );
            let tokens: TokenStream = body.parse().expect("body tokenizes");
            let result = syn::parse2::<AntigenArgs>(tokens);
            prop_assert!(result.is_err(), "expected unknown field rejection for: {body:?}");
            let err = result.unwrap_err().to_string();
            prop_assert!(
                err.contains("unknown") && err.contains(&unknown),
                "error must name the unknown field. got: {err:?}",
            );
        }

        // P6 — references array round-trips: any list of valid strings in
        // the references array parses without error and we record them.
        #[test]
        fn antigen_parser_accepts_references_array(
            name in valid_kebab(),
            fingerprint in valid_text(32),
            refs in proptest::collection::vec(valid_text(24), 0..6usize),
        ) {
            let refs_lit: Vec<String> = refs.iter().map(|s| lit(s)).collect();
            let body = format!(
                "name = {}, fingerprint = {}, references = [{}]",
                lit(&name), lit(&fingerprint), refs_lit.join(", "),
            );
            let tokens: TokenStream = body.parse().expect("body tokenizes");
            let args = syn::parse2::<AntigenArgs>(tokens).expect("body parses");
            prop_assert_eq!(&args.references, &refs);
        }

        // P7 — ImmuneArgs: any valid (path, witness-path) pair parses
        // and validate() accepts.
        //
        // Strategy note: `[a-z][a-z_0-9]{0,8}` can generate Rust reserved
        // words (fn, if, in, let, mod, …). syn rejects reserved words as
        // path segments, so we filter them out. The filter does not weaken the
        // property: the invariant is about VALID witness paths, and keywords
        // are not valid path segments.
        #[test]
        fn immune_parser_accepts_witness(
            antigen in "[A-Z][A-Za-z0-9]{0,16}",
            witness_segments in proptest::collection::vec(
                "[a-z][a-z_0-9]{0,8}".prop_filter("must not be a Rust keyword", |s| {
                    !RUST_KEYWORDS.contains(&s.as_str())
                }),
                1..4usize,
            ),
        ) {
            let witness = witness_segments.join("::");
            let body = format!("{antigen}, witness = {witness}");
            let tokens: TokenStream = body.parse().expect("body tokenizes");
            let args = syn::parse2::<ImmuneArgs>(tokens).expect("body parses");
            prop_assert!(args.witness.is_some());
            prop_assert!(args.validate().is_ok());
        }

        // P8 — ImmuneArgs: missing witness => validate() errors with
        // the witness-required message. (The Parse impl accepts a bare
        // antigen path; validate() is the trust-boundary check.)
        #[test]
        fn immune_parser_validate_rejects_missing_witness(
            antigen in "[A-Z][A-Za-z0-9]{0,16}",
        ) {
            let tokens: TokenStream = antigen.parse().expect("antigen tokenizes");
            let args = syn::parse2::<ImmuneArgs>(tokens).expect("bare path parses");
            prop_assert!(args.witness.is_none());
            let err = args.validate().unwrap_err().to_string();
            prop_assert!(err.contains("witness"), "validate must mention `witness`, got: {err:?}");
        }
    }

    // ========================================================================
    // DefendedByArgs (ADR-029) — code-tier witness registration
    // ========================================================================

    #[test]
    fn defended_by_parses_bare_antigen_path() {
        let tokens: proc_macro2::TokenStream = "ParallelStateTrackersDiverge".parse().unwrap();
        let args = syn::parse2::<DefendedByArgs>(tokens).expect("bare path parses");
        assert_eq!(
            args.antigen.segments.last().unwrap().ident.to_string(),
            "ParallelStateTrackersDiverge"
        );
    }

    #[test]
    fn defended_by_parses_qualified_path() {
        let tokens: proc_macro2::TokenStream = "crate::antigens::DropPanicClass".parse().unwrap();
        let args = syn::parse2::<DefendedByArgs>(tokens).expect("qualified path parses");
        assert_eq!(
            args.antigen.segments.last().unwrap().ident.to_string(),
            "DropPanicClass"
        );
    }

    #[test]
    fn defended_by_rejects_trailing_witness_args() {
        // The old #[immune] shape (`X, witness = fn`) must NOT silently parse:
        // #[defended_by] carries only the failure-class. Site-attached evidence
        // folds into #[presents] (ADR-029 R5). Reject loudly with guidance.
        let tokens: proc_macro2::TokenStream =
            "DropPanicClass, witness = some_test".parse().unwrap();
        let err = syn::parse2::<DefendedByArgs>(tokens)
            .expect_err("trailing args must be rejected")
            .to_string();
        assert!(
            err.contains("exactly one positional argument"),
            "error must explain the single-arg shape; got: {err:?}"
        );
    }

    #[test]
    fn defended_by_rejects_empty() {
        // A bare `#[defended_by]` (no antigen) is a witness for nothing.
        let tokens = proc_macro2::TokenStream::new();
        assert!(
            syn::parse2::<DefendedByArgs>(tokens).is_err(),
            "empty #[defended_by] body must be rejected"
        );
    }

    // ========================================================================
    // PresentsArgs (ADR-029) — site-attached evidence folding
    // ========================================================================

    #[test]
    fn presents_parses_bare_antigen_still() {
        // Back-compat: the v0.1 single-positional form still parses.
        let tokens: proc_macro2::TokenStream = "PanickingInDrop".parse().unwrap();
        let args = syn::parse2::<PresentsArgs>(tokens).expect("bare presents parses");
        assert!(args.requires.is_none());
        assert!(args.proof.is_none());
        assert!(args.validate().is_ok());
    }

    #[test]
    fn presents_parses_requires_predicate() {
        // ADR-029: substrate-tier evidence folds onto #[presents].
        let tokens: proc_macro2::TokenStream =
            r#"UnpinnedDependency, requires = ratified_doc(path = "docs/x.md")"#
                .parse()
                .unwrap();
        let args = syn::parse2::<PresentsArgs>(tokens).expect("requires folds in");
        assert!(args.requires.is_some());
        assert!(args.validate().is_ok());
        // The emitted marker JSON must be present for scan discovery.
        assert!(args.requires_json().is_some());
    }

    #[test]
    fn presents_parses_proof_expression() {
        // ADR-029: phantom-tier evidence folds onto #[presents].
        let tokens: proc_macro2::TokenStream =
            "DropPanicClass, proof = NonPanickingProof::<T>::verified"
                .parse()
                .unwrap();
        let args = syn::parse2::<PresentsArgs>(tokens).expect("proof folds in");
        assert!(args.proof.is_some());
        // proof= is recognized structurally by audit; no requires marker.
        assert!(args.requires_json().is_none());
    }

    #[test]
    fn presents_rejects_unknown_field() {
        // A code-tier `witness =` on #[presents] is a misuse — it belongs on
        // #[defended_by]. Reject with guidance (R5 discriminator).
        let body = "DropPanicClass, witness = some_test";
        let tokens: proc_macro2::TokenStream = body.parse().unwrap();
        let err = syn::parse2::<PresentsArgs>(tokens)
            .expect_err("witness= on presents is rejected")
            .to_string();
        assert!(
            err.contains("defended_by"),
            "error should point at #[defended_by] for code-tier evidence; got: {err:?}"
        );
    }

    // ========================================================================
    // Prescriptive Work-Orchestration Family parse tests (ADR-033)
    // ========================================================================

    #[test]
    fn panel_accepts_full_shape() {
        let tokens: TokenStream = r#"needs = ["review error path", "check edge case"], filled_by = ["alice"], reviewed_by = ["bob"], ordered_by = "carol", due = "2027-01-01""#
            .parse()
            .unwrap();
        let args = syn::parse2::<PanelArgs>(tokens).unwrap();
        assert_eq!(args.needs.len(), 2);
        assert_eq!(args.filled_by, vec!["alice"]);
        assert_eq!(args.reviewed_by, vec!["bob"]);
        assert_eq!(args.ordered_by.as_deref(), Some("carol"));
        args.validate().unwrap();
    }

    #[test]
    fn panel_rejects_empty_needs() {
        // ATK-PRES-1: empty needs is a vacuous work-need.
        let tokens: TokenStream = r"needs = []".parse().unwrap();
        let args = syn::parse2::<PanelArgs>(tokens).unwrap();
        let err = args
            .validate()
            .expect_err("empty needs must reject")
            .to_string();
        assert!(
            err.contains("non-empty"),
            "error must explain vacuity: {err:?}"
        );
    }

    #[test]
    fn panel_rejects_missing_needs() {
        let tokens: TokenStream = r#"filled_by = ["alice"]"#.parse().unwrap();
        let args = syn::parse2::<PanelArgs>(tokens).unwrap();
        assert!(args.validate().is_err(), "missing needs must reject");
    }

    #[test]
    fn panel_rejects_unknown_field() {
        let tokens: TokenStream = r#"needs = ["x"], bogus = "y""#.parse().unwrap();
        assert!(syn::parse2::<PanelArgs>(tokens).is_err());
    }

    #[test]
    fn ddx_accepts_full_shape() {
        let tokens: TokenStream = r#"symptom = "slow query", rule_out = ["missing index", "n+1"], investigator = "alice""#
            .parse()
            .unwrap();
        let args = syn::parse2::<DdxArgs>(tokens).unwrap();
        assert_eq!(args.symptom.as_deref(), Some("slow query"));
        assert_eq!(args.rule_out.len(), 2);
        args.validate().unwrap();
    }

    #[test]
    fn ddx_rejects_empty_rule_out() {
        // ATK-PRES-2: empty alternative-set is no differential diagnosis.
        let tokens: TokenStream = r#"symptom = "x", rule_out = []"#.parse().unwrap();
        let args = syn::parse2::<DdxArgs>(tokens).unwrap();
        assert!(args.validate().is_err(), "empty rule_out must reject");
    }

    #[test]
    fn ddx_rejects_missing_symptom() {
        let tokens: TokenStream = r#"rule_out = ["a"]"#.parse().unwrap();
        let args = syn::parse2::<DdxArgs>(tokens).unwrap();
        assert!(args.validate().is_err());
    }

    #[test]
    fn quarantine_accepts_full_shape() {
        let tokens: TokenStream =
            r#"scope = "legacy::module", until = "2027-06-01", reason = "pending upstream fix""#
                .parse()
                .unwrap();
        let args = syn::parse2::<QuarantineArgs>(tokens).unwrap();
        assert_eq!(args.scope.as_deref(), Some("legacy::module"));
        args.validate().unwrap();
    }

    #[test]
    fn quarantine_rejects_empty_reason() {
        // ATK-PRES-3: ADR-005 Amd2 rationale-as-required.
        let tokens: TokenStream = r#"scope = "x", reason = """#.parse().unwrap();
        let args = syn::parse2::<QuarantineArgs>(tokens).unwrap();
        let err = args
            .validate()
            .expect_err("empty reason must reject")
            .to_string();
        assert!(
            err.contains("Amendment 2"),
            "error must cite ADR-005 Amd2: {err:?}"
        );
    }

    #[test]
    fn quarantine_rejects_missing_reason() {
        let tokens: TokenStream = r#"scope = "x""#.parse().unwrap();
        let args = syn::parse2::<QuarantineArgs>(tokens).unwrap();
        assert!(
            args.validate().is_err(),
            "missing reason must reject (ADR-005 Amd2)"
        );
    }

    #[test]
    fn rx_accepts_minimal_and_rejects_empty_treatment() {
        let ok: TokenStream = r#"treatment = "add retry with backoff""#.parse().unwrap();
        syn::parse2::<RxArgs>(ok).unwrap().validate().unwrap();

        let empty: TokenStream = r#"treatment = """#.parse().unwrap();
        assert!(syn::parse2::<RxArgs>(empty).unwrap().validate().is_err());
    }

    #[test]
    fn refer_requires_to() {
        let ok: TokenStream = r#"to = "platform-team", response_due = "2027-02-01""#
            .parse()
            .unwrap();
        syn::parse2::<ReferArgs>(ok).unwrap().validate().unwrap();

        let missing: TokenStream = r#"response_due = "2027-02-01""#.parse().unwrap();
        assert!(syn::parse2::<ReferArgs>(missing)
            .unwrap()
            .validate()
            .is_err());
    }

    #[test]
    fn biopsy_requires_location_and_request_text() {
        let ok: TokenStream =
            r#"location = "parser::fast_path", request_text = "why does it allocate twice""#
                .parse()
                .unwrap();
        syn::parse2::<BiopsyArgs>(ok).unwrap().validate().unwrap();

        let missing_text: TokenStream = r#"location = "x""#.parse().unwrap();
        assert!(syn::parse2::<BiopsyArgs>(missing_text)
            .unwrap()
            .validate()
            .is_err());
    }

    #[test]
    fn culture_requires_test_kind() {
        let ok: TokenStream = r#"test_kind = "24h soak", runs_until = "2027-01-02""#
            .parse()
            .unwrap();
        syn::parse2::<CultureArgs>(ok).unwrap().validate().unwrap();

        let missing: TokenStream = r#"duration = "24h""#.parse().unwrap();
        assert!(syn::parse2::<CultureArgs>(missing)
            .unwrap()
            .validate()
            .is_err());
    }

    #[test]
    fn triage_accepts_priority_order_of_code_sites() {
        let tokens: TokenStream =
            r#"priority_order = ["src/a.rs::foo", "src/b.rs::bar"], triaged_by = "navigator", re_triage_due = "2027-03-01""#
                .parse()
                .unwrap();
        let args = syn::parse2::<TriageArgs>(tokens).unwrap();
        assert_eq!(args.priority_order.len(), 2);
        assert_eq!(args.triaged_by.as_deref(), Some("navigator"));
        args.validate().unwrap();
    }

    #[test]
    fn triage_rejects_empty_priority_order() {
        let tokens: TokenStream = r"priority_order = []".parse().unwrap();
        let args = syn::parse2::<TriageArgs>(tokens).unwrap();
        assert!(args.validate().is_err(), "empty priority_order is vacuous");
    }

    #[test]
    fn triage_rejects_dropped_campsites_field() {
        // `campsites` was DROPPED post-ratification — using it must be an
        // unknown-field error (not silently accepted), and the error must point
        // the adopter at priority_order.
        let tokens: TokenStream = r#"campsites = ["x"]"#.parse().unwrap();
        let err = syn::parse2::<TriageArgs>(tokens)
            .expect_err("campsites was dropped — must reject")
            .to_string();
        assert!(
            err.contains("priority_order"),
            "the unknown-field error must redirect to priority_order: {err:?}"
        );
    }
}