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
// OpenAPI appears many times in this module's docs as an acronym —
// silence clippy::doc_markdown for it locally. The other allows turn
// off pedantic style nits (`KeyValue::Foo` vs `Foo` inside the enum's
// own impl, `Option::map_or_else` vs `match`/`if let`) that would
// trade clarity for less-readable chained closure calls.
#![allow(
    clippy::doc_markdown,
    clippy::option_if_let_else,
    clippy::single_match_else,
    clippy::use_self
)]

//! `#[api_doc(...)]` attribute parsing for OpenAPI auto-generation.
//!
//! `#[api_doc]` is handled two ways:
//!
//! * As a **stored attribute** on route handlers (`#[get]`, `#[post]`, …):
//!   the route macro strips it from the function's attribute list,
//!   parses it here, and embeds the result in the generated `ApiDoc`
//!   struct.
//! * As a **standalone proc-macro** (see [`macro@crate::api_doc`]) so Rust
//!   accepts the attribute on its own. That entry point is a no-op
//!   wrapper — the real work happens when a route macro is also
//!   applied, since routes are the only places metadata is collected.
//!
//! Supported forms:
//!
//! ```ignore
//! #[api_doc(summary = "Fetch a user", tag = "users")]
//! #[api_doc(description = "...", tags = ["users", "admin"], status = 201)]
//! #[api_doc(hidden)]
//! ```
//!
//! Unknown keys are a compile error, so typos surface at build time.

use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{Attribute, Expr, ExprLit, Ident, Lit, LitBool, LitStr, Token};

pub use autumn_macros_support::schema::{
    last_segment_name, primitive_json_type, unwrap_single_generic,
};

/// Parsed `#[api_doc(...)]` attribute arguments.
// Each bool models a distinct, orthogonal attribute flag (`hidden`, `mcp`,
// `mcp = false`, `stream`, `task`, `core`, `webmcp`); grouping them would obscure rather than clarify.
#[allow(clippy::struct_excessive_bools)]
#[derive(Default)]
pub struct ApiDocAttr {
    pub summary: Option<LitStr>,
    pub description: Option<LitStr>,
    pub tags: Vec<LitStr>,
    pub operation_id: Option<LitStr>,
    pub status: Option<u16>,
    pub hidden: bool,
    /// `#[api_doc(mcp)]` / `#[api_doc(mcp = true)]` — opt this endpoint in
    /// as an MCP tool.
    pub mcp_tool: bool,
    /// `#[api_doc(mcp = false)]` — explicitly exclude from MCP, honored
    /// even under the whole-API hatch.
    pub mcp_exclude: bool,
    /// `#[api_doc(mcp, stream)]` — this MCP tool returns an Autumn `Sse`
    /// stream, projected onto the MCP Streamable-HTTP SSE channel as
    /// `notifications/progress` messages terminated by the final result.
    /// Only meaningful together with `mcp`; it also exempts the tool from
    /// the JSON-response eligibility gate (an `Sse` handler has no JSON
    /// response schema).
    pub mcp_stream: bool,
    /// `#[api_doc(mcp, task)]` — this MCP tool can return a task handle
    /// (MCP Tasks extension) instead of a blocking result.
    pub mcp_task: bool,
    /// `#[api_doc(mcp, core)]` — a core MCP tool. A client that defers tools
    /// loads it first. It does not opt the endpoint in.
    pub mcp_core: bool,
    /// `#[api_doc(webmcp)]` — make this endpoint a `WebMCP` tool. `mcp` does
    /// not set it.
    pub webmcp_tool: bool,
    /// `#[api_doc(webmcp = false)]` — never a `WebMCP` tool, also under the
    /// whole-API hatch.
    pub webmcp_exclude: bool,
}

enum KeyValue {
    Summary(LitStr),
    Description(LitStr),
    Tag(LitStr),
    Tags(Vec<LitStr>),
    OperationId(LitStr),
    Status(u16),
    Hidden,
    /// `true` => opt in as a tool, `false` => explicit exclusion.
    Mcp(bool),
    /// `stream` flag — this MCP tool streams over SSE.
    Stream,
    /// `task` flag — this MCP tool can run as a task.
    Task,
    /// `core` flag — a client that defers tools loads this MCP tool first.
    Core,
    /// `true` => a `WebMCP` tool, `false` => explicit exclusion.
    WebMcp(bool),
}

impl Parse for KeyValue {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let key: Ident = input.parse()?;
        let key_str = key.to_string();

        if key_str == "hidden" {
            if input.peek(Token![=]) {
                let _eq: Token![=] = input.parse()?;
                let value: LitBool = input.parse()?;
                return Ok(if value.value {
                    KeyValue::Hidden
                } else {
                    // `hidden = false` is equivalent to the default (visible).
                    // Return a distinguishable marker via Tags(vec![]) so
                    // ApiDocAttr::merge does nothing — this keeps parsing
                    // symmetric with other bool forms.
                    KeyValue::Tags(Vec::new())
                });
            }
            return Ok(KeyValue::Hidden);
        }

        if key_str == "mcp" {
            if input.peek(Token![=]) {
                let _eq: Token![=] = input.parse()?;
                let value: LitBool = input.parse()?;
                return Ok(KeyValue::Mcp(value.value));
            }
            // Bare `mcp` flag opts in.
            return Ok(KeyValue::Mcp(true));
        }

        if key_str == "webmcp" {
            if input.peek(Token![=]) {
                let _eq: Token![=] = input.parse()?;
                let value: LitBool = input.parse()?;
                return Ok(KeyValue::WebMcp(value.value));
            }
            return Ok(KeyValue::WebMcp(true));
        }

        if key_str == "stream" {
            if input.peek(Token![=]) {
                let _eq: Token![=] = input.parse()?;
                let value: LitBool = input.parse()?;
                return Ok(if value.value {
                    KeyValue::Stream
                } else {
                    // `stream = false` is the default; emit a no-op marker.
                    KeyValue::Tags(Vec::new())
                });
            }
            // Bare `stream` flag opts in.
            return Ok(KeyValue::Stream);
        }

        if key_str == "task" {
            if input.peek(Token![=]) {
                let _eq: Token![=] = input.parse()?;
                let value: LitBool = input.parse()?;
                // `task = false` is the default: a no-op marker.
                return Ok(if value.value {
                    KeyValue::Task
                } else {
                    KeyValue::Tags(Vec::new())
                });
            }
            return Ok(KeyValue::Task);
        }

        if key_str == "core" {
            if input.peek(Token![=]) {
                let _eq: Token![=] = input.parse()?;
                let value: LitBool = input.parse()?;
                // `core = false` is the default: a no-op marker.
                return Ok(if value.value {
                    KeyValue::Core
                } else {
                    KeyValue::Tags(Vec::new())
                });
            }
            return Ok(KeyValue::Core);
        }

        let _eq: Token![=] = input.parse()?;
        match key_str.as_str() {
            "summary" => Ok(KeyValue::Summary(input.parse()?)),
            "description" => Ok(KeyValue::Description(input.parse()?)),
            "tag" => Ok(KeyValue::Tag(input.parse()?)),
            "tags" => {
                // `tags = ["a", "b"]`
                let content;
                syn::bracketed!(content in input);
                let items =
                    syn::punctuated::Punctuated::<LitStr, Token![,]>::parse_terminated(&content)?;
                Ok(KeyValue::Tags(items.into_iter().collect()))
            }
            "operation_id" => Ok(KeyValue::OperationId(input.parse()?)),
            "status" => {
                let value: Expr = input.parse()?;
                let n = expect_u16(&value)?;
                Ok(KeyValue::Status(n))
            }
            other => Err(syn::Error::new(
                key.span(),
                format!(
                    "unknown key `{other}` in `#[api_doc(...)]`. \
                     Supported keys: summary, description, tag, tags, operation_id, status, hidden, mcp, stream, task, core, webmcp."
                ),
            )),
        }
    }
}

fn expect_u16(expr: &Expr) -> syn::Result<u16> {
    if let Expr::Lit(ExprLit {
        lit: Lit::Int(int), ..
    }) = expr
    {
        int.base10_parse::<u16>()
    } else {
        Err(syn::Error::new_spanned(
            expr,
            "expected an integer HTTP status code (e.g. `status = 201`)",
        ))
    }
}

impl ApiDocAttr {
    fn merge(&mut self, kv: KeyValue) {
        match kv {
            KeyValue::Summary(v) => self.summary = Some(v),
            KeyValue::Description(v) => self.description = Some(v),
            KeyValue::Tag(v) => self.tags = vec![v],
            KeyValue::Tags(v) if !v.is_empty() => self.tags = v,
            KeyValue::Tags(_) => {}
            KeyValue::OperationId(v) => self.operation_id = Some(v),
            KeyValue::Status(n) => self.status = Some(n),
            KeyValue::Hidden => self.hidden = true,
            KeyValue::Mcp(true) => self.mcp_tool = true,
            KeyValue::Mcp(false) => self.mcp_exclude = true,
            KeyValue::Stream => self.mcp_stream = true,
            KeyValue::Task => self.mcp_task = true,
            KeyValue::Core => self.mcp_core = true,
            KeyValue::WebMcp(true) => self.webmcp_tool = true,
            KeyValue::WebMcp(false) => self.webmcp_exclude = true,
        }
    }
}

impl Parse for ApiDocAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let items = syn::punctuated::Punctuated::<KeyValue, Token![,]>::parse_terminated(input)?;
        let mut out = ApiDocAttr::default();
        for kv in items {
            out.merge(kv);
        }
        Ok(out)
    }
}

/// Strip `#[api_doc(...)]` attributes from a handler's attribute list
/// and merge all of them into a single [`ApiDocAttr`].
///
/// Repeating the attribute is legal; later values override earlier ones
/// for scalar fields, and `tags = [..]` replaces the accumulated tags.
pub fn extract(attrs: &mut Vec<Attribute>) -> Result<ApiDocAttr, TokenStream> {
    let mut collected = ApiDocAttr::default();
    let mut error: Option<TokenStream> = None;

    attrs.retain(|attr| {
        if !attr.path().is_ident("api_doc") {
            return true;
        }
        // `#[api_doc]` with no arguments → mark visible with no overrides.
        let parsed: syn::Result<ApiDocAttr> = match &attr.meta {
            syn::Meta::Path(_) => Ok(ApiDocAttr::default()),
            syn::Meta::List(list) => syn::parse2(list.tokens.clone()),
            syn::Meta::NameValue(nv) => Err(syn::Error::new_spanned(
                nv,
                "expected `#[api_doc(...)]`, not `#[api_doc = ...]`",
            )),
        };
        match parsed {
            Ok(parsed) => {
                collected.absorb(parsed);
            }
            Err(err) => {
                if error.is_none() {
                    error = Some(err.to_compile_error());
                }
            }
        }
        false
    });

    if let Some(err) = error {
        return Err(err);
    }
    Ok(collected)
}

impl ApiDocAttr {
    fn absorb(&mut self, other: ApiDocAttr) {
        if other.summary.is_some() {
            self.summary = other.summary;
        }
        if other.description.is_some() {
            self.description = other.description;
        }
        if !other.tags.is_empty() {
            self.tags = other.tags;
        }
        if other.operation_id.is_some() {
            self.operation_id = other.operation_id;
        }
        if other.status.is_some() {
            self.status = other.status;
        }
        if other.hidden {
            self.hidden = true;
        }
        if other.mcp_tool {
            self.mcp_tool = true;
        }
        if other.mcp_exclude {
            self.mcp_exclude = true;
        }
        if other.mcp_stream {
            self.mcp_stream = true;
        }
        if other.mcp_task {
            self.mcp_task = true;
        }
        if other.mcp_core {
            self.mcp_core = true;
        }
        if other.webmcp_tool {
            self.webmcp_tool = true;
        }
        if other.webmcp_exclude {
            self.webmcp_exclude = true;
        }
    }

    /// Emit field initializers `summary: ..., description: ..., tags: ..., hidden: ...`
    /// for inclusion in an `ApiDoc { ... }` literal.
    ///
    /// `default_operation_id` is used when `operation_id` was not set on
    /// the attribute — typically the handler function's identifier.
    pub fn emit_ident_fields(&self, default_operation_id: &Ident) -> TokenStream {
        let summary = option_str(self.summary.as_ref());
        let description = option_str(self.description.as_ref());
        let tags = slice_str(&self.tags);
        let op_id = if let Some(id) = &self.operation_id {
            quote! { #id }
        } else {
            quote! { ::core::stringify!(#default_operation_id) }
        };
        let status = self.status.unwrap_or(200);
        let hidden = self.hidden;
        let mcp_tool = self.mcp_tool;
        let mcp_exclude = self.mcp_exclude;
        let mcp_stream = self.mcp_stream;
        let mcp_task = self.mcp_task;
        let mcp_core = self.mcp_core;
        let webmcp_tool = self.webmcp_tool;
        let webmcp_exclude = self.webmcp_exclude;
        quote! {
            operation_id: #op_id,
            summary: #summary,
            description: #description,
            tags: #tags,
            success_status: #status,
            hidden: #hidden,
            mcp_tool: #mcp_tool,
            mcp_exclude: #mcp_exclude,
            mcp_stream: #mcp_stream,
            mcp_task: #mcp_task,
            mcp_core: #mcp_core,
            webmcp_tool: #webmcp_tool,
            webmcp_exclude: #webmcp_exclude,
        }
    }
}

fn option_str(lit: Option<&LitStr>) -> TokenStream {
    match lit {
        Some(v) => quote! { ::core::option::Option::Some(#v) },
        None => quote! { ::core::option::Option::None },
    }
}

fn slice_str(items: &[LitStr]) -> TokenStream {
    if items.is_empty() {
        quote! { &[] }
    } else {
        let literals: Vec<_> = items.iter().map(|s| quote! { #s }).collect();
        quote! { &[#(#literals),*] }
    }
}

// ──────────────────────────────────────────────────────────────────
// Route path + signature inspection helpers
// ──────────────────────────────────────────────────────────────────

/// Extract `{name}` path parameters from a route template.
///
/// Closing braces without an opening brace are ignored. Segments that
/// contain regex (`{id:[0-9]+}`) take only the name before the colon.
/// Escaped braces (`{{` / `}}`) are treated as literal characters and skipped.
pub fn extract_path_params(path: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut remaining = path;

    while let Some(start) = remaining.find('{') {
        let after_brace = &remaining[start + 1..];
        // `{{` is an escaped literal brace — skip both characters and continue.
        if let Some(rest) = after_brace.strip_prefix('{') {
            remaining = rest;
            continue;
        }
        let Some(end_rel) = after_brace.find('}') else {
            break;
        };

        let inner = &after_brace[..end_rel];
        let name = inner.split(':').next().unwrap_or(inner).trim();
        if !name.is_empty() {
            out.push(name.to_owned());
        }

        remaining = &after_brace[end_rel + 1..];
    }

    out
}

/// Emit a `&'static [&'static str]` literal for a list of owned strings.
pub fn emit_path_param_slice(params: &[String]) -> TokenStream {
    if params.is_empty() {
        quote! { &[] }
    } else {
        let literals: Vec<_> = params
            .iter()
            .map(|p| LitStr::new(p, Span::call_site()))
            .collect();
        quote! { &[#(#literals),*] }
    }
}

/// Inspect the handler's parameter list for `Json<T>` request bodies.
///
/// Returns a `Some(tokens)` producing a `SchemaEntry` initializer for the
/// first JSON extractor seen, or `None` if the handler has no JSON body.
///
/// Recognizes Autumn's validation wrapper as well: a parameter typed
/// `Valid<Json<T>>` is treated the same as `Json<T>` so handlers using
/// the documented validator pattern still get a `requestBody` in the
/// generated spec.
pub fn infer_request_body(input_fn: &syn::ItemFn) -> Option<TokenStream> {
    for arg in &input_fn.sig.inputs {
        let syn::FnArg::Typed(pat) = arg else {
            continue;
        };
        if let Some(inner) = unwrap_json_body(&pat.ty) {
            return Some(schema_entry_for_type(&inner));
        }
    }
    None
}

/// Peel one layer of `Valid<...>` so that
/// `Valid<Json<NewPost>>` → `Json<NewPost>` → `NewPost`.
///
/// Matches either a bare `Json<T>` or `Valid<Json<T>>` and returns the
/// inner `T`. Any deeper nesting returns `None` — we intentionally
/// don't guess at unknown wrappers because mis-identifying them would
/// produce wrong schemas.
pub fn unwrap_json_body(ty: &syn::Type) -> Option<syn::Type> {
    if let Some(inner) = unwrap_single_generic(ty, "Json") {
        return Some(inner);
    }
    if let Some(inner) = unwrap_single_generic(ty, "Valid")
        && let Some(payload) = unwrap_single_generic(&inner, "Json")
    {
        return Some(payload);
    }
    None
}

/// Inspect the handler's return type for `Json<T>` to infer the success
/// response body. Handles several common Axum return-type patterns:
///
/// * `Json<T>` — plain JSON body
/// * `Result<Json<T>, _>` / `AutumnResult<Json<T>>` — fallible JSON
/// * `(StatusCode, Json<T>)` — JSON with a custom status code
/// * `Result<(StatusCode, Json<T>), _>` — the two combined
///
/// A body guard (`#[secured]`, `#[step_up]`, `#[authorize]`, `#[throttle]`)
/// written *above* the route attribute expands before this macro runs and
/// rewrites `sig.output` to `Response`, which would otherwise make every
/// guarded route's response schema disappear (#1677). When that has
/// happened, [`recover_guarded_return_type`] reads the pre-rewrite type back
/// from the `__autumn_inner` binding the guard left in the body, so
/// inference is independent of attribute expansion order.
pub fn infer_response_body(input_fn: &syn::ItemFn) -> Option<TokenStream> {
    // #[step_up]/#[throttle] moved their marker consts out of the body and
    // into their gate's own impl block (#1668), so
    // `generated_inner_response_binding`'s in-body marker check can never see
    // them again — a route stacked under either now recognizes the binding
    // via the gate parameter #1668 left in the signature instead. Budgeted
    // (not a bare bool) to one accepted markerless level per such gate
    // parameter present, so a coincidental match nested *deeper* than any
    // real guard wrapper — the exact false positive the marker check exists
    // to rule out — still gets rejected once the budget the real gates
    // earned is spent.
    let markerless_gate_budget = ["__AutumnStepUpGate_", "__AutumnThrottleGate_"]
        .into_iter()
        .filter(|prefix| crate::param_helpers::has_guard_gate_param_with_prefix(input_fn, prefix))
        .count();
    let ty = recover_guarded_return_type(&input_fn.block, markerless_gate_budget)
        .or_else(|| sig_output_type(input_fn))?;
    let ty = unwrap_result_ok(&ty).unwrap_or(ty);
    find_json_in_type(&ty).map(|inner| schema_entry_for_type(&inner))
}

/// The handler's declared return type, straight off `sig.output` — `None` for
/// a unit-returning (`ReturnType::Default`) handler.
pub fn sig_output_type(input_fn: &syn::ItemFn) -> Option<syn::Type> {
    let syn::ReturnType::Type(_, ty) = &input_fn.sig.output else {
        return None;
    };
    Some((**ty).clone())
}

/// Recover a handler's pre-rewrite return type from the `__autumn_inner`
/// binding a body guard leaves behind when it expands before the route macro
/// (issue #1677).
///
/// Every guard that rewrites `sig.output` to `Response` also binds the
/// original type as `let __autumn_inner: #ty = (async move { … }).await;`
/// around the handler's real body — see `secured_macro`, `step_up_macro`,
/// `authorize_macro`, and `throttle_macro`. [`crate::idempotency_guard::generated_inner_response_binding`]
/// recognizes that binding only by its exact structural position (last-but-one
/// statement, followed immediately by the generated `IntoResponse::into_response`
/// tail) *and* one of two signals that a real guard, not a coincidence, put it
/// there: one of the guard's own marker consts earlier in the same block
/// (`#[secured]`/`#[authorize]`), or a spend against `markerless_gate_budget`
/// (`#[step_up]`/`#[throttle]`, whose marker consts moved out of the body and
/// into their gate's own impl block with #1668, so the body has nothing left
/// to scan for — `infer_response_body` counts the budget from the signature
/// instead, once, outside this recursion, and each level that spends it
/// returns the balance one lower so a deeper level cannot spend the same unit
/// twice). Position and tail alone would still be foolable:
/// a guard's generated wrapper carries the user's own original body one level
/// deeper (`(async move { #original_body }).await`), so if that body itself
/// independently ends in the same two-statement shape — whether the handler
/// is unguarded or the coincidence sits nested inside a real guard — position
/// and tail cannot tell it apart from a real guard's own binding. Requiring
/// one of those two signals closes that: no guard ever emits the
/// `__autumn_inner` binding without one, and a handler's own code has no
/// reason to declare an identifier the framework treats as reserved.
///
/// When guards stack, each later-expanding guard wraps the earlier guard's
/// whole generated body one level deeper in that same shape, so only the
/// *innermost* binding carries the type as the user actually wrote it: every
/// outer one necessarily reads back `Response`, because by the time that
/// guard ran, an inner guard had already rewritten `sig.output`. This walk
/// therefore recurses into the nested wrapper (via
/// [`crate::idempotency_guard::expr_nested_async_body`]) before accepting a
/// level's own binding, so the deepest type found wins.
///
/// Returns `None` when no such binding exists — an unguarded handler, a
/// route-attribute-outermost ordering where no guard has expanded yet, or a
/// guard wrapping a `()`/`impl Trait` return, for which no guard emits an
/// explicit annotation (Rust rejects `impl Trait` in a local variable's type
/// ascription) and there is nothing to recover.
fn recover_guarded_return_type(
    block: &syn::Block,
    markerless_gate_budget: usize,
) -> Option<syn::Type> {
    let (ty, init_expr, remaining_budget) =
        crate::idempotency_guard::generated_inner_response_binding(block, markerless_gate_budget)?;
    let nested = crate::idempotency_guard::expr_nested_async_body(init_expr)
        .and_then(|block| recover_guarded_return_type(block, remaining_budget));
    Some(nested.unwrap_or_else(|| ty.clone()))
}

/// Look for `Json<T>` either directly or inside a tuple element.
///
/// Axum handlers often return tuples like `(StatusCode, Json<T>)` or
/// `([(HeaderName, _); N], Json<T>)` to attach status codes or
/// headers. We scan each tuple element so the generated schema still
/// reflects the JSON body.
pub fn find_json_in_type(ty: &syn::Type) -> Option<syn::Type> {
    if let Some(inner) = unwrap_single_generic(ty, "Json") {
        return Some(inner);
    }
    if let syn::Type::Tuple(tup) = ty {
        for elem in &tup.elems {
            if let Some(inner) = unwrap_single_generic(elem, "Json") {
                return Some(inner);
            }
        }
    }
    None
}

/// Peel a single layer of `Result<T, _>` / `AutumnResult<T>` so we can
/// inspect the `Ok` variant for a `Json<...>` wrapper.
pub fn unwrap_result_ok(ty: &syn::Type) -> Option<syn::Type> {
    let path = match ty {
        syn::Type::Path(p) => &p.path,
        _ => return None,
    };
    let last = path.segments.last()?;
    let name = last.ident.to_string();
    let syn::PathArguments::AngleBracketed(args) = &last.arguments else {
        return None;
    };
    match name.as_str() {
        "Result" => args.args.iter().find_map(|arg| match arg {
            syn::GenericArgument::Type(t) => Some(t.clone()),
            _ => None,
        }),
        "AutumnResult" => args.args.iter().find_map(|arg| match arg {
            syn::GenericArgument::Type(t) => Some(t.clone()),
            _ => None,
        }),
        _ => None,
    }
}

/// Emit a `::autumn_web::openapi::SchemaEntry` initializer for a type.
///
/// Handles the following patterns:
///
/// * `Vec<T>`         → `SchemaKind::Array(&inner)`  (array of `T`)
/// * `Option<T>`      → `SchemaKind::Nullable(&inner)` (nullable `T`)
/// * known primitive  → `SchemaKind::Primitive("string"|"integer"|…)`
/// * everything else  → `SchemaKind::Ref` with the type's last path
///   segment as the schema name (back-filled by the spec generator)
fn schema_entry_for_type(ty: &syn::Type) -> TokenStream {
    // `Vec` and `Option` are matched on the LAST PATH SEGMENT, so an
    // application's own `domain::Vec<T>` / `domain::Option<T>` — ordinary
    // structs that merely spell that segment — lands here too, and neither is
    // an array nor nullable. Each wrapper entry therefore carries its own
    // `type_name` identity and its real display name, and the generator checks
    // that identity before rendering the wrapper shape: an impostor is emitted
    // as an ordinary `$ref` instead (see `wrapper_is_impostor`). The `name` is
    // the type's last segment rather than the old `"array"`/`"nullable"`
    // sentinel because that name is what the component index uses as the
    // display base — it is never consulted for a genuine wrapper.
    let wrapper_name = LitStr::new(
        &last_segment_name(ty).unwrap_or_else(|| "Schema".to_owned()),
        Span::call_site(),
    );
    // Vec<T> → array of <schema of T>.
    if let Some(inner) = unwrap_single_generic(ty, "Vec") {
        let inner_tokens = schema_entry_for_type(&inner);
        return quote! {
            ::autumn_web::openapi::SchemaEntry {
                name: #wrapper_name,
                kind: ::autumn_web::openapi::SchemaKind::Array(&#inner_tokens),
                identity: ::core::option::Option::Some(
                    ::autumn_web::openapi::type_name_of::<#ty>
                ),
            }
        };
    }
    // Option<T> → nullable <schema of T>.
    if let Some(inner) = unwrap_single_generic(ty, "Option") {
        let inner_tokens = schema_entry_for_type(&inner);
        return quote! {
            ::autumn_web::openapi::SchemaEntry {
                name: #wrapper_name,
                kind: ::autumn_web::openapi::SchemaKind::Nullable(&#inner_tokens),
                identity: ::core::option::Option::Some(
                    ::autumn_web::openapi::type_name_of::<#ty>
                ),
            }
        };
    }

    let name = last_segment_name(ty).unwrap_or_else(|| "Schema".to_owned());
    let name_lit = LitStr::new(&name, Span::call_site());
    if let Some(json_type) = primitive_json_type(&name) {
        let json_lit = LitStr::new(json_type, Span::call_site());
        quote! {
            ::autumn_web::openapi::SchemaEntry {
                name: #name_lit,
                kind: ::autumn_web::openapi::SchemaKind::Primitive(#json_lit),
                identity: ::core::option::Option::None,
            }
        }
    } else {
        // A named object ref carries its globally-unique `type_name` identity so
        // the spec/MCP back-fill can disambiguate two distinct types that share
        // this last path segment (issue #1972).
        quote! {
            ::autumn_web::openapi::SchemaEntry {
                name: #name_lit,
                kind: ::autumn_web::openapi::SchemaKind::Ref,
                identity: ::core::option::Option::Some(
                    ::autumn_web::openapi::type_name_of::<#ty>
                ),
            }
        }
    }
}

/// Inspect the handler's parameter list for `Query<T>` query-string extractors.
///
/// Returns `Some(tokens)` producing a `SchemaEntry` initializer when a
/// `Query<T>` parameter is found, `None` otherwise. Only the first `Query`
/// extractor is used — multiple `Query<T>` parameters are uncommon and the
/// first one captures the intent.
pub fn infer_query_params(input_fn: &syn::ItemFn) -> Option<TokenStream> {
    for arg in &input_fn.sig.inputs {
        let syn::FnArg::Typed(pat) = arg else {
            continue;
        };
        if let Some(inner) = unwrap_single_generic(&pat.ty, "Query") {
            return Some(schema_entry_for_type(&inner));
        }
    }
    None
}

/// Detect `#[secured]` on a handler and return `(secured, required_roles)`.
///
/// Two detection strategies:
/// 1. `#[secured]` still in attrs (route macro is outermost; secured is below it).
/// 2. Function-local `__AUTUMN_SECURED_ROLES` marker present (secured was
///    above the route macro and already expanded its body).
/// 3. Legacy fallback: `__autumn_session` param present.
pub fn has_policy_check_in_stmts(stmts: &[syn::Stmt]) -> bool {
    for stmt in stmts {
        let s = quote::quote!(#stmt).to_string();
        if s.contains("__check_policy") {
            return true;
        }
    }
    false
}

pub fn extract_secured_info(input_fn: &syn::ItemFn) -> (bool, TokenStream, TokenStream) {
    // Case 1 — #[secured] or #[autumn_web::secured] visible as a remaining attribute.
    for attr in &input_fn.attrs {
        if attr.path().is_ident("secured")
            || attr
                .path()
                .segments
                .last()
                .is_some_and(|s| s.ident == "secured")
        {
            let roles = extract_secured_roles(attr);
            let scopes = extract_secured_scopes(attr);
            return (
                true,
                emit_static_str_slice(&roles),
                emit_static_str_slice(&scopes),
            );
        }
    }

    // Case 2 — #[secured] was above the route macro and already expanded;
    // read the markers emitted into the guarded function body. This runs
    // BEFORE the live-#[authorize] fallback below: `#[secured]` above the
    // route macro with `#[authorize]` below it leaves both an expanded marker
    // and a live attribute, and letting the attribute win would drop the
    // roles/scopes to `&[]` while `secured` stayed true — deleting the
    // `#[secured(...)]` line would then produce zero manifest diff on a
    // `provable` dimension.
    if let Some(roles) = extract_secured_roles_marker(input_fn) {
        let scopes = extract_secured_scopes_marker(input_fn).unwrap_or_default();
        return (
            true,
            emit_static_str_slice(&roles),
            emit_static_str_slice(&scopes),
        );
    }

    // Case 1b — #[authorize] or #[autumn_web::authorize] visible as a remaining
    // attribute (and no secured markers anywhere in the body).
    for attr in &input_fn.attrs {
        if attr.path().is_ident("authorize")
            || attr
                .path()
                .segments
                .last()
                .is_some_and(|s| s.ident == "authorize")
        {
            return (true, quote! { &[] }, quote! { &[] });
        }
    }

    // Case 2b — #[authorize] was above the route macro and already expanded;
    // check if a policy check statement is present.
    if has_policy_check_in_stmts(&input_fn.block.stmts) {
        return (true, quote! { &[] }, quote! { &[] });
    }

    // Case 3 — compatibility fallback for expansions produced before the
    // marker existed. This can only recover that the route is secured.
    let has_session = input_fn.sig.inputs.iter().any(|param| {
        if let syn::FnArg::Typed(pt) = param
            && let syn::Pat::Ident(pi) = pt.pat.as_ref()
        {
            return pi.ident == "__autumn_session";
        }
        false
    });
    if has_session {
        return (true, quote! { &[] }, quote! { &[] });
    }

    (false, quote! { &[] }, quote! { &[] })
}

/// Detect an explicit `#[public]` marker on a handler.
///
/// Mirrors [`extract_secured_info`]'s attribute/marker duality:
/// 1. `#[public]` (or `#[autumn_web::public]`) still present as an attribute,
///    which happens when the route macro is outermost and `#[public]` has not
///    expanded yet.
/// 2. The `__AUTUMN_PUBLIC` marker const emitted into the handler body when
///    `#[public]` expanded before the route macro.
pub fn is_public(input_fn: &syn::ItemFn) -> bool {
    for attr in &input_fn.attrs {
        if attr.path().is_ident("public")
            || attr
                .path()
                .segments
                .last()
                .is_some_and(|s| s.ident == "public")
        {
            return true;
        }
    }
    has_public_marker_in_stmts(&input_fn.block.stmts)
}

/// Name of the marker const `#[agent_operable]` prepends to a governed handler
/// body so the declaration survives the attribute's own removal.
const AGENT_OPERABLE_MARKER: &str = "__AUTUMN_AGENT_OPERABLE";

/// Detect `#[agent_operable(grant = ...)]` on a handler (issue #1691).
///
/// Mirrors [`is_public`]'s attribute/marker duality, because the two stackings
/// are equally idiomatic and losing either one is silent: a governed handler
/// whose `ApiDoc::agent_authority` came back `None` would be exposed to agents
/// as an *ungoverned* MCP tool — audited with `reversibility = "unknown"` and
/// filed under the manifest's `ungoverned_tools` — with nothing in the source
/// to show for it.
///
/// 1. `#[agent_operable]` (or `#[autumn_web::agent_operable]`) still present as
///    an attribute, which happens when the route macro is outermost.
/// 2. The `__AUTUMN_AGENT_OPERABLE` marker const the attribute injects as the
///    first statement of the body when it expanded *before* the route macro.
///    Read through [`crate::edge::stmts_have_marker`], so it stays reachable
///    however many body guards wrapped it in `(async move { … }).await`.
///
/// The marker is decoded structurally (a `const` item of that name), never by
/// scanning stringified tokens, so handler *text* that merely spells it cannot
/// forge a governed route.
///
/// Returns only whether the handler is governed: the authority `static` is
/// named after the handler, so the route macro needs no further detail from
/// either site, and the grant path in the marker is the analyser's business.
pub fn extract_agent_authority(input_fn: &syn::ItemFn) -> bool {
    let has_attr = input_fn.attrs.iter().any(|attr| {
        attr.path().is_ident("agent_operable")
            || attr
                .path()
                .segments
                .last()
                .is_some_and(|s| s.ident == "agent_operable")
    });
    has_attr || crate::edge::stmts_have_marker(&input_fn.block.stmts, AGENT_OPERABLE_MARKER)
}

fn has_public_marker_in_stmts(stmts: &[syn::Stmt]) -> bool {
    stmts.iter().any(has_public_marker_in_stmt)
}

fn has_public_marker_in_stmt(stmt: &syn::Stmt) -> bool {
    match stmt {
        syn::Stmt::Item(syn::Item::Const(item_const)) => item_const.ident == "__AUTUMN_PUBLIC",
        syn::Stmt::Expr(expr, _) => has_public_marker_in_expr(expr),
        syn::Stmt::Local(local) => local
            .init
            .as_ref()
            .is_some_and(|init| has_public_marker_in_expr(&init.expr)),
        _ => false,
    }
}

fn has_public_marker_in_expr(expr: &syn::Expr) -> bool {
    match expr {
        syn::Expr::Block(block) => has_public_marker_in_stmts(&block.block.stmts),
        syn::Expr::Unsafe(block) => has_public_marker_in_stmts(&block.block.stmts),
        // Same generated-wrapper descent as the secured/authorize marker walks:
        // a body guard expanding after `#[public]` (e.g. `#[throttle]`) buries
        // the marker inside `(async move { … }).await`, and losing it here
        // flips the route to `unclassified` and false-fails the coverage gate.
        _ => crate::idempotency_guard::expr_nested_async_body(expr)
            .is_some_and(|block| has_public_marker_in_stmts(&block.stmts)),
    }
}

fn extract_secured_roles_marker(input_fn: &syn::ItemFn) -> Option<Vec<String>> {
    extract_secured_roles_marker_from_stmts(&input_fn.block.stmts)
}

fn extract_secured_roles_marker_from_stmts(stmts: &[syn::Stmt]) -> Option<Vec<String>> {
    stmts
        .iter()
        .find_map(extract_secured_roles_marker_from_stmt)
}

fn extract_secured_roles_marker_from_stmt(stmt: &syn::Stmt) -> Option<Vec<String>> {
    match stmt {
        syn::Stmt::Item(syn::Item::Const(item_const))
            if item_const.ident == "__AUTUMN_SECURED_ROLES" =>
        {
            extract_roles_from_marker_expr(&item_const.expr)
        }
        syn::Stmt::Expr(expr, _) => extract_secured_roles_marker_from_expr(expr),
        syn::Stmt::Local(local) => local
            .init
            .as_ref()
            .and_then(|init| extract_secured_roles_marker_from_expr(&init.expr)),
        _ => None,
    }
}

fn extract_secured_roles_marker_from_expr(expr: &syn::Expr) -> Option<Vec<String>> {
    match expr {
        syn::Expr::Block(block) => extract_secured_roles_marker_from_stmts(&block.block.stmts),
        syn::Expr::Unsafe(block) => extract_secured_roles_marker_from_stmts(&block.block.stmts),
        // A guard that expands after `#[secured]` (e.g. `#[authorize]`) buries
        // the marker inside `let __autumn_inner: T = (async move { … }).await;`
        // — descend that generated wrapper or the roles silently vanish from
        // the route metadata while `secured` stays `true` via the fallbacks.
        _ => crate::idempotency_guard::expr_nested_async_body(expr)
            .and_then(|block| extract_secured_roles_marker_from_stmts(&block.stmts)),
    }
}

fn extract_roles_from_marker_expr(expr: &syn::Expr) -> Option<Vec<String>> {
    let syn::Expr::Reference(reference) = expr else {
        return None;
    };
    let syn::Expr::Array(array) = reference.expr.as_ref() else {
        return None;
    };

    let mut roles = Vec::with_capacity(array.elems.len());
    for elem in &array.elems {
        let syn::Expr::Lit(lit) = elem else {
            return None;
        };
        let syn::Lit::Str(role) = &lit.lit else {
            return None;
        };
        roles.push(role.value());
    }
    Some(roles)
}

fn extract_secured_roles(attr: &syn::Attribute) -> Vec<String> {
    use proc_macro2::TokenTree;

    let syn::Meta::List(list) = &attr.meta else {
        return Vec::new();
    };
    // Roles are the leading bare string literals; a trailing `scopes = [...]`
    // (token abilities) may follow and is not a role, so peel literals
    // directly rather than parsing the whole list as `LitStr`s.
    let mut roles = Vec::new();
    let mut iter = list.tokens.clone().into_iter().peekable();
    while let Some(TokenTree::Literal(lit)) = iter.peek() {
        match syn::parse2::<syn::LitStr>(quote! { #lit }) {
            Ok(s) => roles.push(s.value()),
            Err(_) => break,
        }
        iter.next();
        if let Some(TokenTree::Punct(p)) = iter.peek()
            && p.as_char() == ','
        {
            iter.next();
        } else {
            break;
        }
    }
    roles
}

fn extract_secured_scopes(attr: &syn::Attribute) -> Vec<String> {
    use proc_macro2::TokenTree;

    let syn::Meta::List(list) = &attr.meta else {
        return Vec::new();
    };
    // Scopes appear as `scopes = ["scope1", "scope2"]` after any role literals.
    let mut iter = list.tokens.clone().into_iter();
    while let Some(tt) = iter.next() {
        let TokenTree::Ident(ident) = tt else {
            continue;
        };
        if ident != "scopes" {
            continue;
        }
        let Some(TokenTree::Punct(p)) = iter.next() else {
            continue;
        };
        if p.as_char() != '=' {
            continue;
        }
        let Some(TokenTree::Group(group)) = iter.next() else {
            continue;
        };
        let mut scopes = Vec::new();
        for inner_tt in group.stream() {
            if let TokenTree::Literal(lit) = inner_tt
                && let Ok(s) = syn::parse2::<syn::LitStr>(quote! { #lit })
            {
                scopes.push(s.value());
            }
        }
        return scopes;
    }
    Vec::new()
}

fn extract_secured_scopes_marker(input_fn: &syn::ItemFn) -> Option<Vec<String>> {
    extract_secured_scopes_marker_from_stmts(&input_fn.block.stmts)
}

fn extract_secured_scopes_marker_from_stmts(stmts: &[syn::Stmt]) -> Option<Vec<String>> {
    stmts
        .iter()
        .find_map(extract_secured_scopes_marker_from_stmt)
}

fn extract_secured_scopes_marker_from_stmt(stmt: &syn::Stmt) -> Option<Vec<String>> {
    match stmt {
        syn::Stmt::Item(syn::Item::Const(item_const))
            if item_const.ident == "__AUTUMN_SECURED_SCOPES" =>
        {
            extract_roles_from_marker_expr(&item_const.expr)
        }
        syn::Stmt::Expr(expr, _) => extract_secured_scopes_marker_from_expr(expr),
        syn::Stmt::Local(local) => local
            .init
            .as_ref()
            .and_then(|init| extract_secured_scopes_marker_from_expr(&init.expr)),
        _ => None,
    }
}

fn extract_secured_scopes_marker_from_expr(expr: &syn::Expr) -> Option<Vec<String>> {
    match expr {
        syn::Expr::Block(block) => extract_secured_scopes_marker_from_stmts(&block.block.stmts),
        syn::Expr::Unsafe(block) => extract_secured_scopes_marker_from_stmts(&block.block.stmts),
        // Same generated-wrapper descent as the roles walk above: the scopes
        // marker sits wherever the roles marker sits.
        _ => crate::idempotency_guard::expr_nested_async_body(expr)
            .and_then(|block| extract_secured_scopes_marker_from_stmts(&block.stmts)),
    }
}

/// Name of the marker const `#[authorize]` prepends to a guarded body so the
/// binding survives the attribute's own removal.
const AUTHORIZE_BINDINGS_MARKER: &str = "__AUTUMN_AUTHORIZE_BINDINGS";

/// Extract the `#[authorize]` bindings declared on a handler, as
/// `(action, resource)` pairs in source order.
///
/// Mirrors [`extract_secured_info`]'s attribute/marker duality, but takes the
/// **union** of the two rather than the first that matches: a mixed stack
/// (`#[authorize(A)]` above the route macro, `#[authorize(B)]` below it) leaves
/// one already-expanded marker *and* one live attribute, and both are real
/// bindings.
///
/// 1. Marker consts in the body — `#[authorize]` expanded first and deleted its
///    own attribute. The walk descends the generated `(async move { … }).await`
///    wrappers, because each guard that expands afterwards buries the marker one
///    level deeper, and collects every level instead of stopping at the first.
/// 2. Attributes still present — the route macro is outermost, so `#[authorize]`
///    has not expanded yet. Parsed with the `#[authorize]` grammar itself
///    ([`crate::authorize::parse_with_leading_literal`]) so the two sites cannot
///    drift apart. Every matching attribute contributes, since nothing stops a
///    handler from stacking several.
///
/// The result is source-ordered. Markers precede live attributes because a
/// marker only ever comes from an attribute *above* the route macro, and live
/// attributes sit *below* it; within the markers, deeper nesting means an
/// earlier expansion — i.e. higher in the source stack — so the walk records
/// nested markers before the level that wraps them.
///
/// Markers are decoded structurally (`&[( "action", "Resource" ), …]`), never by
/// scanning stringified tokens, so handler *text* that merely spells the marker
/// cannot forge a binding. A same-named const of any other shape is not ours to
/// interpret and contributes nothing rather than erroring.
pub fn extract_authorize_bindings(input_fn: &syn::ItemFn) -> Vec<(String, String)> {
    let mut bindings = Vec::new();

    collect_authorize_markers_in_stmts(&input_fn.block.stmts, &mut bindings);

    for attr in &input_fn.attrs {
        if crate::authorize::attr_is_authorize_shaped(attr, input_fn) {
            bindings.extend(authorize_binding_from_attr(attr));
        }
    }

    bindings
}

/// Read one still-unexpanded `#[authorize(...)]` attribute.
///
/// Returns `None` for an attribute the `#[authorize]` macro will itself reject
/// (a bare `#[authorize]` with no arguments, a missing action or resource): the
/// macro reports the diagnostic, and metadata extraction stays silent rather
/// than emitting a second error or a half-formed binding.
fn authorize_binding_from_attr(attr: &syn::Attribute) -> Option<(String, String)> {
    let syn::Meta::List(list) = &attr.meta else {
        return None;
    };
    let args = crate::authorize::parse_with_leading_literal(list.tokens.clone()).ok()?;
    Some((args.action?, args.resource?.to_string()))
}

fn collect_authorize_markers_in_stmts(stmts: &[syn::Stmt], out: &mut Vec<(String, String)>) {
    // Nested wrappers first: a deeper marker was expanded earlier, i.e. its
    // attribute sat higher in the source stack, so it must be recorded before
    // this level's own marker for the result to stay source-ordered.
    for stmt in stmts {
        match stmt {
            syn::Stmt::Expr(expr, _) => collect_authorize_markers_in_expr(expr, out),
            syn::Stmt::Local(local) => {
                if let Some(init) = &local.init {
                    collect_authorize_markers_in_expr(&init.expr, out);
                }
            }
            _ => {}
        }
    }
    for stmt in stmts {
        if let syn::Stmt::Item(syn::Item::Const(item_const)) = stmt
            && item_const.ident == AUTHORIZE_BINDINGS_MARKER
        {
            collect_authorize_bindings_from_marker_expr(&item_const.expr, out);
        }
    }
}

fn collect_authorize_markers_in_expr(expr: &syn::Expr, out: &mut Vec<(String, String)>) {
    match expr {
        syn::Expr::Block(block) => collect_authorize_markers_in_stmts(&block.block.stmts, out),
        syn::Expr::Unsafe(block) => collect_authorize_markers_in_stmts(&block.block.stmts, out),
        // Everything the body guards generate — `(async move { … }).await`,
        // optionally inside `IntoResponse::into_response(…)`, parens or
        // invisible groups — is unwrapped by the shared helper, so a marker
        // stays reachable however many guards expanded around it.
        _ => {
            if let Some(block) = crate::idempotency_guard::expr_nested_async_body(expr) {
                collect_authorize_markers_in_stmts(&block.stmts, out);
            }
        }
    }
}

/// Decode a `&[("action", "Resource"), …]` marker initializer.
///
/// All-or-nothing per marker: one element of an unexpected shape means the const
/// is not the one we emit, so none of it is recorded.
fn collect_authorize_bindings_from_marker_expr(expr: &syn::Expr, out: &mut Vec<(String, String)>) {
    let syn::Expr::Reference(reference) = expr else {
        return;
    };
    let syn::Expr::Array(array) = reference.expr.as_ref() else {
        return;
    };

    let mut decoded = Vec::with_capacity(array.elems.len());
    for elem in &array.elems {
        let syn::Expr::Tuple(tuple) = elem else {
            return;
        };
        let [action, resource] = tuple.elems.iter().collect::<Vec<_>>()[..] else {
            return;
        };
        let (Some(action), Some(resource)) =
            (string_literal_value(action), string_literal_value(resource))
        else {
            return;
        };
        decoded.push((action, resource));
    }
    out.extend(decoded);
}

fn string_literal_value(expr: &syn::Expr) -> Option<String> {
    match expr {
        syn::Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(s),
            ..
        }) => Some(s.value()),
        _ => None,
    }
}

/// Emit the `&'static [AuthorizeBinding]` slice for `ApiDoc::authorize_bindings`.
pub fn emit_authorize_binding_slice(bindings: &[(String, String)]) -> TokenStream {
    if bindings.is_empty() {
        return quote! { &[] };
    }
    let entries = bindings.iter().map(|(action, resource)| {
        let action = LitStr::new(action, Span::call_site());
        let resource = LitStr::new(resource, Span::call_site());
        quote! {
            ::autumn_web::openapi::AuthorizeBinding { action: #action, resource: #resource }
        }
    });
    quote! { &[#(#entries),*] }
}

fn emit_static_str_slice(items: &[String]) -> TokenStream {
    if items.is_empty() {
        quote! { &[] }
    } else {
        let lits: Vec<_> = items
            .iter()
            .map(|s| LitStr::new(s, Span::call_site()))
            .collect();
        quote! { &[#(#lits),*] }
    }
}

/// Convenience wrapper: emit an `Option<SchemaEntry>` expression.
pub fn schema_option(expr: Option<TokenStream>) -> TokenStream {
    match expr {
        Some(e) => quote! { ::core::option::Option::Some(#e) },
        None => quote! { ::core::option::Option::None },
    }
}

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

    #[test]
    fn api_doc_core_flag_parses() {
        let attr: ApiDocAttr = syn::parse_str("mcp, core").unwrap();
        assert!(attr.mcp_tool && attr.mcp_core);
        let attr: ApiDocAttr = syn::parse_str("mcp, core = true").unwrap();
        assert!(attr.mcp_core);
        let attr: ApiDocAttr = syn::parse_str("mcp, core = false").unwrap();
        assert!(!attr.mcp_core);
    }

    #[test]
    fn api_doc_core_alone_does_not_opt_in() {
        let attr: ApiDocAttr = syn::parse_str("core").unwrap();
        assert!(attr.mcp_core && !attr.mcp_tool);
    }

    #[test]
    fn api_doc_core_survives_a_merge() {
        let mut first: ApiDocAttr = syn::parse_str("mcp").unwrap();
        let second: ApiDocAttr = syn::parse_str("core").unwrap();
        first.absorb(second);
        assert!(first.mcp_tool && first.mcp_core);
    }

    #[test]
    fn api_doc_unknown_key_error_lists_core_and_webmcp() {
        let err = syn::parse_str::<ApiDocAttr>("bogus = 1").err().unwrap();
        assert!(err.to_string().contains("task, core, webmcp."), "{err}");
    }

    #[test]
    fn api_doc_webmcp_flag_parses() {
        let attr: ApiDocAttr = syn::parse_str("webmcp").unwrap();
        assert!(attr.webmcp_tool && !attr.webmcp_exclude && !attr.mcp_tool);
        let attr: ApiDocAttr = syn::parse_str("webmcp = true").unwrap();
        assert!(attr.webmcp_tool);
        let attr: ApiDocAttr = syn::parse_str("webmcp = false").unwrap();
        assert!(attr.webmcp_exclude && !attr.webmcp_tool);
    }

    #[test]
    fn api_doc_mcp_does_not_imply_webmcp() {
        let attr: ApiDocAttr = syn::parse_str("mcp").unwrap();
        assert!(attr.mcp_tool && !attr.webmcp_tool);
        let attr: ApiDocAttr = syn::parse_str("mcp, webmcp").unwrap();
        assert!(attr.mcp_tool && attr.webmcp_tool);
    }

    #[test]
    fn api_doc_webmcp_survives_a_merge() {
        let mut first: ApiDocAttr = syn::parse_str("mcp").unwrap();
        first.absorb(syn::parse_str("webmcp").unwrap());
        first.absorb(syn::parse_str("summary = \"x\"").unwrap());
        assert!(first.webmcp_tool);
        let mut other: ApiDocAttr = syn::parse_str("summary = \"x\"").unwrap();
        other.absorb(syn::parse_str("webmcp = false").unwrap());
        assert!(other.webmcp_exclude);
    }

    #[test]
    fn api_doc_webmcp_fields_are_emitted() {
        let attr: ApiDocAttr = syn::parse_str("webmcp").unwrap();
        let ident = syn::Ident::new("handler", Span::call_site());
        let out = attr.emit_ident_fields(&ident).to_string();
        assert!(out.contains("webmcp_tool : true"), "{out}");
        assert!(out.contains("webmcp_exclude : false"), "{out}");
    }

    #[test]
    fn extract_path_params_handles_single() {
        assert_eq!(extract_path_params("/users/{id}"), vec!["id".to_owned()]);
    }

    #[test]
    fn extract_path_params_handles_multiple() {
        assert_eq!(
            extract_path_params("/posts/{year}/{slug}"),
            vec!["year".to_owned(), "slug".to_owned()]
        );
    }

    #[test]
    fn extract_path_params_handles_regex_prefix() {
        assert_eq!(
            extract_path_params("/users/{id:[0-9]+}"),
            vec!["id".to_owned()]
        );
    }

    #[test]
    fn extract_path_params_returns_empty_for_static() {
        assert_eq!(extract_path_params("/hello"), [] as [String; 0]);
        assert_eq!(extract_path_params("/"), [] as [String; 0]);
    }

    #[test]
    fn extract_path_params_ignores_unclosed_braces() {
        assert_eq!(extract_path_params("/oops/{broken"), [] as [String; 0]);
    }

    #[test]
    fn extract_path_params_skips_escaped_braces() {
        // `{{hello}}` is a static route segment, not a path parameter.
        assert_eq!(extract_path_params("/{{hello}}"), [] as [String; 0]);
        // Escaped brace followed by a real param.
        assert_eq!(
            extract_path_params("/{{literal}}/{id}"),
            vec!["id".to_owned()]
        );
    }

    #[test]
    fn secured_roles_marker_extracts_roles() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_SECURED_ROLES: &[&str] = &["admin", "editor"];
            }
        };

        assert_eq!(
            extract_secured_roles_marker(&input_fn),
            Some(vec!["admin".to_owned(), "editor".to_owned()])
        );
    }

    #[test]
    fn secured_roles_marker_extracts_empty_roles() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_SECURED_ROLES: &[&str] = &[];
            }
        };

        assert_eq!(extract_secured_roles_marker(&input_fn), Some(Vec::new()));
    }

    #[test]
    fn secured_roles_marker_extracts_nested_roles() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                {
                    const __AUTUMN_SECURED_ROLES: &[&str] = &["admin"];
                }
            }
        };

        assert_eq!(
            extract_secured_roles_marker(&input_fn),
            Some(vec!["admin".to_owned()])
        );
    }

    // ── Scopes extraction (#1158) ────────────────────────────────────────────

    #[test]
    fn extract_secured_scopes_from_attribute_scopes_only() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[secured(scopes = ["posts:read", "posts:write"])]
            async fn handler() {}
        };
        let attr = input_fn
            .attrs
            .iter()
            .find(|a| a.path().is_ident("secured"))
            .unwrap();
        assert_eq!(
            extract_secured_scopes(attr),
            vec!["posts:read".to_owned(), "posts:write".to_owned()]
        );
    }

    #[test]
    fn extract_secured_scopes_from_attribute_roles_and_scopes() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[secured("admin", scopes = ["posts:write"])]
            async fn handler() {}
        };
        let attr = input_fn
            .attrs
            .iter()
            .find(|a| a.path().is_ident("secured"))
            .unwrap();
        assert_eq!(extract_secured_scopes(attr), vec!["posts:write".to_owned()]);
    }

    #[test]
    fn extract_secured_scopes_returns_empty_for_roles_only() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[secured("admin")]
            async fn handler() {}
        };
        let attr = input_fn
            .attrs
            .iter()
            .find(|a| a.path().is_ident("secured"))
            .unwrap();
        assert_eq!(extract_secured_scopes(attr), [] as [String; 0]);
    }

    #[test]
    fn scopes_marker_extracted_from_handler_body() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_SECURED_SCOPES: &[&str] = &["posts:write", "posts:delete"];
            }
        };
        assert_eq!(
            extract_secured_scopes_marker(&input_fn),
            Some(vec!["posts:write".to_owned(), "posts:delete".to_owned()])
        );
    }

    #[test]
    fn scopes_marker_empty_array_returns_some_empty_vec() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_SECURED_SCOPES: &[&str] = &[];
            }
        };
        assert_eq!(
            extract_secured_scopes_marker(&input_fn),
            Some(Vec::<String>::new())
        );
    }

    #[test]
    fn scopes_marker_absent_returns_none() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {}
        };
        assert_eq!(extract_secured_scopes_marker(&input_fn), None);
    }

    // ── #[public] detection (#1604) ──────────────────────────────────────────

    #[test]
    fn is_public_detects_attribute() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[public]
            async fn handler() {}
        };
        assert!(is_public(&input_fn));
    }

    #[test]
    fn is_public_detects_body_marker() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_PUBLIC: () = ();
            }
        };
        assert!(is_public(&input_fn));
    }

    #[test]
    fn is_public_false_for_unannotated() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {}
        };
        assert!(!is_public(&input_fn));
    }

    // ── #[authorize] binding extraction (#1627) ──────────────────────────────

    #[test]
    fn extract_authorize_bindings_from_attribute() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[authorize("update", resource = Note)]
            async fn handler(note: Note) {}
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            vec![("update".to_owned(), "Note".to_owned())]
        );
    }

    #[test]
    fn extract_authorize_bindings_from_marker() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[("update", "Note")];
            }
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            vec![("update".to_owned(), "Note".to_owned())]
        );
    }

    #[test]
    fn extract_authorize_bindings_from_nested_marker() {
        // A guard that expanded after `#[authorize]` wraps the marker in
        // `(async move { … }).await`, one level per stacked guard.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                let __autumn_inner: ::autumn_web::reexports::axum::response::Response =
                    (async move {
                        const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[("update", "Note")];
                    })
                    .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            vec![("update".to_owned(), "Note".to_owned())]
        );
    }

    #[test]
    fn extract_authorize_bindings_is_empty_without_authorize() {
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {}
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            Vec::<(String, String)>::new()
        );
    }

    #[test]
    fn extract_authorize_bindings_handles_string_literal_resource() {
        // `resource = "Note"` is accepted by the #[authorize] grammar and
        // normalized back to an identifier; reading the attribute through that
        // same parser keeps both spellings recording the same binding.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[authorize("update", resource = "Note")]
            async fn handler(note: Note) {}
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            vec![("update".to_owned(), "Note".to_owned())]
        );
    }

    #[test]
    fn extract_authorize_bindings_unions_attr_and_marker() {
        // A mixed stack (`#[authorize(A)]` above the route macro, `#[authorize(B)]`
        // below it) leaves one marker and one attribute — both are real bindings,
        // so neither case may short-circuit the other. The marker comes from the
        // attribute *above* the route macro, so source order puts it first.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[authorize("publish", resource = Note)]
            async fn handler(note: Note) {
                const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[("update", "Note")];
            }
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            vec![
                ("update".to_owned(), "Note".to_owned()),
                ("publish".to_owned(), "Note".to_owned()),
            ]
        );
    }

    #[test]
    fn extract_authorize_bindings_orders_stacked_markers_by_source() {
        // Two `#[authorize]`s above the route macro expand top-down: the first
        // (higher in source) is wrapped by the second, so its marker sits one
        // wrapper level *deeper*. Source order is therefore deepest-first, and
        // the walk must record nested markers before the level that wraps them.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[("second", "Note")];
                let __autumn_inner: ::autumn_web::reexports::axum::response::Response =
                    (async move {
                        const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] =
                            &[("first", "Note")];
                    })
                    .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            vec![
                ("first".to_owned(), "Note".to_owned()),
                ("second".to_owned(), "Note".to_owned()),
            ]
        );
    }

    #[test]
    fn secured_markers_survive_live_authorize_attribute() {
        // `#[secured]` ABOVE the route macro (already expanded into markers)
        // with `#[authorize]` BELOW it (still a live attribute): the marker
        // read must win over the authorize-attribute fallback, or the roles
        // and scopes silently drop to `&[]` while `secured` stays true.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            #[authorize("update", resource = Note)]
            async fn handler(note: Note) {
                const __AUTUMN_SECURED_ROLES: &[&str] = &["admin"];
                const __AUTUMN_SECURED_SCOPES: &[&str] = &["notes:write"];
            }
        };
        let (secured, roles, scopes) = extract_secured_info(&input_fn);
        assert!(secured);
        assert!(
            roles.to_string().contains("\"admin\""),
            "roles from an expanded #[secured] must survive a live #[authorize] attribute: {roles}"
        );
        assert!(
            scopes.to_string().contains("\"notes:write\""),
            "scopes must survive alongside the roles: {scopes}"
        );
    }

    #[test]
    fn public_marker_survives_generated_wrapper() {
        // `#[public]` above a wrapping guard (e.g. `#[throttle]`): the guard
        // buries the `__AUTUMN_PUBLIC` marker inside its generated
        // `(async move { … }).await` body. The walk must descend that wrapper,
        // or the route silently loses `public: true` and false-fails the
        // coverage gate as `unclassified`.
        let public = crate::public::public_macro(
            quote::quote! {},
            quote::quote! { async fn h() -> &'static str { "ok" } },
        );
        let throttled =
            crate::throttle::throttle_macro(quote::quote! { limit = 5, per = "1m" }, public);
        let parsed = crate::param_helpers::extract_fn_item(throttled, "h");
        assert!(
            is_public(&parsed),
            "the public marker must survive a #[throttle] wrapper"
        );
    }

    #[test]
    fn secured_roles_survive_authorize_wrapper() {
        // `#[secured]`'s role markers end up under the
        // `let __autumn_inner: T = (async move { … }).await;` wrapper when a
        // guard expands after it. The roles walk must descend that shape, like
        // the authorize-binding walk does, or the roles silently vanish.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[("update", "Note")];
                let __autumn_inner: ::autumn_web::reexports::axum::response::Response =
                    (async move {
                        const __AUTUMN_SECURED_ROLES: &[&str] = &["admin"];
                        const __AUTUMN_SECURED_SCOPES: &[&str] = &["notes:write"];
                    })
                    .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let (secured, roles, scopes) = extract_secured_info(&input_fn);
        assert!(secured);
        assert!(
            roles.to_string().contains("\"admin\""),
            "roles buried under a generated wrapper must be recovered: {roles}"
        );
        assert!(
            scopes.to_string().contains("\"notes:write\""),
            "scopes buried under a generated wrapper must be recovered: {scopes}"
        );
    }

    #[test]
    fn extract_authorize_bindings_ignores_malformed_marker() {
        // A same-named const of a foreign shape is not ours to interpret: it
        // contributes nothing rather than panicking on the unexpected AST.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() {
                const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, u32)] = &[("update", 1)];
            }
        };
        assert_eq!(
            extract_authorize_bindings(&input_fn),
            Vec::<(String, String)>::new()
        );
    }

    // ── Response-schema recovery across guard reordering (#1677) ────────────
    //
    // When a body guard (`#[secured]`, `#[step_up]`, `#[authorize]`,
    // `#[throttle]`) is written ABOVE the route method attribute, it expands
    // first and rewrites `sig.output` to `Response` before the route macro
    // ever sees the handler. Each guard leaves the pre-rewrite type behind as
    // `let __autumn_inner: #ty = (async move { … }).await;`, so
    // `infer_response_body` must recover it from there instead of reading the
    // (by then rewritten) `sig.output`.

    #[test]
    fn infer_response_body_reads_sig_output_when_no_guard_marker_present() {
        // Baseline: an unguarded handler (or the route-attribute-outermost
        // ordering, where guards haven't expanded yet) is unaffected — the
        // plain `sig.output` path must keep working exactly as before.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::Json<Created> { todo!() }
        };
        let schema = infer_response_body(&input_fn)
            .expect("a bare Json<T> return type must produce a response schema");
        assert!(
            schema.to_string().contains("\"Created\""),
            "schema should name the Created type: {schema}"
        );
    }

    #[test]
    fn infer_response_body_recovers_type_under_single_guard_wrapper() {
        // Shape emitted by any one of the four body guards when it expands
        // before the route macro: `sig.output` already reads `Response`, and
        // the real type is only recoverable from the `__autumn_inner` binding.
        // The leading marker const is what every real guard unconditionally
        // emits ahead of that binding (here, #[throttle]'s).
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
                let __autumn_inner: ::autumn_web::reexports::axum::Json<Created> =
                    (async move { todo!() }).await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn).expect(
            "a Json<T> return type rewritten to Response by a single guard must still be \
             recoverable from the __autumn_inner marker",
        );
        assert!(
            schema.to_string().contains("\"Created\""),
            "recovered schema should name the Created type: {schema}"
        );
    }

    #[test]
    fn infer_response_body_recovers_innermost_type_under_stacked_guards() {
        // Two guards stacked above the route macro: the outer one's own
        // `__autumn_inner` binding necessarily reads `Response` (the inner
        // guard already rewrote `sig.output` by the time the outer guard
        // captured its own binding), so only the innermost binding carries
        // the type the user actually wrote. Each level carries its own
        // guard's marker const, matching real (e.g. #[secured] above
        // #[throttle]) output.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_SECURED_ROLES: &[&str] = &[];
                let __autumn_inner: ::autumn_web::reexports::axum::response::Response = (async move {
                    const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
                    let __autumn_inner: ::autumn_web::reexports::axum::Json<Created> =
                        (async move { todo!() }).await;
                    ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
                })
                .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn).expect(
            "the innermost __autumn_inner binding must be recovered even under a second, \
             outer guard wrapper",
        );
        assert!(
            schema.to_string().contains("\"Created\""),
            "recovered schema should name the innermost Created type, not Response: {schema}"
        );
    }

    #[test]
    fn infer_response_body_none_when_guard_wraps_unit_return() {
        // A guard over a `()`-returning handler emits no explicit type
        // annotation at all (see `original_response`'s `ReturnType::Default`
        // arm in each guard), so there is nothing to recover — this must not
        // panic and must simply infer no response schema, same as today.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
                let __autumn_inner: () = (async move { todo!() }).await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        assert!(infer_response_body(&input_fn).is_none());
    }

    #[test]
    fn infer_response_body_recovers_result_wrapped_json_under_guard() {
        // `Result<Json<T>, E>` / `AutumnResult<Json<T>>` returns must still
        // unwrap the Ok arm after being recovered from the marker, exactly as
        // they do when read directly off `sig.output`.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
                let __autumn_inner: AutumnResult<::autumn_web::reexports::axum::Json<Created>> =
                    (async move { todo!() }).await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn)
            .expect("Result-wrapped Json<T> recovered from the marker must still be inferred");
        assert!(
            schema.to_string().contains("\"Created\""),
            "recovered schema should name the Created type: {schema}"
        );
    }

    #[test]
    fn infer_response_body_ignores_unrelated_local_named_autumn_inner() {
        // Recovery must key off the guard's exact structural shape (a
        // `__autumn_inner: T` binding immediately followed by the generated
        // `IntoResponse::into_response(__autumn_inner)` tail, with a guard
        // marker const preceding it), not a bare name-and-type match
        // anywhere in the body. An UNGUARDED handler whose correctly-declared
        // `sig.output` is `Json<Real>`, but which happens to also declare an
        // unrelated local matching the marker's name (not its position),
        // must still infer `Real` from `sig.output` — never the incidental
        // local's own type.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::Json<Real> {
                let __autumn_inner: ::autumn_web::reexports::axum::Json<Fake> =
                    (async move { compute() }).await;
                do_something(__autumn_inner);
                ::autumn_web::reexports::axum::Json(Real::default())
            }
        };
        let schema = infer_response_body(&input_fn)
            .expect("the correctly-declared sig.output must still be inferred");
        let rendered = schema.to_string();
        assert!(
            rendered.contains("\"Real\""),
            "must recover the handler's real declared return type, not the incidental local: \
             {rendered}"
        );
        assert!(
            !rendered.contains("\"Fake\""),
            "must not be fooled by an unrelated local that merely shares the marker's name: \
             {rendered}"
        );
    }

    #[test]
    fn infer_response_body_ignores_position_and_tail_match_without_a_guard_marker() {
        // A deeper trap than the name-only collision above: an UNGUARDED
        // handler whose body happens to end in the *exact* two-statement
        // shape a guard emits (right position, right tail call, right
        // identifier) — but with no guard marker const anywhere, because no
        // guard actually ran. Position and tail alone cannot tell this apart
        // from real guard output; only the marker requirement can, and it
        // must still recover the correctly-declared `Json<Real>` from
        // `sig.output`, not the coincidental `Json<Fake>`.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::Json<Real> {
                let __autumn_inner: ::autumn_web::reexports::axum::Json<Fake> =
                    (async move { compute() }).await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn)
            .expect("the correctly-declared sig.output must still be inferred");
        let rendered = schema.to_string();
        assert!(
            rendered.contains("\"Real\""),
            "must recover the handler's real declared return type: {rendered}"
        );
        assert!(
            !rendered.contains("\"Fake\""),
            "must not be fooled by a coincidental position+tail match with no guard marker: \
             {rendered}"
        );
    }

    #[test]
    fn infer_response_body_ignores_a_nested_coincidental_match_with_no_marker_of_its_own() {
        // The same trap one level deeper: a single REAL guard correctly
        // wraps a `Json<Real>` handler (marker present, so its own binding is
        // trusted) — but the user's *original* body, now nested one level
        // inside the guard's `(async move { … }).await`, itself happens to
        // end in the same two-statement shape with no marker of its own.
        // Recursing into that inner block must not find a "deeper" binding
        // there: the correct answer is the guard's own outer `Real`, not the
        // inner accidental `Fake`.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
                let __autumn_inner: ::autumn_web::reexports::axum::Json<Real> = (async move {
                    let __autumn_inner: ::autumn_web::reexports::axum::Json<Fake> =
                        (async move { compute() }).await;
                    ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
                })
                .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn)
            .expect("the real guard's own outer binding must still be recovered");
        let rendered = schema.to_string();
        assert!(
            rendered.contains("\"Real\""),
            "must recover the real guard's own type, not the nested coincidental one: {rendered}"
        );
        assert!(
            !rendered.contains("\"Fake\""),
            "must not descend into a nested block that lacks its own guard marker: {rendered}"
        );
    }

    #[test]
    fn infer_response_body_ignores_a_nested_coincidental_match_under_a_markerless_gate() {
        // The gate-parameter counterpart of the test above (Codex review,
        // #2508): #[step_up]/#[throttle] leave no marker const in the body,
        // so their single real wrapper is accepted by spending the one unit
        // of `markerless_gate_budget` the `__AutumnThrottleGate_` parameter
        // earns — but that budget must not also cover a *second*,
        // coincidental match nested one level deeper inside the user's own
        // body. If it did, recovery would report the inner accidental
        // `Fake` instead of the real guard's own `Real`.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler(
                _: __AutumnThrottleGate_handler,
            ) -> ::autumn_web::reexports::axum::response::Response {
                let __autumn_inner: ::autumn_web::reexports::axum::Json<Real> = (async move {
                    let __autumn_inner: ::autumn_web::reexports::axum::Json<Fake> =
                        (async move { compute() }).await;
                    ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
                })
                .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn)
            .expect("the real gate's own outer binding must still be recovered");
        let rendered = schema.to_string();
        assert!(
            rendered.contains("\"Real\""),
            "must recover the real gate's own type, not the nested coincidental one: {rendered}"
        );
        assert!(
            !rendered.contains("\"Fake\""),
            "must not spend the same gate parameter's budget twice on an unrelated nested \
             coincidence: {rendered}"
        );
    }

    #[test]
    fn infer_response_body_recovers_innermost_type_under_triple_stacked_guards() {
        // Three guards stacked above the route macro (e.g. #[secured] above
        // #[authorize] above #[throttle] above #[post]): each of the two
        // outer __autumn_inner bindings necessarily reads back Response, so
        // only the third, innermost level carries the real type. Each level
        // carries its own guard's marker const.
        let input_fn: syn::ItemFn = syn::parse_quote! {
            async fn handler() -> ::autumn_web::reexports::axum::response::Response {
                const __AUTUMN_SECURED_ROLES: &[&str] = &[];
                let __autumn_inner: ::autumn_web::reexports::axum::response::Response = (async move {
                    const __AUTUMN_AUTHORIZE_BINDINGS: &[(&str, &str)] = &[];
                    let __autumn_inner: ::autumn_web::reexports::axum::response::Response = (async move {
                        const __AUTUMN_THROTTLE_ROUTE_ID: &str = "handler";
                        let __autumn_inner: ::autumn_web::reexports::axum::Json<Created> =
                            (async move { todo!() }).await;
                        ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
                    })
                    .await;
                    ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
                })
                .await;
                ::autumn_web::reexports::axum::response::IntoResponse::into_response(__autumn_inner)
            }
        };
        let schema = infer_response_body(&input_fn).expect(
            "the innermost __autumn_inner binding must be recovered through three levels of \
             guard wrapping",
        );
        assert!(
            schema.to_string().contains("\"Created\""),
            "recovered schema should name the innermost Created type: {schema}"
        );
    }
}