autumn-macros 0.9.0

Proc macros for the Autumn web framework
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
//! Route macro implementation.
//!
//! Generates two companion functions for each annotated handler:
//!
//! 1. `__autumn_route_info_{name}()` — returns a `Route` (existing behaviour).
//! 2. `__autumn_path_{helper_name}(params…) -> String` — typed path helper
//!    that accepts one `impl Display` argument per `{param}` segment in the URL
//!    and returns the formatted absolute path string.
//!
//! The `helper_name` defaults to the handler function name but can be
//! overridden with the `name = "custom_name"` route attribute argument.
//!
//! [`ApiDoc`]: ../../autumn_web/openapi/struct.ApiDoc.html

use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::{FnArg, LitStr, ReturnType, Type};

use crate::api_doc;
use crate::idempotency_guard::block_has_replay_guard;
use crate::parse;

/// Core implementation shared by all route macros (`#[get]`, `#[post]`, etc.).
///
/// `http_method` is the uppercase method name (e.g., `"GET"`).
/// `axum_fn` is the lowercase axum routing function name (e.g., `"get"`).
#[allow(clippy::too_many_lines)]
pub fn route_macro(
    http_method: &str,
    axum_fn: &str,
    attr: TokenStream,
    item: TokenStream,
) -> TokenStream {
    let route_args = match parse::parse_route_attr(attr) {
        Ok(a) => a,
        Err(err) => return emit_with_attr_parse_error(&item, &err),
    };
    let path = route_args.path.clone();

    let (leading_items, mut input_fn) = match parse::parse_async_handler_with_leading_items(item) {
        Ok(v) => v,
        Err(err) => return err,
    };

    // An attribute sharing #[authorize]'s argument grammar under a different
    // name is refused rather than guessed at when deciding whether this
    // route keeps the standalone `IdempotencyReplayLayer` — see
    // `authorize::reject_if_ambiguous_authorize_shape`'s doc comment.
    if let Some(err) = crate::authorize::reject_if_ambiguous_authorize_shape(&input_fn) {
        return err;
    }

    // Extract #[intercept(LayerType)] attributes from the handler.
    let interceptors = parse::extract_interceptors(&mut input_fn.attrs);

    // Extract #[api_doc(...)] overrides before emitting the function, so
    // the attribute doesn't leak onto the emitted fn definition and
    // trigger an "unknown attribute" error.
    let api_doc_attr = match api_doc::extract(&mut input_fn.attrs) {
        Ok(v) => v,
        Err(err) => return err,
    };

    // ── `#[edge]` opt-in (#1790) ────────────────────────────────
    // Detected before any code is generated so an ineligible route fails with
    // one purpose-written diagnostic instead of a wall of downstream type
    // errors from the emitted edge companion.
    let edge = crate::edge::detect(&input_fn);
    if let Some(marking) = edge
        && let Some(err) = reject_ineligible_edge_route(
            http_method,
            &input_fn,
            !interceptors.is_empty(),
            marking.needs_identity,
            marking.span,
        )
    {
        return err;
    }

    let fn_name = &input_fn.sig.ident;
    let route_info_name = format_ident!("__autumn_route_info_{}", fn_name);
    let vis = &input_fn.vis;

    // Determine the path-helper name: use `name = "..."` override when set,
    // otherwise default to the handler function name.
    let helper_ident = route_args.helper_ident(fn_name);
    let path_helper_name = format_ident!("__autumn_path_{}", helper_ident);
    let fn_name_alias = emit_fn_name_alias(
        route_args.name_override.as_ref(),
        fn_name,
        &path_helper_name,
    );

    let method_const = format_ident!("{}", http_method); // e.g., GET
    let routing_fn = format_ident!("{}", axum_fn); // e.g., get

    // When #[feature_flag] is stacked, it prepends a gate parameter of type
    // `__AutumnFlagGate_{handler_name}` to the handler inputs. Since route macros
    // run before attribute macros lower down the chain, we must detect this attribute
    // and manually propagate the gate parameter to the primitive wrapper so that
    // the wrapper's call to the handler compiles.
    let has_feature_flag_attr = input_fn.attrs.iter().any(|a| {
        a.path()
            .segments
            .last()
            .is_some_and(|s| s.ident == "feature_flag")
    });
    // Body guards that rewrite the handler's return type to `Response` (and
    // inject hidden extractors): #[throttle], #[step_up], #[authorize], and
    // #[secured]. This route macro is outermost, so when one of these guards is
    // still present as an attribute it has not expanded yet — the signature we
    // see here still declares the original primitive return type, but the guard
    // will lower it to `Response`. Emitting the primitive `.to_string()` wrapper
    // (which calls the handler with only the user's original args and stringifies
    // the result) would then fail to compile, so skip it and route through the
    // normal `Response` path. (#[feature_flag] does NOT rewrite the return type;
    // it propagates its gate param instead, so the primitive wrapper is kept.)
    let has_response_rewriting_guard = has_throttle_guard(&input_fn)
        || has_step_up_guard(&input_fn)
        || has_secured_attr(&input_fn)
        || has_authorize_attr(&input_fn);
    let primitive_wrapper = if should_stringify_primitive_output(&input_fn.sig.output)
        && !has_response_rewriting_guard
    {
        let wrapper_name = format_ident!("__autumn_primitive_handler_{}", fn_name);
        let mut wrapper_inputs = Vec::new();
        let mut call_args = Vec::new();

        if has_feature_flag_attr {
            let gate_ident = format_ident!("__AutumnFlagGate_{}", fn_name);
            wrapper_inputs.push(quote! { __autumn_gate: #gate_ident });
            call_args.push(quote! { __autumn_gate });
        }

        for (idx, arg) in input_fn.sig.inputs.iter().enumerate() {
            match arg {
                FnArg::Typed(pat_type) => {
                    let arg_name = format_ident!("__autumn_arg_{idx}");
                    let ty = &pat_type.ty;
                    wrapper_inputs.push(quote! { #arg_name: #ty });
                    call_args.push(quote! { #arg_name });
                }
                FnArg::Receiver(receiver) => {
                    return syn::Error::new_spanned(
                        receiver,
                        "Autumn route handlers cannot take a self receiver",
                    )
                    .to_compile_error();
                }
            }
        }

        Some(quote! {
            #[doc(hidden)]
            async fn #wrapper_name(#(#wrapper_inputs),*) -> ::std::string::String {
                #fn_name(#(#call_args),*).await.to_string()
            }
        })
    } else {
        None
    };

    let handler_name = primitive_wrapper.as_ref().map_or_else(
        || fn_name.clone(),
        |_| format_ident!("__autumn_primitive_handler_{}", fn_name),
    );

    // ── Edge lane codegen (#1790) ───────────────────────────────
    // For an edge route every item that mentions `::autumn_web` is gated off
    // the wasm32 target (autumn-web is never compiled for wasm), while the
    // handler itself and the edge companion stay unconditional so one source
    // file serves both the origin binary and the capsule. For every other
    // route both values are empty and the expansion is unchanged.
    let (native_cfg, edge_companion) = emit_edge_items(edge, fn_name, &handler_name, vis, &path);

    // ── OpenAPI metadata ────────────────────────────────────────
    let pools_tokens = emit_pool_slice(&derive_pools(&input_fn));
    let path_params = api_doc::extract_path_params(&path.value());
    let path_params_tokens = api_doc::emit_path_param_slice(&path_params);
    let request_body = api_doc::schema_option(api_doc::infer_request_body(&input_fn));
    let response_body = api_doc::schema_option(api_doc::infer_response_body(&input_fn));
    let query_schema = api_doc::schema_option(api_doc::infer_query_params(&input_fn));
    let (secured, required_roles, required_scopes) = api_doc::extract_secured_info(&input_fn);
    let is_public = api_doc::is_public(&input_fn);
    let has_feature_flag = has_feature_flag_attr || has_expanded_feature_flag_gate(&input_fn);
    let body_guarded_replay = secured
        || has_authorize_guard(&input_fn)
        || has_feature_flag
        || has_step_up_guard(&input_fn)
        || has_throttle_guard(&input_fn);
    let intercepted_route = !interceptors.is_empty();
    let mut handler_expr = build_handler_expr(
        &routing_fn,
        &handler_name,
        &interceptors,
        !body_guarded_replay && !intercepted_route,
    );
    if edge.is_some() {
        // The wire runtime strips SENSITIVE_HEADERS before the capsule
        // dispatches, so the native mount must strip the same set before the
        // handler: otherwise a handler that reads `cookie`/`authorization`
        // through `HeaderMap` would serve different bytes at the origin than
        // at the edge. Route-local — middleware above the router still sees
        // the original request.
        handler_expr = quote! {
            #handler_expr.layer(::autumn_edge::reexports::axum::middleware::map_request(
                ::autumn_edge::strip_request_credentials,
            ))
        };
    }
    let route_idempotency = if !route_args.idempotent {
        quote! { ::autumn_web::RouteIdempotency::Off }
    } else if intercepted_route {
        quote! { ::autumn_web::RouteIdempotency::Direct }
    } else {
        quote! { ::autumn_web::RouteIdempotency::ReplayThroughInner }
    };
    let api_doc_fields = api_doc_attr.emit_ident_fields(fn_name);
    let http_method_lit = LitStr::new(http_method, Span::call_site());
    let api_version_expr = route_args.api_version.as_ref().map_or_else(
        || quote! { ::core::option::Option::None },
        |lit| quote! { ::core::option::Option::Some(#lit) },
    );
    let sunset_opt_out_val = route_args.sunset_opt_out;
    let route_timeout = match route_args.timeout {
        crate::parse::RouteTimeoutAttr::Inherit => {
            quote! { ::autumn_web::RouteTimeout::Inherit }
        }
        crate::parse::RouteTimeoutAttr::Ms(ms) => {
            quote! {
                ::autumn_web::RouteTimeout::Override(
                    ::core::time::Duration::from_millis(#ms)
                )
            }
        }
        crate::parse::RouteTimeoutAttr::Disabled => {
            quote! { ::autumn_web::RouteTimeout::Disabled }
        }
    };
    let route_criticality = match route_args.criticality {
        crate::parse::RouteCriticalityAttr::Critical => {
            quote! { ::autumn_web::Criticality::Critical }
        }
        crate::parse::RouteCriticalityAttr::Default => {
            quote! { ::autumn_web::Criticality::Default }
        }
        crate::parse::RouteCriticalityAttr::Sheddable => {
            quote! { ::autumn_web::Criticality::Sheddable }
        }
    };
    let has_policy_val = has_policy_only(&input_fn);
    // Source order is preserved here on purpose: `ApiDoc` stays faithful to the
    // handler as written, and the route listing canonicalizes (sorts/dedupes)
    // when it projects these onto the wire.
    let authorize_bindings =
        api_doc::emit_authorize_binding_slice(&api_doc::extract_authorize_bindings(&input_fn));
    // `#[agent_operable]` names the authority static after the handler, so the
    // route macro only needs to know *whether* the handler is governed — the
    // grant, the proved effects and the const assertions are the analyser's.
    let agent_authority = if api_doc::extract_agent_authority(&input_fn) {
        let authority_static = format_ident!("__AUTUMN_AGENT_AUTHORITY_{}", fn_name);
        quote! { ::core::option::Option::Some(&#authority_static) }
    } else {
        quote! { ::core::option::Option::None }
    };
    let seo_defaults = route_args.seo.emit();

    // ── Architecture-graph node (#1747) ─────────────────────────
    // Gated off wasm32 with `#native_cfg` for the same reason the route-info
    // route companion does: a route the edge lane compiles out has nothing to
    // say about the native binary's architecture, and the descriptor names
    // `::autumn_web`, which never compiles for that target.
    let graph_descriptor =
        crate::graph::emit_route_descriptor(&input_fn, http_method, &quote! { #path }, false);

    // ── Path helper ─────────────────────────────────────────────
    // An `#[edge]` route's helper uses the `autumn_edge` encoders and is not
    // gated, so a handler that builds a link compiles on both lanes (#1790).
    let encoders = if edge.is_some() {
        quote! { ::autumn_edge::paths }
    } else {
        quote! { ::autumn_web::paths }
    };
    let path_helper = emit_path_helper(&path_helper_name, &path, &path_params, &encoders);

    quote! {
        // A guard macro that already expanded above this route attribute
        // (#[secured]/#[step_up]/#[throttle], #1668) leaves its hidden
        // `FromRequestParts` gate type here, ahead of the handler — re-emit
        // it verbatim; empty when no such guard expanded first.
        #leading_items

        // ECHO-001: We want to apply #[axum::debug_handler] but without forcing the user
        // to import axum manually. However, the path resolution in Axum macros makes this impossible
        // natively. Custom compile errors handle the type checks.
        #input_fn
        #primitive_wrapper

        #native_cfg
        #[doc(hidden)]
        #vis fn #route_info_name() -> ::autumn_web::Route {
            ::autumn_web::Route {
                method: ::autumn_web::reexports::http::Method::#method_const,
                path: #path,
                handler: #handler_expr,
                name: ::core::stringify!(#fn_name),
                api_version: #api_version_expr,
                sunset_opt_out: #sunset_opt_out_val,
                api_doc: ::autumn_web::openapi::ApiDoc {
                    method: #http_method_lit,
                    path: #path,
                    path_params: #path_params_tokens,
                    request_body: #request_body,
                    response: #response_body,
                    query_schema: #query_schema,
                    secured: #secured,
                    required_roles: #required_roles,
                    required_scopes: #required_scopes,
                    register_schemas: ::core::option::Option::None,
                    api_version: #api_version_expr,
                    sunset_opt_out: #sunset_opt_out_val,
                    has_policy: #has_policy_val,
                    authorize_bindings: #authorize_bindings,
                    pools: #pools_tokens,
                    public: #is_public,
                    module_path: ::core::module_path!(),
                    source_file: ::core::file!(),
                    source_line: ::core::line!(),
                    agent_authority: #agent_authority,
                    #api_doc_fields
                },
                repository: ::core::option::Option::None,
                idempotency: #route_idempotency,
                timeout: #route_timeout,
                criticality: #route_criticality,
                seo: #seo_defaults,
            }
        }

        #native_cfg
        #graph_descriptor

        #path_helper
        #fn_name_alias

        #edge_companion
    }
}

/// When the `#[get("/path")]`-style attribute itself fails to parse (an empty
/// literal, a missing leading slash, a dropped string literal entirely —
/// `#[get()]`), still emit the handler and a stub `__autumn_route_info_*`
/// companion alongside the `compile_error!`, instead of only the
/// `compile_error!`.
///
/// Without this, the handler silently disappears from the module (the early
/// `return err` this replaces never re-emits `item`), so `routes![handler]` —
/// the README's documented way to register every handler — can't find
/// `handler`, and can't find its `__autumn_route_info_handler` companion
/// either: two more "cannot find" errors on top of the real one, the second
/// naming an internal macro symbol no user ever typed (docs/reports/
/// echo-audit-run.md). Mirrors the same guard already in
/// `agent_operable_macro` and `query_budget_macro` (see their "Keep the
/// original tokens so a parse failure still emits the item" comments).
///
/// Two things this re-emission must not do (Codex review, PR #2798):
///
/// - Assume `item` parses as a bare function. A guard macro stacked *above*
///   the malformed route attribute (`#[secured]`/`#[step_up]`/`#[throttle]`)
///   already expanded by the time this runs, so `item` is really its gate
///   struct/impl followed by the handler — `split_leading_items_and_fn`
///   (the same helper the successful path uses) is what actually finds the
///   function in that shape.
/// - Re-emit `#[intercept(...)]` verbatim. It is a route-macro-only marker
///   (`parse::extract_interceptors`), never registered as its own attribute
///   macro, so left on the handler it would fail to resolve and add
///   "cannot find attribute `intercept`" on top of the real diagnostic.
/// - Re-emit `#[api_doc(...)]` verbatim either. It *is* a real, independently
///   registered attribute macro (`#[proc_macro_attribute] pub fn api_doc`),
///   but only under its full path or when the caller's module has it in
///   scope; a caller that wrote `use autumn_web::{get, routes};` (not the
///   prelude) never imported the bare name, so re-emitting it unqualified
///   fails to resolve too. The successful path always consumes it via
///   `api_doc::extract` before emitting `input_fn` — this path must match.
/// - Emit the `__autumn_route_info_*` stub unconditionally on an
///   `#[edge]`-marked handler. `::autumn_web::Route` (its return type) does
///   not resolve on `wasm32` builds of the edge lane — e.g.
///   `examples/edge-greeting`'s capsule target, which depends on
///   `autumn-edge` but never on `autumn-web` — so the stub itself would fail
///   to compile there, and `edge_routes![handler]` (the wasm-side sibling of
///   `routes![handler]`) would still be missing the
///   `__autumn_edge_route_*` companion it actually collects. Mirrors
///   `emit_edge_items`: the native stub is gated the same
///   `#[cfg(not(target_arch = "wasm32"))]` way, and an unconditional
///   `__autumn_edge_route_*` stub (returning `::autumn_edge::EdgeRoute`,
///   available on every target `#[edge]` compiles for) stands in for it.
fn emit_with_attr_parse_error(item: &TokenStream, err: &TokenStream) -> TokenStream {
    let Ok((leading_items, mut input_fn)) = parse::split_leading_items_and_fn(item) else {
        return quote! { #item #err };
    };
    parse::extract_interceptors(&mut input_fn.attrs);
    let _ = api_doc::extract(&mut input_fn.attrs);
    let edge = crate::edge::detect(&input_fn);
    let vis = &input_fn.vis;
    let fn_name = &input_fn.sig.ident;
    let route_info_name = format_ident!("__autumn_route_info_{fn_name}");
    let native_cfg = edge.map(|_| quote! { #[cfg(not(target_arch = "wasm32"))] });
    let edge_stub = edge.map(|_| {
        let edge_route_name = format_ident!("__autumn_edge_route_{fn_name}");
        quote! {
            #[doc(hidden)]
            #vis fn #edge_route_name() -> ::autumn_edge::EdgeRoute {
                unreachable!()
            }
        }
    });
    quote! {
        #leading_items
        #input_fn

        #native_cfg
        #[doc(hidden)]
        #vis fn #route_info_name() -> ::autumn_web::Route {
            unreachable!()
        }

        #edge_stub

        #err
    }
}

/// Compile error for `#[edge]` on a route the edge lane cannot serve.
const EDGE_METHOD_ERROR: &str = "`#[edge]` is only supported on `#[get]` routes; \
                                 the edge lane is read-path only (issue #1790)";

/// Compile error for `#[edge]` stacked with an auth or rate guard.
const EDGE_GUARD_ERROR: &str = "`#[edge]` cannot be combined with \
                                `#[secured]`/`#[authorize]`/`#[step_up]`/`#[throttle]` — the edge \
                                capsule has no session or auth state; serve this route from the \
                                origin";

/// Compile error for `#[edge]` stacked with `#[intercept(...)]`.
const EDGE_INTERCEPT_ERROR: &str = "`#[edge]` cannot be combined with `#[intercept(...)]` — \
                                    interceptor layers are origin-only tower middleware and are \
                                    not carried into the edge capsule, so the two lanes would \
                                    serve different bytes; serve this route from the origin";

/// Compile error for an `#[edge]` handler taking `Extension<T>`.
const EDGE_EXTENSION_ERROR: &str = "`#[edge]` handlers cannot take `Extension<...>` — the \
                                    capsule installs no request extensions (the `EdgeCache` seam \
                                    is the one mediated capability), so a missing extension \
                                    would be served as a 500 instead of falling through; use \
                                    `EdgeCache`, or serve this route from the origin";

/// Compile error for an `#[edge]` handler taking `EdgeIdentity` without
/// declaring it.
const EDGE_IDENTITY_UNDECLARED_ERROR: &str = "`#[edge]` handlers that take `EdgeIdentity` must \
     declare it with `#[edge(needs(identity))]`, so an unauthenticated request falls through to \
     the origin before any handler code runs";

/// Compile error for `#[edge]` stacked with `#[agent_operable]`.
const EDGE_AGENT_OPERABLE_ERROR: &str = "`#[edge]` cannot be combined with `#[agent_operable(...)]` — the edge lane is \
     read-only, and the capsule has no audit sink or `AppState` to record an agent \
     invocation against, so a governed action would run there unaudited; serve this \
     route from the origin.\n\nServe the route from the origin, or drop \
     `#[agent_operable]`. See docs/guide/agent-authority.md.";

/// Marker consts a guard that expanded *before* this route macro left behind
/// in the handler body instead of an attribute, and missing it would ship a
/// guarded route to the unauthenticated edge lane.
///
/// `#[step_up]`/`#[throttle]` don't appear here: their check moved into a
/// pre-body `FromRequestParts` gate (#1668) and they never left an
/// OpenAPI-readable body marker to begin with, so `has_auth_or_rate_guard`
/// recognizes them via `has_step_up_guard`/`has_throttle_guard`'s own
/// gate-param check instead of this body scan.
const GUARD_MARKERS: &[&str] = &[
    "__AUTUMN_SECURED_ROLES",
    "__AUTUMN_SECURED_SCOPES",
    "__AUTUMN_AUTHORIZE_BINDINGS",
    "__AUTUMN_AGENT_OPERABLE",
];

/// Reject an `#[edge]` route the edge lane cannot serve, spanning the error at
/// the `#[edge]` attribute (or the handler name once it has expanded).
fn reject_ineligible_edge_route(
    http_method: &str,
    input_fn: &syn::ItemFn,
    has_interceptors: bool,
    needs_identity: bool,
    span: Span,
) -> Option<TokenStream> {
    if http_method != "GET" {
        return Some(syn::Error::new(span, EDGE_METHOD_ERROR).to_compile_error());
    }
    // Checked before the generic auth/rate guard sweep below: the marker is in
    // `GUARD_MARKERS` too (so a governed handler can never slip past that
    // sweep), but its own diagnostic names the real reason — the edge lane is
    // read-only — instead of talking about session state.
    if crate::api_doc::extract_agent_authority(input_fn) {
        return Some(syn::Error::new(span, EDGE_AGENT_OPERABLE_ERROR).to_compile_error());
    }
    if has_auth_or_rate_guard(input_fn) {
        return Some(syn::Error::new(span, EDGE_GUARD_ERROR).to_compile_error());
    }
    // `#[intercept(...)]` attrs were already stripped off `input_fn` by
    // `parse::extract_interceptors`, so the caller passes the extracted list's
    // emptiness instead of this fn re-scanning attributes.
    if has_interceptors {
        return Some(syn::Error::new(span, EDGE_INTERCEPT_ERROR).to_compile_error());
    }
    if has_extension_param(input_fn) {
        return Some(syn::Error::new(span, EDGE_EXTENSION_ERROR).to_compile_error());
    }
    if !needs_identity && has_edge_identity_param(input_fn) {
        return Some(syn::Error::new(span, EDGE_IDENTITY_UNDECLARED_ERROR).to_compile_error());
    }
    None
}

/// Whether any parameter's type names `EdgeIdentity`.
///
/// Identity must be declared with `needs(identity)` so the runtime can refuse
/// an unauthenticated request *before* dispatch, the same way it refuses a
/// missing `kv`. Like [`has_extension_param`], an alias that hides the name is
/// not resolved; the extractor's own rejection still falls through to origin.
fn has_edge_identity_param(input_fn: &syn::ItemFn) -> bool {
    input_fn.sig.inputs.iter().any(|arg| {
        let syn::FnArg::Typed(pat_type) = arg else {
            return false;
        };
        tokens_contain_ident(&quote! { #pat_type }, "EdgeIdentity")
    })
}

/// Whether any parameter's type names `Extension` — `Extension<T>`,
/// `axum::Extension<T>`, or nested as `Option<Extension<T>>`.
///
/// `Extension` satisfies axum's `Handler<_, EdgeState>` bound for *any* state,
/// so the type system alone cannot keep it out of the edge lane; this
/// syntactic check is the enforcement point. A type alias that hides the name
/// is not resolved — the same recognition limit every source-level check in
/// this crate documents.
fn has_extension_param(input_fn: &syn::ItemFn) -> bool {
    input_fn.sig.inputs.iter().any(|arg| {
        let syn::FnArg::Typed(pat_type) = arg else {
            return false;
        };
        tokens_contain_ident(&quote! { #pat_type }, "Extension")
    })
}

/// Extractor identifiers that prove a route holds a pooled or external
/// resource for the length of the request, paired with the pool tag recorded
/// in the capacity contract (issue #1733).
///
/// Deliberately narrow: only extractors that *are* a handle on the resource,
/// for the length of the request, are listed. `LazyDb` (#2264) is excluded:
/// its whole point is *not* holding a connection across the body read, so
/// listing it here would claim the very thing it exists to avoid. An
/// extractor that merely happens to consult the database on some paths
/// (`Session`, `Tenant`, `Flags`) is not listed either, because a contract
/// that over-claims is worse than one that under-claims — see the "provable
/// subset" caveat on `RouteInfo::pools`.
const POOL_EXTRACTORS: &[(&str, &str)] = &[
    ("CrossShard", "db"),
    ("Db", "db"),
    ("Events", "events"),
    ("Mailer", "mail"),
    ("Notifications", "notifications"),
    ("Presence", "presence"),
    ("ShardedDb", "db"),
    ("ShardedReadDb", "db"),
    ("Shards", "db"),
];

/// The pool tags a handler's declared extractors prove it touches, sorted and
/// deduplicated so the emitted contract diff is stable.
///
/// Only the parameter *types* are scanned, never the binding names, so a
/// parameter called `events` cannot be mistaken for the `Events` extractor.
/// Like every source-level check in this crate, a type alias that hides the
/// extractor's name is not resolved.
fn derive_pools(input_fn: &syn::ItemFn) -> Vec<&'static str> {
    let mut pools: Vec<&'static str> = Vec::new();
    for arg in &input_fn.sig.inputs {
        let syn::FnArg::Typed(pat_type) = arg else {
            continue;
        };
        let Some(extractor) = declared_extractor(&pat_type.ty) else {
            continue;
        };
        for (name, pool) in POOL_EXTRACTORS {
            if extractor == *name && !pools.contains(pool) {
                pools.push(pool);
            }
        }
    }
    pools.sort_unstable();
    pools
}

/// The name of the extractor a parameter *declares*, or `None` when the type
/// is not a plain path.
///
/// Deliberately NOT a recursive search for a resource name anywhere in the
/// type: `State<AppState<Db>>` declares `State`, not `Db`. Matching nested
/// generic arguments would contradict the documented rule that a pool held
/// through an application `State` value is invisible to this derivation, and
/// would write false `db-bound` shapes — and digest drift — into the contract.
/// Under-claiming is the safe direction here; over-claiming is a lie.
///
/// Transparent wrappers axum itself sees through are peeled, so `Option<Db>`
/// and `&Db` still declare `Db`. Like every source-level check in this crate,
/// a type alias that hides the name is not resolved.
fn declared_extractor(ty: &syn::Type) -> Option<String> {
    match ty {
        syn::Type::Reference(inner) => declared_extractor(&inner.elem),
        syn::Type::Paren(inner) => declared_extractor(&inner.elem),
        syn::Type::Group(inner) => declared_extractor(&inner.elem),
        syn::Type::Path(path) => {
            let segment = path.path.segments.last()?;
            if segment.ident == "Option"
                && let syn::PathArguments::AngleBracketed(args) = &segment.arguments
                && let Some(syn::GenericArgument::Type(inner)) = args.args.first()
            {
                return declared_extractor(inner);
            }
            Some(segment.ident.to_string())
        }
        _ => None,
    }
}

/// Emit the derived pool set as a `&'static [&'static str]` literal.
fn emit_pool_slice(pools: &[&'static str]) -> TokenStream {
    if pools.is_empty() {
        quote! { &[] }
    } else {
        quote! { &[#(#pools),*] }
    }
}

/// Whether `stream` contains `needle` as an exact identifier, at any nesting.
fn tokens_contain_ident(stream: &TokenStream, needle: &str) -> bool {
    stream.clone().into_iter().any(|tree| match tree {
        proc_macro2::TokenTree::Ident(ident) => ident == needle,
        proc_macro2::TokenTree::Group(group) => tokens_contain_ident(&group.stream(), needle),
        _ => false,
    })
}

/// Whether an auth or rate guard is declared on the handler, in either
/// attribute order: still a live attribute, or already expanded into the marker
/// const it injects.
fn has_auth_or_rate_guard(input_fn: &syn::ItemFn) -> bool {
    has_secured_attr(input_fn)
        || has_authorize_attr(input_fn)
        || has_step_up_guard(input_fn)
        || has_throttle_guard(input_fn)
        || GUARD_MARKERS
            .iter()
            .any(|marker| crate::edge::stmts_have_marker(&input_fn.block.stmts, marker))
}

/// Build the wasm32 gate and the edge companion for an `#[edge]` route.
///
/// Returns two empty token streams for every other route, which keeps the
/// expansion of a non-edge route byte-identical to what it was before the edge
/// lane existed.
fn emit_edge_items(
    edge: Option<crate::edge::EdgeMarking>,
    fn_name: &proc_macro2::Ident,
    handler_name: &proc_macro2::Ident,
    vis: &syn::Visibility,
    path: &LitStr,
) -> (TokenStream, TokenStream) {
    let Some(marking) = edge else {
        return (TokenStream::new(), TokenStream::new());
    };

    let mut capabilities = Vec::new();
    if marking.needs_kv {
        capabilities.push(quote! { ::autumn_edge::EdgeCapability::Kv });
    }
    if marking.needs_identity {
        capabilities.push(quote! { ::autumn_edge::EdgeCapability::Identity });
    }
    let needs = quote! { &[#(#capabilities),*] };
    let edge_route_name = format_ident!("__autumn_edge_route_{}", fn_name);

    (
        quote! { #[cfg(not(target_arch = "wasm32"))] },
        quote! {
            #[doc(hidden)]
            #vis fn #edge_route_name() -> ::autumn_edge::EdgeRoute {
                ::autumn_edge::EdgeRoute {
                    method: ::autumn_edge::reexports::http::Method::GET,
                    path: #path,
                    // The same handler axum mounts natively — including the
                    // primitive-output wrapper when there is one. Everything
                    // else the native mount can wrap around a handler
                    // (`#[intercept]` layers, auth guards) is refused for edge
                    // routes by `reject_ineligible_edge_route`, so the two
                    // lanes cannot diverge on how a response is produced.
                    handler: ::autumn_edge::edge_get(#handler_name),
                    name: ::core::stringify!(#fn_name),
                    needs: #needs,
                }
            }
        },
    )
}

/// Build the axum handler expression, applying interceptor layers in reverse
/// attribute order so the first `#[intercept(...)]` is the outermost layer.
fn build_handler_expr(
    routing_fn: &proc_macro2::Ident,
    handler_name: &proc_macro2::Ident,
    interceptors: &[syn::Path],
    include_replay_layer: bool,
) -> TokenStream {
    let mut expr = quote! { ::autumn_web::reexports::axum::routing::#routing_fn(#handler_name) };
    if include_replay_layer {
        expr = quote! {
            ::autumn_web::reexports::axum::routing::MethodRouter::<
                ::autumn_web::AppState, ::core::convert::Infallible
            >::layer(#expr, ::autumn_web::idempotency::IdempotencyReplayLayer)
        };
    }
    for interceptor in interceptors.iter().rev() {
        // Explicit type annotation avoids inference ambiguity with chained .layer() calls.
        expr = quote! {
            ::autumn_web::reexports::axum::routing::MethodRouter::<
                ::autumn_web::AppState, ::core::convert::Infallible
            >::layer(#expr, #interceptor)
        };
    }
    expr
}

fn has_authorize_guard(input_fn: &syn::ItemFn) -> bool {
    input_fn
        .attrs
        .iter()
        .any(|attr| crate::authorize::attr_is_authorize_shaped(attr, input_fn))
        || block_has_replay_guard(&input_fn.block)
        || crate::api_doc::has_policy_check_in_stmts(&input_fn.block.stmts)
}

/// Whether `#[step_up]` applies to `input_fn`, in either attribute order: a
/// still-unexpanded `#[step_up]` attribute, or (issue #1668) the
/// `__AutumnStepUpGate_*` pre-body `FromRequestParts` gate parameter it
/// expands into. The gate parameter check matters because `#[step_up]` no
/// longer leaves any recognizable shape in the handler *body* — its check now
/// runs in a sibling gate, before the body ever executes — so `body_guarded_replay`
/// (which must stay true whenever a gate owns replay-serving, to keep the
/// standalone `IdempotencyReplayLayer` from serving a cached response ahead of
/// the gate's check) can no longer rely on a body-shape scan alone.
fn has_step_up_guard(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "step_up")
    }) || crate::param_helpers::has_guard_gate_param_with_prefix(input_fn, "__AutumnStepUpGate_")
}

/// Whether `#[throttle]` applies to `input_fn`. See [`has_step_up_guard`] for
/// why the pre-body gate parameter is checked alongside the attribute.
fn has_throttle_guard(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "throttle")
    }) || crate::param_helpers::has_guard_gate_param_with_prefix(input_fn, "__AutumnThrottleGate_")
}

/// Whether a `#[secured]` attribute is still present on the handler (i.e. it has
/// not expanded yet because this route macro is outermost). Used to disable the
/// primitive-output wrapper, since `#[secured]` rewrites the return type to
/// `Response`.
fn has_secured_attr(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "secured")
    })
}

/// Whether an `#[authorize]` attribute is still present on the handler. Used to
/// disable the primitive-output wrapper, since `#[authorize]` rewrites the
/// return type to `Response`. This is intentionally narrower than
/// [`has_authorize_guard`], which also matches inline policy checks that do not
/// rewrite the return type.
fn has_authorize_attr(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "authorize")
    })
}

fn has_policy_only(input_fn: &syn::ItemFn) -> bool {
    input_fn.attrs.iter().any(|attr| {
        attr.path()
            .segments
            .last()
            .is_some_and(|segment| segment.ident == "authorize")
    }) || crate::api_doc::has_policy_check_in_stmts(&input_fn.block.stmts)
}

fn has_expanded_feature_flag_gate(input_fn: &syn::ItemFn) -> bool {
    input_fn.sig.inputs.iter().any(|arg| {
        let FnArg::Typed(pat_type) = arg else {
            return false;
        };
        let Type::Path(type_path) = pat_type.ty.as_ref() else {
            return false;
        };
        let Some(last_segment) = type_path.path.segments.last() else {
            return false;
        };
        last_segment
            .ident
            .to_string()
            .starts_with("__AutumnFlagGate_")
    })
}

/// When a `name = "..."` override is active, emit a `pub use` alias for the
/// handler's own function name so that `paths![fn_name]` resolves alongside
/// the override's `paths![custom_name]`.
fn emit_fn_name_alias(
    name_override: Option<&syn::LitStr>,
    fn_name: &proc_macro2::Ident,
    path_helper_name: &proc_macro2::Ident,
) -> TokenStream {
    let fn_path_helper_name = format_ident!("__autumn_path_{}", fn_name);
    if name_override.is_some() && fn_path_helper_name != *path_helper_name {
        quote! {
            #[doc(hidden)]
            pub use self::#path_helper_name as #fn_path_helper_name;
        }
    } else {
        quote! {}
    }
}

/// Emit the typed path helper function.
///
/// For `/posts/{id}/comments/{comment_id}` this emits:
/// ```ignore
/// pub fn __autumn_path_handler(id: impl Display, comment_id: impl Display) -> String {
///     format!("/posts/{}/comments/{}", id, comment_id)
/// }
/// ```
///
/// Helpers are always emitted as `pub` regardless of handler visibility so
/// that `paths![]` can re-export them without hitting E0364.
///
/// Positional `{}` placeholders are used (rather than named captures) so that
/// route params whose names are Rust keywords — e.g. `/{type}` or `/{match}` —
/// do not produce invalid `format!` invocations. Parameter idents are emitted
/// as raw identifiers (`r#type`) so they are valid in the function signature.
fn emit_path_helper(
    helper_name: &proc_macro2::Ident,
    path: &LitStr,
    params: &[String],
    encoders: &TokenStream,
) -> TokenStream {
    // Build parameter idents: strip `*` catch-all prefix, replace `-` → `_`,
    // then emit as raw identifiers so Rust keywords are valid param names.
    let param_idents: Vec<proc_macro2::Ident> = params
        .iter()
        .map(|p| {
            let sanitized = p.trim_start_matches('*').replace('-', "_");
            proc_macro2::Ident::new_raw(&sanitized, proc_macro2::Span::call_site())
        })
        .collect();

    // Build a positional format string: each `{param}` / `{param:regex}` → `{}`.
    // Positional placeholders avoid named-capture errors when param names are
    // Rust keywords (you cannot write `format!("{type}")` in generated code).
    let format_str = positional_format_string(&path.value());
    let format_lit = LitStr::new(&format_str, path.span());
    let encoded_params: Vec<TokenStream> = params
        .iter()
        .zip(param_idents.iter())
        .map(|(param, ident)| {
            if param.starts_with('*') {
                quote! { #encoders::encode_catch_all_param(#ident) }
            } else {
                quote! { #encoders::encode_path_segment(#ident) }
            }
        })
        .collect();

    quote! {
        #[doc(hidden)]
        pub fn #helper_name(#(#param_idents: impl ::std::fmt::Display),*) -> ::std::string::String {
            format!(#format_lit, #(#encoded_params),*)
        }
    }
}

/// Replace every `{...}` placeholder in a route path with `{}` (positional).
///
/// Handles nested braces from regex quantifiers like `{id:[0-9]{1,3}}` by
/// tracking brace depth, so the outer `{...}` is consumed correctly.
/// Escaped braces (`{{` / `}}`) are passed through unchanged as literal
/// format-string escapes representing a single `{` or `}` in the output.
fn positional_format_string(path: &str) -> String {
    let mut result = String::with_capacity(path.len());
    let mut chars = path.chars().peekable();
    while let Some(c) = chars.next() {
        match c {
            '{' if chars.peek() == Some(&'{') => {
                // Escaped literal brace `{{` — pass through for format string.
                chars.next();
                result.push_str("{{");
            }
            '{' => {
                // Path parameter — emit positional placeholder and skip contents.
                result.push_str("{}");
                let mut depth: u32 = 1;
                for inner in chars.by_ref() {
                    match inner {
                        '{' => depth += 1,
                        '}' => {
                            depth -= 1;
                            if depth == 0 {
                                break;
                            }
                        }
                        _ => {}
                    }
                }
            }
            '}' if chars.peek() == Some(&'}') => {
                // Escaped closing brace `}}` — pass through.
                chars.next();
                result.push_str("}}");
            }
            _ => result.push(c),
        }
    }
    result
}

/// Whether a route handler's declared return type is a bare numeric/bool
/// primitive that Autumn serves by stringifying it (primitives do not implement
/// axum's `IntoResponse`). Shared with the `#[throttle]` macro so a throttled
/// primitive-returning handler stringifies its result the same way the plain
/// primitive-output wrapper does.
pub fn should_stringify_primitive_output(output: &ReturnType) -> bool {
    let ReturnType::Type(_, ty) = output else {
        return false;
    };

    let Type::Path(path) = ty.as_ref() else {
        return false;
    };

    if path.qself.is_some() || path.path.segments.len() != 1 {
        return false;
    }

    let ident = path.path.segments[0].ident.to_string();
    matches!(
        ident.as_str(),
        "bool"
            | "i8"
            | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "isize"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "usize"
            | "f32"
            | "f64"
    )
}

#[cfg(test)]
mod tests {
    use quote::quote;

    use super::{positional_format_string, route_macro};

    #[test]
    fn positional_plain_params() {
        assert_eq!(positional_format_string("/posts/{id}"), "/posts/{}");
    }

    #[test]
    fn positional_regex_constrained_params() {
        assert_eq!(positional_format_string("/users/{id:[0-9]+}"), "/users/{}");
    }

    #[test]
    fn positional_multiple_params() {
        assert_eq!(
            positional_format_string("/posts/{year}/{slug}"),
            "/posts/{}/{}"
        );
    }

    #[test]
    fn positional_static_path() {
        assert_eq!(positional_format_string("/hello"), "/hello");
    }

    #[test]
    fn positional_catch_all_param() {
        assert_eq!(positional_format_string("/files/{*path}"), "/files/{}");
    }

    #[test]
    fn positional_hyphenated_param() {
        assert_eq!(positional_format_string("/items/{item-id}"), "/items/{}");
    }

    #[test]
    fn positional_regex_with_quantifier_braces() {
        // Regex quantifiers like {1,3} must not end the outer capture early.
        assert_eq!(
            positional_format_string("/users/{id:[0-9]{1,3}}"),
            "/users/{}"
        );
    }

    #[test]
    fn positional_keyword_param() {
        // Keyword params like `type` must produce a valid positional placeholder.
        assert_eq!(positional_format_string("/items/{type}"), "/items/{}");
    }

    #[test]
    fn positional_escaped_braces_pass_through() {
        // `{{` / `}}` are literal braces in the route, not parameters.
        assert_eq!(positional_format_string("/{{hello}}"), "/{{hello}}");
        // Escaped brace followed by a real param.
        assert_eq!(
            positional_format_string("/{{literal}}/{id}"),
            "/{{literal}}/{}"
        );
    }

    #[test]
    fn route_macro_attr_parse_error_still_emits_handler_and_companion() {
        // `#[get()]` -- a dropped path literal. Regression test for the
        // cascade in `route_attr_error_cascades_through_routes.rs`: without
        // re-emitting `index` and a stub `__autumn_route_info_index`, this
        // handler vanishes from the module and `routes![index]` piles on two
        // more "cannot find" errors, the second naming an internal macro
        // symbol (docs/reports/echo-audit-run.md).
        let generated = route_macro(
            "GET",
            "get",
            quote! {},
            quote! {
                async fn index() -> &'static str { "Hello!" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a bad route attribute must still be a compile error: {generated}"
        );
        assert!(
            generated.contains("fn index"),
            "the handler must survive the attribute error, or routes![index] \
             cannot find `index`: {generated}"
        );
        assert!(
            generated.contains("fn __autumn_route_info_index"),
            "the companion must survive the attribute error, or routes![index] \
             adds a second, confusing \"cannot find function\" error: {generated}"
        );
    }

    #[test]
    fn route_macro_attr_parse_error_strips_intercept_marker() {
        // Codex review, PR #2798: `#[intercept(...)]` is a route-macro-only
        // marker (`parse::extract_interceptors`), never its own registered
        // attribute macro. Left on the re-emitted handler it fails to
        // resolve, adding "cannot find attribute `intercept`" on top of the
        // real diagnostic -- defeating the one-error promise this whole
        // helper exists for.
        let generated = route_macro(
            "GET",
            "get",
            quote! {},
            quote! {
                #[intercept(MyLayer)]
                async fn index() -> &'static str { "Hello!" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("intercept"),
            "`#[intercept(...)]` must not survive onto the re-emitted handler: {generated}"
        );
        assert!(
            generated.contains("fn index") && generated.contains("fn __autumn_route_info_index"),
            "the handler and its companion must still survive: {generated}"
        );
    }

    #[test]
    fn route_macro_attr_parse_error_strips_api_doc_marker() {
        // Codex review, PR #2798, second round: `#[api_doc(...)]` *is* a real
        // registered attribute macro, but a caller who wrote
        // `use autumn_web::{get, routes};` (not the prelude) never imported
        // the bare `api_doc` name into scope, so re-emitting it unqualified
        // fails to resolve too -- a different "cannot find attribute" on top
        // of the real diagnostic. The successful path always consumes it via
        // `api_doc::extract` before emitting `input_fn`; this path must too.
        let generated = route_macro(
            "GET",
            "get",
            quote! {},
            quote! {
                #[api_doc(summary = "Fetch a user by id")]
                async fn index() -> &'static str { "Hello!" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("api_doc"),
            "`#[api_doc(...)]` must not survive onto the re-emitted handler: {generated}"
        );
        assert!(
            generated.contains("fn index") && generated.contains("fn __autumn_route_info_index"),
            "the handler and its companion must still survive: {generated}"
        );
    }

    #[test]
    fn route_macro_attr_parse_error_gates_the_native_stub_on_edge_routes() {
        // Codex review, PR #2798, third round: `::autumn_web::Route` (the
        // route-info stub's return type) never resolves on the wasm32
        // builds `#[edge]` compiles for (examples/edge-greeting's capsule
        // depends on autumn-edge, never autumn-web) -- the unconditional
        // stub would itself fail to compile there, and `edge_routes![show]`
        // would still be missing its own `__autumn_edge_route_show`
        // companion. Regression test, mirroring
        // route_macro_edge_cfg_gates_native_companions above: the route-info
        // stub gets the same wasm32 cfg gate as the successful path's native
        // companions, and an unconditional edge-route stub stands in for
        // `edge_routes![]`.
        let generated = route_macro(
            "GET",
            "get",
            quote! {},
            quote! {
                #[edge]
                async fn show() -> &'static str { "post" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a bad route attribute on an edge route must still be a compile error: {generated}"
        );
        let gate = "# [cfg (not (target_arch = \"wasm32\"))]";
        assert!(
            generated.contains(&format!(
                "{gate} # [doc (hidden)] fn __autumn_route_info_show"
            )),
            "the route-info stub must be gated off wasm32, same as the successful path: \
             {generated}"
        );
        assert!(
            generated.contains("fn __autumn_edge_route_show () -> :: autumn_edge :: EdgeRoute"),
            "an unconditional edge-route stub must stand in for edge_routes![show]: {generated}"
        );
    }

    #[test]
    fn route_macro_attr_parse_error_survives_a_guard_expanded_above_it() {
        // Codex review, PR #2798: `#[secured]` written above a malformed
        // route attribute has already expanded into its gate struct/impl
        // followed by the handler by the time route_macro runs -- `item`
        // is that whole sequence, not a bare function. Regression test that
        // `emit_with_attr_parse_error` uses `split_leading_items_and_fn`
        // (the same helper the successful path relies on) rather than
        // assuming a bare `ItemFn` and silently dropping to the "not a
        // function" fallback, which would re-emit the gate item but never
        // build the `__autumn_route_info_*` stub.
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                async fn create() -> &'static str { "ok" }
            },
        );
        let generated = route_macro("POST", "post", quote! {}, secured).to_string();

        assert!(
            generated.contains("compile_error"),
            "a bad route attribute above an expanded guard must still be a compile error: \
             {generated}"
        );
        assert!(
            generated.contains("fn create"),
            "the handler must survive alongside the guard's gate item: {generated}"
        );
        assert!(
            generated.contains("fn __autumn_route_info_create"),
            "the companion must still be built even though `item` carries leading items: \
             {generated}"
        );
    }

    #[test]
    fn route_macro_string_literal_replay_guard_still_injects_layer() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                async fn create_item() -> &'static str {
                    let _ = "__AUTUMN_IDEMPOTENCY_REPLAY_GUARD";
                    "created"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("IdempotencyReplayLayer"),
            "plain handler text must not be mistaken for a generated replay stop: {generated}"
        );
    }

    #[test]
    fn route_macro_interceptor_uses_direct_idempotency() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                #[intercept(TenantLayer)]
                async fn create_item() -> &'static str {
                    "created"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteIdempotency :: Direct"),
            "intercepted routes must fail closed when replay scope is not explicit: {generated}"
        );
        assert!(
            !generated.contains("IdempotencyReplayLayer"),
            "intercepted routes must not advertise an implicit replay stop: {generated}"
        );
    }

    #[test]
    fn route_macro_suppresses_replay_layer_when_throttle_attribute_present() {
        // Ordering A: `#[post]` outermost, `#[throttle]` still an attribute below
        // it. The route macro detects the attribute (`has_throttle_guard`) and
        // must NOT add the outer IdempotencyReplayLayer — replay handling moves
        // into the (later-expanded) throttle body, after the throttle check.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                #[throttle(limit = 1, per = "60s", key = "ip")]
                async fn create_item() -> &'static str { "created" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("IdempotencyReplayLayer"),
            "throttled route (route outermost) must not add the outer replay layer: {generated}"
        );
    }

    #[test]
    fn route_macro_suppresses_replay_layer_for_expanded_throttle_prologue() {
        // Ordering B: `#[throttle]` written ABOVE `#[post]`, so the throttle macro
        // expands FIRST — it removes its own attribute and injects the throttle
        // prologue into the body. The route macro no longer sees a `#[throttle]`
        // attribute and must instead recognize the generated throttle prologue in
        // the body to suppress the outer IdempotencyReplayLayer; otherwise a
        // cached replay would be served before the in-body throttle check.
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 1, per = "60s", key = "ip" },
            quote! {
                async fn create_item() -> &'static str { "created" }
            },
        );
        let generated = route_macro("POST", "post", quote! { "/items" }, throttled).to_string();

        assert!(
            !generated.contains("IdempotencyReplayLayer"),
            "throttled route (throttle expanded first) must not add the outer replay layer: \
             {generated}"
        );
    }

    // ── OpenAPI response schema survives guard-outermost expansion (#1677) ──
    //
    // All four body guards rewrite `sig.output` to `Response` when they
    // expand. When a guard is written ABOVE the route attribute it expands
    // FIRST, so by the time the route macro runs and calls
    // `infer_response_body`, the real `Json<T>` return type is already gone
    // from `sig.output` — unless the route macro recovers it from the
    // `__autumn_inner: T` binding the guard left behind.

    #[test]
    fn route_macro_infers_response_schema_when_throttle_expands_first() {
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 5, per = "1m", key = "ip" },
            quote! {
                async fn create() -> ::autumn_web::reexports::axum::Json<Created> { todo!() }
            },
        );
        // #2488 redesigned throttle_macro to emit a SIBLING gate item (a
        // marker struct + its FromRequestParts impl) alongside the
        // transformed handler fn, rather than a single transformed item —
        // see param_helpers::extract_fn_item's doc comment. The real
        // compiler re-invokes a still-pending attribute (here, #[post])
        // with only the one fn item's tokens, never the sibling gate item
        // too, so the test has to reproduce that same slice.
        let throttled_fn = crate::param_helpers::extract_fn_item(throttled, "create");
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/users" },
            quote! { #throttled_fn },
        )
        .to_string();

        assert!(
            generated.contains("response : :: core :: option :: Option :: Some")
                && generated.contains("\"Created\""),
            "a #[throttle]-above-#[post] route must still document its Json<Created> response: \
             {generated}"
        );
    }

    #[test]
    fn route_macro_infers_response_schema_when_secured_expands_first() {
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                async fn create() -> ::autumn_web::reexports::axum::Json<Created> { todo!() }
            },
        );
        // See the comment in the throttle sibling test above: secured_macro
        // returns the gate item and the transformed fn as siblings now, so
        // only the fn item goes on to route_macro.
        let secured_fn = crate::param_helpers::extract_fn_item(secured, "create");
        let generated =
            route_macro("POST", "post", quote! { "/users" }, quote! { #secured_fn }).to_string();

        assert!(
            generated.contains("response : :: core :: option :: Option :: Some")
                && generated.contains("\"Created\""),
            "a #[secured]-above-#[post] route must still document its Json<Created> response: \
             {generated}"
        );
    }

    #[test]
    fn route_macro_infers_response_schema_when_step_up_expands_first() {
        let stepped_up = crate::step_up::step_up_macro(
            quote! {},
            quote! {
                async fn create() -> ::autumn_web::reexports::axum::Json<Created> { todo!() }
            },
        );
        // See the comment in the throttle sibling test above: step_up_macro
        // returns the gate item and the transformed fn as siblings now, so
        // only the fn item goes on to route_macro.
        let stepped_up_fn = crate::param_helpers::extract_fn_item(stepped_up, "create");
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/users" },
            quote! { #stepped_up_fn },
        )
        .to_string();

        assert!(
            generated.contains("response : :: core :: option :: Option :: Some")
                && generated.contains("\"Created\""),
            "a #[step_up]-above-#[post] route must still document its Json<Created> response: \
             {generated}"
        );
    }

    #[test]
    fn route_macro_infers_response_schema_when_authorize_expands_first() {
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> ::autumn_web::reexports::axum::Json<Created> {
                    todo!()
                }
            },
        );
        let generated =
            route_macro("POST", "post", quote! { "/notes/{id}" }, authorized).to_string();

        assert!(
            generated.contains("response : :: core :: option :: Option :: Some")
                && generated.contains("\"Created\""),
            "an #[authorize]-above-#[post] route must still document its Json<Created> response: \
             {generated}"
        );
    }

    #[test]
    fn route_macro_infers_response_schema_under_stacked_guards_above_route() {
        // `#[secured]` above `#[throttle]` above `#[post]`: throttle expands
        // first and captures the real type, then secured wraps throttle's
        // whole generated body one level deeper. Only the innermost
        // `__autumn_inner` binding carries `Json<Created>` — the outer one
        // reads `Response`. Each guard returns its gate item and the
        // transformed fn as SIBLINGS (#2488), and the real compiler only
        // ever re-invokes the next still-pending attribute with that one fn
        // item's tokens — so extract_fn_item has to run after every hop,
        // not just before the final one into route_macro.
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 5, per = "1m", key = "ip" },
            quote! {
                async fn create() -> ::autumn_web::reexports::axum::Json<Created> { todo!() }
            },
        );
        let throttled_fn = crate::param_helpers::extract_fn_item(throttled, "create");
        let secured = crate::secured::secured_macro(quote! { "admin" }, quote! { #throttled_fn });
        let secured_fn = crate::param_helpers::extract_fn_item(secured, "create");
        let generated =
            route_macro("POST", "post", quote! { "/users" }, quote! { #secured_fn }).to_string();

        assert!(
            generated.contains("response : :: core :: option :: Option :: Some")
                && generated.contains("\"Created\""),
            "stacked guards above the route macro must not drop the response schema: {generated}"
        );
    }

    #[test]
    fn route_macro_parses_api_version_and_sunset_opt_out() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/items", api_version = "v1", sunset_opt_out = true },
            quote! {
                async fn get_items() -> &'static str {
                    "items"
                }
            },
        )
        .to_string();

        // Check that api_version and sunset_opt_out are generated in Route constructor
        assert!(
            generated.contains("api_version"),
            "should generate api_version field: {generated}"
        );
        assert!(
            generated.contains("sunset_opt_out"),
            "should generate sunset_opt_out field: {generated}"
        );
    }

    #[test]
    fn route_macro_defaults_timeout_to_inherit() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/items" },
            quote! {
                async fn get_items() -> &'static str { "items" }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteTimeout :: Inherit"),
            "routes without a timeout attribute must inherit the global deadline: {generated}"
        );
    }

    #[test]
    fn route_macro_parses_timeout_ms_override() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/export", timeout_ms = 120000 },
            quote! {
                async fn export() -> &'static str { "report" }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteTimeout :: Override"),
            "timeout_ms must emit a RouteTimeout::Override: {generated}"
        );
        assert!(
            generated.contains("from_millis") && generated.contains("120000"),
            "override must carry the configured millisecond budget: {generated}"
        );
    }

    #[test]
    fn route_macro_defaults_public_false() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/widgets" },
            quote! { async fn create_widget() -> &'static str { "ok" } },
        )
        .to_string();
        assert!(
            generated.contains("public : false"),
            "an unannotated route must record public = false: {generated}"
        );
        // The handler's module path is captured for audit diagnostics.
        assert!(generated.contains("module_path"));
    }

    #[test]
    fn route_macro_marks_public_when_public_attribute_present() {
        // Ordering A: `#[post]` outermost, `#[public]` still an attribute below.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/pricing" },
            quote! {
                #[public]
                async fn pricing() -> &'static str { "free" }
            },
        )
        .to_string();
        assert!(
            generated.contains("public : true"),
            "a #[public] handler must record public = true: {generated}"
        );
    }

    #[test]
    fn route_macro_marks_public_from_expanded_marker() {
        // Ordering B: `#[public]` written above `#[post]`, so it expands first and
        // injects the `__AUTUMN_PUBLIC` marker into the body; the route macro must
        // recognize the marker.
        let public_fn = crate::public::public_macro(
            quote! {},
            quote! { async fn pricing() -> &'static str { "free" } },
        );
        let generated = route_macro("POST", "post", quote! { "/pricing" }, public_fn).to_string();
        assert!(
            generated.contains("public : true"),
            "a route macro over an expanded #[public] marker must record public = true: {generated}"
        );
    }

    // ── seo(...) route-level defaults (#1182) ───────────────────────────────

    #[test]
    fn route_macro_defaults_seo_to_empty() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("SeoRouteDefaults :: EMPTY"),
            "a route without seo(...) must record the empty defaults: {generated}"
        );
    }

    #[test]
    fn route_macro_emits_declared_seo_defaults() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "About", description = "Learn about us") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("with_title (\"About\")"),
            "seo(title = ...) must populate the title default: {generated}"
        );
        assert!(
            generated.contains("with_description (\"Learn about us\")"),
            "seo(description = ...) must populate the description default: {generated}"
        );
        assert!(
            generated.contains("SeoRouteDefaults :: EMPTY . with_title"),
            "unset seo keys must fall back to the empty defaults: {generated}"
        );
    }

    #[test]
    fn route_macro_seo_composes_with_other_keys() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "About"), name = "about_page", timeout_ms = 500 },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("with_title (\"About\")"),
            "seo(...) must parse when it precedes other keys: {generated}"
        );
        assert!(
            generated.contains("RouteTimeout :: Override"),
            "keys after seo(...) must still parse: {generated}"
        );
        assert!(
            generated.contains("__autumn_path_about_page"),
            "name override after seo(...) must still apply: {generated}"
        );
    }

    #[test]
    fn route_macro_never_emits_a_seo_struct_literal() {
        // The expansion lands in the *user's* crate, so a struct literal there
        // would pin `SeoRouteDefaults` as exhaustively constructible forever —
        // a fourteenth SEO key could then never be added without a breaking
        // change — and would trip `clippy::needless_update` once every key is
        // spelled out. Chained `const fn` setters avoid both.
        let generated = route_macro(
            "GET",
            "get",
            quote! {
                "/full",
                seo(
                    title = "t",
                    description = "d",
                    canonical = "c",
                    og_title = "ot",
                    og_description = "od",
                    og_image = "oi",
                    og_type = "oty",
                    og_url = "ou",
                    twitter_card = "tc",
                    twitter_title = "tt",
                    twitter_description = "td",
                    twitter_image = "ti",
                    robots = "noindex"
                )
            },
            quote! { async fn full() -> &'static str { "full" } },
        )
        .to_string();

        assert!(
            generated.contains("with_robots (\"noindex\")"),
            "every declared key must still be emitted: {generated}"
        );
        assert!(
            !generated.contains("SeoRouteDefaults {"),
            "the expansion must not construct SeoRouteDefaults by struct literal: {generated}"
        );
        // Scoped to the emitted `seo:` value. The surrounding expansion
        // legitimately contains `..Default::default()` in other literals, so
        // asserting over the whole token stream would be a trap for future
        // edits (the `#[static_get]` expansion already trips it).
        let seo_value = generated
            .split("seo : ")
            .nth(1)
            .and_then(|rest| rest.split(',').next())
            .expect("expansion should assign the seo field");
        assert!(
            seo_value.contains("SeoRouteDefaults :: EMPTY"),
            "sanity: seo value should build from EMPTY: {seo_value}"
        );
        assert!(
            !seo_value.contains(".."),
            "the seo value must not use struct-update syntax: {seo_value}"
        );
    }

    #[test]
    fn route_macro_rejects_empty_seo_group() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo() },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "an empty seo() must be a compile error, not a silent no-op: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_repeated_seo_argument() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "A"), seo(og_type = "website") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a second seo(...) argument must be a compile error: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_seo_keys_without_separating_comma() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "A" og_type = "website") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a missing comma must be rejected rather than dropping later keys: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_unknown_seo_key() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(titel = "About") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "an unknown seo key must be a compile error: {generated}"
        );
        assert!(
            generated.contains("titel"),
            "the error must name the offending key: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_duplicate_seo_key() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = "A", title = "B") },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a duplicate seo key must be a compile error: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_non_string_seo_value() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo(title = 42) },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a non-string seo value must be a compile error: {generated}"
        );
    }

    #[test]
    fn route_macro_rejects_seo_without_parentheses() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about", seo = "title" },
            quote! { async fn about() -> &'static str { "about" } },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "`seo = ...` must be rejected in favour of `seo(...)`: {generated}"
        );
    }

    #[test]
    fn route_macro_parses_timeout_off_disabled() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stream", timeout = "off" },
            quote! {
                async fn stream() -> &'static str { "data" }
            },
        )
        .to_string();

        assert!(
            generated.contains("RouteTimeout :: Disabled"),
            "timeout = \"off\" must emit RouteTimeout::Disabled: {generated}"
        );
    }

    // ── criticality (#3068) ─────────────────────────────────────────────────

    #[test]
    fn route_macro_defaults_criticality_to_default() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/x" },
            quote! { async fn x() -> &'static str { "x" } },
        )
        .to_string();
        assert!(
            generated.contains("criticality : :: autumn_web :: Criticality :: Default"),
            "{generated}"
        );
    }

    #[test]
    fn route_macro_parses_each_criticality() {
        for (value, variant) in [
            ("critical", "Critical"),
            ("default", "Default"),
            ("sheddable", "Sheddable"),
        ] {
            let generated = route_macro(
                "POST",
                "post",
                quote! { "/x", criticality = #value },
                quote! { async fn x() -> &'static str { "x" } },
            )
            .to_string();
            assert!(
                generated.contains(&format!("Criticality :: {variant}")),
                "criticality = {value:?}: {generated}"
            );
        }
    }

    #[test]
    fn route_macro_rejects_an_unknown_criticality() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/x", criticality = "urgent" },
            quote! { async fn x() -> &'static str { "x" } },
        )
        .to_string();
        assert!(generated.contains("compile_error"), "{generated}");
        assert!(
            generated.contains("invalid `criticality` value"),
            "{generated}"
        );
    }

    // ── idempotent = false ──────────────────────────────────────────────────

    #[test]
    fn route_macro_defaults_to_the_idempotency_layer() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/x" },
            quote! { async fn x() -> &'static str { "x" } },
        )
        .to_string();
        assert!(
            generated.contains("RouteIdempotency :: ReplayThroughInner"),
            "{generated}"
        );
    }

    #[test]
    fn route_macro_parses_idempotent_false_as_off() {
        for attr in [
            quote! { "/x", idempotent = false },
            // The opt-out wins over the intercept-driven `Direct` choice.
            quote! { "/x", criticality = "critical", idempotent = false },
        ] {
            let generated = route_macro(
                "POST",
                "post",
                attr.clone(),
                quote! {
                    #[intercept(TenantLayer)]
                    async fn x() -> &'static str { "x" }
                },
            )
            .to_string();
            assert!(
                generated.contains("RouteIdempotency :: Off"),
                "{attr}: {generated}"
            );
        }
    }

    #[test]
    fn route_macro_accepts_idempotent_true_as_the_default() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/x", idempotent = true },
            quote! { async fn x() -> &'static str { "x" } },
        )
        .to_string();
        assert!(
            generated.contains("RouteIdempotency :: ReplayThroughInner"),
            "{generated}"
        );
    }

    #[test]
    fn route_macro_rejects_a_non_bool_idempotent() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/x", idempotent = "no" },
            quote! { async fn x() -> &'static str { "x" } },
        )
        .to_string();
        assert!(generated.contains("compile_error"), "{generated}");
    }

    // ── #[authorize] bindings recorded in ApiDoc (#1627) ────────────────────

    #[test]
    fn route_macro_emits_empty_authorize_bindings_by_default() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/widgets" },
            quote! { async fn create_widget() -> &'static str { "ok" } },
        )
        .to_string();

        assert!(
            generated.contains("authorize_bindings : & []"),
            "an unguarded route must record no authorization bindings: {generated}"
        );
    }

    #[test]
    fn route_macro_records_authorize_binding_when_attribute_present() {
        // Ordering A: `#[post]` outermost, `#[authorize]` still an attribute
        // below it, so the route macro reads the arguments straight off the
        // unexpanded attribute.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/notes/{id}" },
            quote! {
                #[authorize("update", resource = Note)]
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        )
        .to_string();

        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "an #[authorize] attribute must record its (action, resource) binding: {generated}"
        );
    }

    #[test]
    fn route_macro_records_authorize_binding_from_expanded_marker() {
        // Ordering B: `#[authorize]` written ABOVE `#[post]`, so it expands
        // first, removes its own attribute and leaves only the generated body.
        // The binding must survive in the marker const it injects.
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let generated =
            route_macro("POST", "post", quote! { "/notes/{id}" }, authorized).to_string();

        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "an already-expanded #[authorize] must still record its binding: {generated}"
        );
    }

    #[test]
    fn route_macro_records_authorize_binding_under_secured_wrapper() {
        // `#[authorize]` above `#[secured]` above `#[post]`: authorize expands
        // first, then secured wraps that whole body in
        // `(async move { … }).await`, burying the marker one level down. The
        // walk must descend the generated wrapper instead of stopping at the
        // outermost statement list.
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let secured = crate::secured::secured_macro(quote! { "admin" }, authorized);
        let secured_fn = crate::param_helpers::extract_fn_item(secured, "update_note");
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/notes/{id}" },
            quote! { #secured_fn },
        )
        .to_string();

        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "a binding nested inside a #[secured] wrapper must not be lost: {generated}"
        );
    }

    #[test]
    fn route_macro_records_all_bindings_for_stacked_authorize_attributes() {
        // Every attribute contributes: the existing `policy` boolean collapses
        // N bindings into one flag, so the list must not do the same.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/notes/{id}" },
            quote! {
                #[authorize("update", resource = Note)]
                #[authorize("publish", resource = Note)]
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        )
        .to_string();

        let update = generated
            .find(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#)
            .unwrap_or_else(|| {
                panic!("the first stacked #[authorize] must record a binding: {generated}")
            });
        let publish = generated
            .find(r#"AuthorizeBinding { action : "publish" , resource : "Note" }"#)
            .unwrap_or_else(|| {
                panic!("the second stacked #[authorize] must record a binding: {generated}")
            });
        assert!(
            update < publish,
            "stacked bindings must be recorded in source order: {generated}"
        );
    }

    #[test]
    fn route_macro_preserves_secured_roles_when_authorize_wraps_them() {
        // `#[secured("admin")]` above `#[authorize]` above `#[post]`: secured
        // expands first and leaves its role marker in the body; authorize then
        // wraps that body in `let __autumn_inner: T = (async move { … }).await;`.
        // The roles walk must descend that generated wrapper — otherwise the
        // route silently reports `required_roles: &[]` and a `provable` manifest
        // dimension under-states the posture.
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let secured_fn = crate::param_helpers::extract_fn_item(secured, "update_note");
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! { #secured_fn },
        );
        let generated =
            route_macro("POST", "post", quote! { "/notes/{id}" }, authorized).to_string();

        assert!(
            generated.contains(r#"required_roles : & ["admin"]"#),
            "roles from a #[secured] buried under an #[authorize] wrapper must survive: \
             {generated}"
        );
        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "…and the authorize binding must be recorded alongside them: {generated}"
        );
    }

    #[test]
    fn route_macro_preserves_secured_roles_when_authorize_is_still_an_attribute() {
        // The remaining ordering of {secured, route, authorize}: `#[secured]`
        // ABOVE `#[post]` (already expanded into markers) with `#[authorize]`
        // BELOW it (still a live attribute). The marker read must not be
        // short-circuited by the live-authorize fallback — both idioms are the
        // documented house style, and losing the roles here means deleting the
        // `#[secured(...)]` line produces zero manifest diff on a `provable`
        // dimension.
        let secured = crate::secured::secured_macro(
            quote! { "admin", scopes = ["notes:write"] },
            quote! {
                #[authorize("update", resource = Note)]
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let secured_fn = crate::param_helpers::extract_fn_item(secured, "update_note");
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/notes/{id}" },
            quote! { #secured_fn },
        )
        .to_string();

        assert!(
            generated.contains(r#"required_roles : & ["admin"]"#),
            "roles from an expanded #[secured] must survive a live #[authorize] attribute: \
             {generated}"
        );
        assert!(
            generated.contains(r#"required_scopes : & ["notes:write"]"#),
            "scopes must survive alongside the roles: {generated}"
        );
        assert!(
            generated.contains(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#),
            "…and the authorize binding must be recorded alongside them: {generated}"
        );
    }

    #[test]
    fn route_macro_orders_marker_binding_before_live_attribute() {
        // Mixed arrangement: `#[authorize(A)]` ABOVE `#[post]` (already
        // expanded into a marker by the time the route macro runs) and
        // `#[authorize(B)]` BELOW it (still a live attribute). A is higher in
        // the source than B, so the recorded order must be [A, B] — the marker
        // before the attribute, not the collection-mechanism order.
        let authorized = crate::authorize::authorize_macro(
            quote! { "update", resource = Note },
            quote! {
                async fn update_note(note: Note) -> &'static str { "ok" }
            },
        );
        let mixed = quote! {
            #[authorize("publish", resource = Note)]
            #authorized
        };
        let generated = route_macro("POST", "post", quote! { "/notes/{id}" }, mixed).to_string();

        let update = generated
            .find(r#"AuthorizeBinding { action : "update" , resource : "Note" }"#)
            .unwrap_or_else(|| panic!("the marker binding must be recorded: {generated}"));
        let publish = generated
            .find(r#"AuthorizeBinding { action : "publish" , resource : "Note" }"#)
            .unwrap_or_else(|| panic!("the live-attribute binding must be recorded: {generated}"));
        assert!(
            update < publish,
            "the marker comes from the attribute above the route macro, so it precedes the \
             live attribute below it in source order: {generated}"
        );
    }

    // ── `#[edge]` opt-in (#1790) ────────────────────────────────────────────

    /// The edge companion is emitted last, so everything from its `fn` keyword
    /// to the end of the stream *is* the companion. Comparing that slice across
    /// two attribute stackings proves detection produced the same route, not
    /// merely that both stackings emitted *something*.
    fn edge_companion_fragment(generated: &str) -> &str {
        let start = generated
            .find("fn __autumn_edge_route_")
            .unwrap_or_else(|| panic!("expansion should emit an edge companion: {generated}"));
        &generated[start..]
    }

    #[test]
    fn route_macro_edge_get_emits_edge_companion() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        assert!(
            generated.contains("fn __autumn_edge_route_greet () -> :: autumn_edge :: EdgeRoute"),
            "an #[edge] GET route must emit the edge companion: {generated}"
        );
        assert!(
            generated.contains(":: autumn_edge :: edge_get (greet)"),
            "the edge companion must adapt the handler through edge_get: {generated}"
        );
        assert!(
            generated.contains(":: autumn_edge :: reexports :: http :: Method :: GET"),
            "the edge companion must carry the GET method: {generated}"
        );
        assert!(
            generated.contains("path : \"/greet\""),
            "the edge companion must carry the route path: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_companion_mounts_the_primitive_wrapper() {
        // A primitive-returning handler is mounted natively through a
        // `.to_string()` wrapper (primitives are not `IntoResponse`). The edge
        // companion must mount the *same* wrapper, or the two lanes would
        // disagree about what the response body is — and `edge_get(stats)`
        // would not even compile.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stats" },
            quote! {
                #[edge]
                async fn stats() -> usize { 42 }
            },
        )
        .to_string();

        assert!(
            generated.contains(":: autumn_edge :: edge_get (__autumn_primitive_handler_stats)"),
            "the edge companion must mount the primitive wrapper: {generated}"
        );
        // …and that wrapper is pure std, so it stays available on wasm32.
        let wrapper = generated
            .find("async fn __autumn_primitive_handler_stats")
            .unwrap_or_else(|| panic!("the primitive wrapper must be emitted: {generated}"));
        assert!(
            !generated[..wrapper].contains("cfg"),
            "the primitive wrapper references no autumn_web item, so it is not gated: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_cfg_gates_native_companions() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts/{id}" },
            quote! {
                #[edge]
                async fn show(id: Path<String>) -> &'static str { "post" }
            },
        )
        .to_string();

        // Native companions reference `::autumn_web`, which never compiles for
        // wasm32 — they must be gated off the edge target.
        let gate = "# [cfg (not (target_arch = \"wasm32\"))]";
        assert!(
            generated.contains(&format!(
                "{gate} # [doc (hidden)] fn __autumn_route_info_show"
            )),
            "the route-info companion must be gated off wasm32: {generated}"
        );
        assert!(
            generated.contains(&format!(
                "{gate} :: autumn_web :: reexports :: inventory :: submit !"
            )),
            "the architecture-graph node references ::autumn_web too (#1747): {generated}"
        );
        assert_eq!(
            generated.matches(gate).count(),
            2,
            "exactly the two native companions are gated: {generated}"
        );
        // The handler itself and the edge companion stay unconditional.
        assert!(
            !edge_companion_fragment(&generated).contains("cfg"),
            "the edge companion must not be gated: {generated}"
        );
    }

    /// The path helper of an `#[edge]` route compiles on both lanes, so a
    /// handler that builds a link does not change for the edge (#1790).
    #[test]
    fn route_macro_edge_path_helper_uses_autumn_edge_and_is_not_gated() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/files/{id}/{*rest}" },
            quote! {
                #[edge]
                async fn file() -> &'static str { "f" }
            },
        )
        .to_string();

        assert!(
            generated.contains("pub fn __autumn_path_file"),
            "the path helper must be emitted: {generated}"
        );
        assert!(
            !generated.contains(
                "# [cfg (not (target_arch = \"wasm32\"))] # [doc (hidden)] pub fn __autumn_path_file"
            ),
            "the edge path helper must not be gated off wasm32: {generated}"
        );
        assert!(
            generated.contains(":: autumn_edge :: paths :: encode_path_segment (r#id)"),
            "a segment must use the edge encoder: {generated}"
        );
        assert!(
            generated.contains(":: autumn_edge :: paths :: encode_catch_all_param (r#rest)"),
            "a catch-all must use the edge encoder: {generated}"
        );
        assert!(
            !generated.contains(":: autumn_web :: paths"),
            "the edge path helper must not name autumn_web: {generated}"
        );
    }

    /// A plain route keeps the `autumn_web` encoders.
    #[test]
    fn route_macro_plain_path_helper_keeps_autumn_web() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/files/{id}" },
            quote! {
                async fn file() -> &'static str { "f" }
            },
        )
        .to_string();

        assert!(
            generated.contains(":: autumn_web :: paths :: encode_path_segment (r#id)"),
            "{generated}"
        );
        assert!(!generated.contains("autumn_edge"), "{generated}");
    }

    #[test]
    fn route_macro_edge_path_helper_alias_is_not_gated() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet", name = "greeting" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        assert!(
            generated.contains(
                "} # [doc (hidden)] pub use self :: __autumn_path_greeting as __autumn_path_greet ;"
            ),
            "the alias re-exports an ungated helper, so it is not gated: {generated}"
        );
        assert_eq!(
            generated
                .matches("# [cfg (not (target_arch = \"wasm32\"))]")
                .count(),
            2,
            "only route info and the graph node are native-only: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_detection_is_identical_for_both_attribute_orders() {
        // Ordering A: `#[get]` outermost, `#[edge]` still a live attribute.
        let below = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        // Ordering B: `#[edge]` above `#[get]`, so it expanded first and left
        // only the `__AUTUMN_EDGE` marker in the body.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! { async fn greet() -> &'static str { "hi" } },
        );
        let above = route_macro("GET", "get", quote! { "/greet" }, edged).to_string();

        assert_eq!(
            edge_companion_fragment(&below),
            edge_companion_fragment(&above),
            "both stacking orders must produce the same edge route"
        );
    }

    #[test]
    fn route_macro_edge_needs_identity_populates_the_needs_slice() {
        let edged = crate::edge::edge_macro(
            quote! { needs(kv, identity) },
            quote! { async fn me(identity: EdgeIdentity) -> String { identity.user_id().as_str().to_owned() } },
        );
        let generated = route_macro("GET", "get", quote! { "/me" }, edged).to_string();

        assert!(
            generated.contains(
                "needs : & [:: autumn_edge :: EdgeCapability :: Kv , :: autumn_edge :: EdgeCapability :: Identity]"
            ),
            "needs(identity) must declare the Identity capability on the edge route: {generated}"
        );
        assert!(!generated.contains("compile_error"), "{generated}");
    }

    #[test]
    fn route_macro_edge_rejects_undeclared_edge_identity() {
        // Without `needs(identity)` the runtime cannot refuse an
        // unauthenticated request before dispatch.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! { async fn me(identity: EdgeIdentity) -> String { identity.user_id().as_str().to_owned() } },
        );
        let generated = route_macro("GET", "get", quote! { "/me" }, edged).to_string();
        assert!(generated.contains("compile_error"), "{generated}");
        assert!(
            generated.contains("needs(identity)"),
            "the error must name the missing declaration: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_needs_kv_populates_the_needs_slice() {
        let edged = crate::edge::edge_macro(
            quote! { needs(kv) },
            quote! { async fn note() -> &'static str { "note" } },
        );
        let generated = route_macro("GET", "get", quote! { "/note" }, edged).to_string();

        assert!(
            generated.contains("needs : & [:: autumn_edge :: EdgeCapability :: Kv]"),
            "needs(kv) must declare the Kv capability on the edge route: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_needs_kv_is_read_from_a_live_attribute_too() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/note" },
            quote! {
                #[edge(needs(kv))]
                async fn note() -> &'static str { "note" }
            },
        )
        .to_string();

        assert!(
            generated.contains("needs : & [:: autumn_edge :: EdgeCapability :: Kv]"),
            "a live #[edge(needs(kv))] attribute must declare the capability: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_without_needs_declares_no_capabilities() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                #[edge]
                async fn greet() -> &'static str { "hi" }
            },
        )
        .to_string();

        assert!(
            generated.contains("needs : & []"),
            "a bare #[edge] route must declare no capabilities: {generated}"
        );
    }

    #[test]
    fn route_macro_non_edge_expansion_is_untouched() {
        // The edge work must be inert for every route that did not opt in:
        // no cfg attribute, no edge companion, nothing.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts/{id}", name = "post_page" },
            quote! {
                async fn show(id: Path<String>) -> &'static str { "post" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("cfg"),
            "a non-edge route must not gain a cfg attribute: {generated}"
        );
        assert!(
            !generated.contains("__autumn_edge_route_"),
            "a non-edge route must not gain an edge companion: {generated}"
        );
        assert!(
            !generated.contains("autumn_edge"),
            "a non-edge route must not reference autumn_edge at all: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_on_post_is_a_compile_error() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                #[edge]
                async fn create_item() -> &'static str { "created" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] on a write-path route must be rejected: {generated}"
        );
        assert!(
            generated.contains("only supported on"),
            "the error must say the edge lane is GET-only: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_secured_attribute_is_a_compile_error() {
        // Ordering A: both guards still live attributes below `#[get]`.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/dashboard" },
            quote! {
                #[edge]
                #[secured]
                async fn dashboard() -> &'static str { "dash" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[secured] must be rejected: {generated}"
        );
        assert!(
            generated.contains("no session or auth state"),
            "the error must explain why the edge lane cannot authenticate: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_expanded_secured_marker_is_a_compile_error() {
        // Ordering B: `#[secured]` above `#[get]` (already expanded into
        // markers), `#[edge]` still a live attribute below it.
        let secured = crate::secured::secured_macro(
            quote! { "admin" },
            quote! {
                #[edge]
                async fn dashboard() -> &'static str { "dash" }
            },
        );
        let generated = route_macro("GET", "get", quote! { "/dashboard" }, secured).to_string();

        assert!(
            generated.contains("compile_error"),
            "an already-expanded #[secured] must still be detected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_marker_buried_under_secured_wrapper_is_a_compile_error() {
        // `#[edge]` above `#[secured]` above `#[get]`: edge expands first, then
        // secured buries its marker inside `(async move { … }).await`. Losing
        // the marker here would silently ship an authenticated route to the
        // edge lane.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! { async fn dashboard() -> &'static str { "dash" } },
        );
        let secured = crate::secured::secured_macro(quote! { "admin" }, edged);
        let generated = route_macro("GET", "get", quote! { "/dashboard" }, secured).to_string();

        assert!(
            generated.contains("compile_error"),
            "a buried #[edge] marker must still be detected next to #[secured]: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_intercept_is_a_compile_error() {
        // `#[intercept]` layers wrap only the native mount; the edge companion
        // mounts the bare handler, so allowing the pair would let the two
        // lanes serve different bytes. Refused whichever side of `#[get]` the
        // interceptor sits on.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stamped" },
            quote! {
                #[edge]
                #[intercept(StampLayer)]
                async fn stamped() -> &'static str { "stamped" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[intercept] must be rejected: {generated}"
        );
        assert!(
            generated.contains("origin-only tower middleware"),
            "the error must explain that interceptors do not cross into the capsule: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_marker_with_intercept_is_a_compile_error() {
        // Ordering B: `#[edge]` above `#[get]` (already expanded into its
        // marker const), `#[intercept]` still a live attribute.
        let edged = crate::edge::edge_macro(
            quote! {},
            quote! {
                #[intercept(StampLayer)]
                async fn stamped() -> &'static str { "stamped" }
            },
        );
        let generated = route_macro("GET", "get", quote! { "/stamped" }, edged).to_string();

        assert!(
            generated.contains("compile_error"),
            "an expanded #[edge] marker + live #[intercept] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_native_mount_strips_request_credentials() {
        // The wire runtime strips SENSITIVE_HEADERS before capsule dispatch;
        // the native mount must strip the same set so a HeaderMap-reading
        // handler observes identical headers on both substrates.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet/{name}" },
            quote! {
                #[edge]
                async fn greet(Path(name): Path<String>) -> String { name }
            },
        )
        .to_string();

        assert!(
            generated.contains("strip_request_credentials"),
            "the edge route's native mount must carry the credential strip: {generated}"
        );

        let plain = route_macro(
            "GET",
            "get",
            quote! { "/greet/{name}" },
            quote! {
                async fn greet(Path(name): Path<String>) -> String { name }
            },
        )
        .to_string();
        assert!(
            !plain.contains("strip_request_credentials"),
            "a non-edge route must not be rewritten: {plain}"
        );
    }

    #[test]
    fn route_macro_edge_with_extension_param_is_a_compile_error() {
        // `Extension<T>` satisfies the Handler bound for any state, so the
        // type system cannot keep it out of the capsule; the macro must.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/tenant" },
            quote! {
                #[edge]
                async fn tenant(ext: Extension<TenantConfig>) -> String { ext.name() }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + Extension<T> must be rejected: {generated}"
        );
        assert!(
            generated.contains("installs no request extensions"),
            "the error must explain the missing-extension 500 hazard: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_nested_extension_param_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/tenant" },
            quote! {
                #[edge]
                async fn tenant(ext: Option<axum::Extension<TenantConfig>>) -> String { greet() }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "a nested Extension extractor must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_cache_param_is_not_mistaken_for_an_extension() {
        // EdgeCache is delivered through an extension internally, but the
        // parameter type the author writes never names `Extension`.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/note/{key}" },
            quote! {
                #[edge(needs(kv))]
                async fn note(Path(key): Path<String>, cache: EdgeCache) -> String {
                    cache.get_string(&key).unwrap_or_default()
                }
            },
        )
        .to_string();

        assert!(
            !generated.contains("compile_error"),
            "EdgeCache must stay accepted: {generated}"
        );
    }

    #[test]
    fn route_macro_intercept_without_edge_is_unaffected() {
        // The refusal must not leak into the ordinary interceptor path.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/stamped" },
            quote! {
                #[intercept(StampLayer)]
                async fn stamped() -> &'static str { "stamped" }
            },
        )
        .to_string();

        assert!(
            !generated.contains("compile_error"),
            "#[intercept] without #[edge] must keep compiling: {generated}"
        );
        assert!(
            generated.contains("StampLayer"),
            "the interceptor layer must still wrap the native mount: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_throttle_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/search" },
            quote! {
                #[edge]
                #[throttle(limit = 1, per = "60s", key = "ip")]
                async fn search() -> &'static str { "results" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[throttle] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_expanded_throttle_marker_is_a_compile_error() {
        let throttled = crate::throttle::throttle_macro(
            quote! { limit = 1, per = "60s", key = "ip" },
            quote! {
                #[edge]
                async fn search() -> &'static str { "results" }
            },
        );
        let generated = route_macro("GET", "get", quote! { "/search" }, throttled).to_string();

        assert!(
            generated.contains("compile_error"),
            "an already-expanded #[throttle] must still be detected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_step_up_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/vault" },
            quote! {
                #[edge]
                #[step_up]
                async fn vault() -> &'static str { "secrets" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[step_up] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_edge_with_authorize_is_a_compile_error() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/notes/{id}" },
            quote! {
                #[edge]
                #[authorize("read", resource = Note)]
                async fn show_note(note: Note) -> &'static str { "note" }
            },
        )
        .to_string();

        assert!(
            generated.contains("compile_error"),
            "#[edge] + #[authorize] must be rejected: {generated}"
        );
    }

    #[test]
    fn route_macro_string_literal_edge_marker_is_not_an_edge_route() {
        // Handler *text* that merely spells the marker const must not opt the
        // route into the edge lane: the marker is decoded structurally.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/greet" },
            quote! {
                async fn greet() -> &'static str {
                    let _ = "const __AUTUMN_EDGE: () = ();";
                    "hi"
                }
            },
        )
        .to_string();

        assert!(
            !generated.contains("__autumn_edge_route_"),
            "a string literal must not be mistaken for the edge marker: {generated}"
        );
    }

    #[test]
    fn route_macro_string_literal_authorize_marker_is_not_a_binding() {
        // Handler *text* that merely spells the marker const must not be
        // mistaken for one: the marker is decoded structurally, never scanned
        // for as a string.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/items" },
            quote! {
                async fn create_item() -> &'static str {
                    let _ = "const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[(\"update\", \"Note\")];";
                    "created"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("authorize_bindings : & []"),
            "a string literal must not be mistaken for a generated binding marker: {generated}"
        );
    }

    // ── `#[agent_operable]` recorded in ApiDoc (#1691) ──────────────────────
    //
    // The route macro must fill `ApiDoc::agent_authority` from EITHER stacking
    // order, exactly like `#[secured]`/`#[authorize]`/`#[edge]`: the attribute
    // when it is still live below the route macro, the body marker const when
    // `#[agent_operable]` expanded above it and deleted its own attribute.
    // Losing it in one order would silently ship a governed handler as an
    // *ungoverned* MCP tool — audited with `reversibility=unknown` and missing
    // from the authority manifest's `actions` — with no diff anywhere.

    /// The `Some(&…)` initializer the route macro must emit for a handler
    /// governed by `#[agent_operable(grant = RefundDrafter)]`.
    const DRAFT_REFUND_AUTHORITY: &str = "agent_authority : :: core :: option :: Option :: Some (& __AUTUMN_AGENT_AUTHORITY_draft_refund)";

    #[test]
    fn route_macro_sets_agent_authority_from_live_attribute() {
        // Ordering A: `#[post]` outermost, `#[agent_operable]` still an
        // attribute below it, so the route macro reads it straight off the
        // unexpanded attribute.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/refunds" },
            quote! {
                #[agent_operable(grant = RefundDrafter)]
                async fn draft_refund() -> &'static str { "drafted" }
            },
        )
        .to_string();

        assert!(
            generated.contains(DRAFT_REFUND_AUTHORITY),
            "a live #[agent_operable] attribute must point ApiDoc at the handler's \
             authority static: {generated}"
        );
    }

    #[test]
    fn route_macro_sets_agent_authority_from_body_marker() {
        // Ordering B: `#[agent_operable]` written ABOVE `#[post]`, so it
        // expanded first, removed its own attribute and left only the marker
        // const in the body. The marker names the grant, and the authority
        // static is named after the handler either way.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/refunds" },
            quote! {
                async fn draft_refund() -> &'static str {
                    #[allow(dead_code)]
                    const __AUTUMN_AGENT_OPERABLE: &str = "RefundDrafter";
                    "drafted"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains(DRAFT_REFUND_AUTHORITY),
            "an already-expanded #[agent_operable] must still point ApiDoc at the \
             authority static: {generated}"
        );
    }

    #[test]
    fn route_macro_without_agent_operable_emits_none() {
        // The default must stay `None`: `Some` here is a claim that the body
        // was walked and every effect const-asserted against a grant, so an
        // ungoverned handler must never accidentally assert one.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/refunds" },
            quote! { async fn draft_refund() -> &'static str { "drafted" } },
        )
        .to_string();

        assert!(
            generated.contains("agent_authority : :: core :: option :: Option :: None"),
            "a handler with no #[agent_operable] records no authority: {generated}"
        );
        assert!(
            !generated.contains("__AUTUMN_AGENT_AUTHORITY_"),
            "…and must not reference an authority static that was never emitted: {generated}"
        );
    }

    #[test]
    fn route_macro_string_literal_agent_operable_marker_is_not_an_authority() {
        // Handler *text* that merely spells the marker const must not opt the
        // route into a governed authority: the marker is decoded structurally,
        // never scanned for as a string.
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/refunds" },
            quote! {
                async fn draft_refund() -> &'static str {
                    let _ = "const __AUTUMN_AGENT_OPERABLE: &str = \"RefundDrafter\";";
                    "drafted"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("agent_authority : :: core :: option :: Option :: None"),
            "a string literal must not be mistaken for the generated marker: {generated}"
        );
    }

    #[test]
    fn edge_rejects_agent_operable() {
        // The edge lane is read-only and has no session, audit sink or state
        // to record an agent invocation against, so a governed handler must
        // never be served from it. Both stacking orders are refused — the
        // marker is in `GUARD_MARKERS` for exactly this reason.

        // Ordering A: both attributes still live below `#[get]`.
        let attribute_form = route_macro(
            "GET",
            "get",
            quote! { "/refunds" },
            quote! {
                #[edge]
                #[agent_operable(grant = RefundDrafter)]
                async fn draft_refund() -> &'static str { "drafted" }
            },
        )
        .to_string();

        assert!(
            attribute_form.contains("compile_error"),
            "#[edge] + #[agent_operable] must be rejected: {attribute_form}"
        );
        assert!(
            attribute_form.contains("read-only"),
            "the error must say the edge lane is read-only: {attribute_form}"
        );

        // Ordering B: `#[agent_operable]` expanded above `#[get]`, leaving only
        // its marker const in the body.
        let marker_form = route_macro(
            "GET",
            "get",
            quote! { "/refunds" },
            quote! {
                #[edge]
                async fn draft_refund() -> &'static str {
                    #[allow(dead_code)]
                    const __AUTUMN_AGENT_OPERABLE: &str = "RefundDrafter";
                    "drafted"
                }
            },
        )
        .to_string();

        assert!(
            marker_form.contains("compile_error"),
            "an already-expanded #[agent_operable] must still be detected next to \
             #[edge]: {marker_form}"
        );
        assert!(
            marker_form.contains("read-only"),
            "the error must say the edge lane is read-only: {marker_form}"
        );
    }

    // ── capacity contract: statically derived pool set (#1733) ───────────

    #[test]
    fn route_macro_records_the_database_pool_from_a_db_extractor() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts" },
            quote! {
                async fn index(db: Db) -> String {
                    let _ = db;
                    String::new()
                }
            },
        )
        .to_string();

        assert!(
            generated.contains(r#"pools : & ["db"]"#),
            "a `Db` extractor must prove the database pool: {generated}"
        );
    }

    #[test]
    fn route_macro_records_no_pools_for_a_compute_only_handler() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/about" },
            quote! {
                async fn about() -> &'static str {
                    "about"
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("pools : & []"),
            "a handler declaring no resource extractor proves no pool: {generated}"
        );
    }

    #[test]
    fn route_macro_records_each_distinct_pool_once_and_in_order() {
        let generated = route_macro(
            "POST",
            "post",
            quote! { "/posts" },
            quote! {
                async fn create(db: Db, mailer: Mailer, events: Events) -> String {
                    let _ = (db, mailer, events);
                    String::new()
                }
            },
        )
        .to_string();

        assert!(
            generated.contains(r#"pools : & ["db" , "events" , "mail"]"#),
            "pools must be sorted and deduplicated for a stable contract diff: {generated}"
        );
    }

    #[test]
    fn route_macro_recognizes_sharded_database_extractors() {
        for extractor in ["ShardedDb", "ShardedReadDb", "Shards", "CrossShard"] {
            let ty = syn::Ident::new(extractor, proc_macro2::Span::call_site());
            let generated = route_macro(
                "GET",
                "get",
                quote! { "/posts" },
                quote! {
                    async fn index(db: #ty) -> String {
                        let _ = db;
                        String::new()
                    }
                },
            )
            .to_string();

            assert!(
                generated.contains(r#"pools : & ["db"]"#),
                "`{extractor}` is a database handle: {generated}"
            );
        }
    }

    #[test]
    fn route_macro_sees_a_pool_extractor_through_a_qualified_path() {
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts" },
            quote! {
                async fn index(db: autumn_web::db::Db) -> String {
                    let _ = db;
                    String::new()
                }
            },
        )
        .to_string();

        assert!(
            generated.contains(r#"pools : & ["db"]"#),
            "a fully qualified extractor path still proves the pool: {generated}"
        );
    }

    #[test]
    fn route_macro_does_not_read_a_pool_out_of_a_nested_generic() {
        // `State<AppState<Db>>` is an application-held state value, not a `Db`
        // extractor. Recording the database pool here would contradict the
        // documented rule that `State`-held resources are invisible, and would
        // put false `db-bound` shapes (and digest drift) into the contract.
        let generated = route_macro(
            "GET",
            "get",
            quote! { "/posts" },
            quote! {
                async fn index(state: State<AppState<Db>>) -> String {
                    let _ = state;
                    String::new()
                }
            },
        )
        .to_string();

        assert!(
            generated.contains("pools : & []"),
            "a pool name nested inside another type is not a declared extractor: {generated}"
        );
    }

    #[test]
    fn route_macro_still_sees_a_pool_through_option_and_reference_wrappers() {
        // The recognizer looks at the declared extractor, so the transparent
        // wrappers axum itself understands must not hide it.
        for spelling in ["Option < Db >", "& Db"] {
            let ty: syn::Type = syn::parse_str(spelling).expect("type parses");
            let generated = route_macro(
                "GET",
                "get",
                quote! { "/posts" },
                quote! {
                    async fn index(db: #ty) -> String {
                        let _ = db;
                        String::new()
                    }
                },
            )
            .to_string();

            assert!(
                generated.contains(r#"pools : & ["db"]"#),
                "`{spelling}` still declares the database extractor: {generated}"
            );
        }
    }
}