server-less-macros 0.6.0

Proc macros for server-less
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
//! CLI generation macro.
//!
//! Generates clap-based CLI applications from impl blocks with automatic command generation.
//!
//! # Command Generation
//!
//! Each `pub` method with `&self` becomes a subcommand:
//! - Method name converted to kebab-case: `create_user` → `create-user`
//! - Doc comments become command descriptions
//! - Parameters become command arguments/options
//!
//! # Method Attributes
//!
//! - `#[cli(name = "...")]` — Override the subcommand name (works on leaf methods and mount points)
//! - `#[cli(skip)]` — Exclude a method from becoming a subcommand
//! - `#[cli(helper)]` — Self-documenting alias for `skip` (for display formatters, internal logic)
//! - `#[cli(hidden)]` — Include the subcommand but hide it from `--help`
//! - `#[cli(default)]` — Make this the default action when no subcommand is given
//! - `#[cli(display_with = "fn_name")]` — Use a custom function for text output formatting.
//!   The function is called as `self.fn_name(&return_value)` and can live in any impl block
//!   on the same type (not just the `#[cli]` block). Only affects text output; `--json`/`--jq`
//!   bypass this and use serde serialization.
//!
//! # Mount Points
//!
//! Methods returning `&T` become subcommand groups (mount points):
//! - Static: `fn users(&self) -> &Users` → `app users <subcommand>`
//! - Slug: `fn user(&self, id: UserId) -> &UserService` → `app user <id> <subcommand>`
//!
//! The mounted type must implement `CliSubcommand` (generated by `#[cli]`).
//!
//! # Parameter Mapping
//!
//! - Required parameters → Positional arguments
//! - `Option<T>` parameters → Optional flags (`--name <NAME>`)
//! - `bool` parameters → Boolean flags (`--verbose`)
//!
//! # Generated Methods
//!
//! **Sync entrypoints** (suppressed by `#[cli(no_sync)]`):
//! - `cli_command() -> clap::Command` - Complete CLI application
//! - `cli_run()` - Run from process args using an internally-created Tokio runtime
//! - `cli_run_with(args)` - Run with custom args (same runtime behaviour as `cli_run`)
//!
//! **Async entrypoints** (suppressed by `#[cli(no_async)]`):
//! - `cli_run_async()` - Run from process args; caller supplies the async runtime
//! - `cli_run_with_async(args)` - Run with custom args; caller supplies the async runtime
//!
//! **Trait methods** (always generated, never suppressed):
//! - `cli_dispatch(&self, matches)` - Sync dispatch (part of `CliSubcommand`)
//! - `cli_dispatch_async(&self, matches)` - Async dispatch (part of `CliSubcommand`)
//!
//! The `cli_dispatch` / `cli_dispatch_async` trait methods are never suppressed because
//! they are the integration point used by `#[program]` and other presets for composition.
//!
//! Also implements `CliSubcommand` trait for composition.
//!
//! # Example
//!
//! ```ignore
//! use server_less::cli;
//!
//! struct MyApp;
//!
//! #[cli(name = "myapp", version = "1.0")]
//! impl MyApp {
//!     /// Create a new user
//!     fn create_user(&self, name: String, email: String) {
//!         println!("Creating user: {}", name);
//!     }
//!
//!     /// Delete a user by ID
//!     fn delete_user(&self, id: u32) {
//!         println!("Deleting user: {}", id);
//!     }
//! }
//!
//! // Use it:
//! let app = MyApp;
//! let matches = MyApp::cli_command().get_matches();
//! app.cli_run_with(&matches);
//! ```
//!
//! # Command Line Usage
//!
//! ```bash
//! myapp create-user "Alice" "alice@example.com"
//! myapp delete-user 123
//! myapp --help
//! ```

use heck::ToKebabCase;

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use server_less_parse::{
    MethodInfo, ParamInfo, extract_groups, extract_map_type, extract_methods, extract_option_type,
    extract_vec_type, get_impl_name, is_unit_type, partition_methods, resolve_method_group,
};
use syn::{ItemImpl, Token, parse::Parse};

// Import Context helpers
use crate::context::{
    generate_cli_context_extraction, partition_context_params,
};
use crate::app::extract_app_meta;
use crate::server_attrs::{has_server_hidden, has_server_skip, validate_server_attrs};

/// Arguments for the #[cli] attribute
#[derive(Default)]
pub(crate) struct CliArgs {
    pub name: Option<String>,
    pub version: Option<String>,
    pub description: Option<String>,
    pub homepage: Option<String>,
    pub global: Vec<(String, Option<String>)>,
    pub defaults: Option<String>,
    /// Suppress the sync convenience entrypoints `cli_run()` and `cli_run_with()`.
    ///
    /// The underlying `CliSubcommand::cli_dispatch()` trait method is **not** suppressed —
    /// it remains on the trait and is used by `#[program]` and other presets for composition.
    /// Use `no_sync` when you want to provide your own sync entrypoint or when you only
    /// use the async path.
    pub no_sync: bool,
    /// Suppress the async convenience entrypoints `cli_run_async()` and `cli_run_with_async()`.
    ///
    /// The underlying `CliSubcommand::cli_dispatch_async()` trait method is **not** suppressed —
    /// it remains on the trait and is used by `#[program]` and other presets for composition.
    /// Use `no_async` when all methods are synchronous and you want to keep the generated
    /// impl free of async items.
    pub no_async: bool,
    /// Config struct type path, e.g. `MyConfig`. When set, a `config` subcommand is generated.
    pub config_ty: Option<syn::Path>,
    /// Name of the generated config subcommand (default: `"config"`).
    pub config_cmd_name: Option<String>,
    /// Whether to prepend the program name to the description: `"name - description"`.
    /// Default: `true` when both name and description are set. Set to `false` to use
    /// the description verbatim.
    pub description_prefix: Option<bool>,
    /// Inject the `--manual` whole-subtree reference flag. Default `true`.
    /// `#[cli(manual = false)]` drops the flag globally; a colliding `manual`
    /// parameter then becomes legal.
    pub manual: Option<bool>,
    /// Inject the per-leaf `--input-schema` flag. Default `true`.
    pub input_schema: Option<bool>,
    /// Inject the per-leaf `--output-schema` flag. Default `true`.
    pub output_schema: Option<bool>,
}

/// Which injected meta-surface flags are enabled for a `#[cli]` projection.
///
/// Threaded into leaf match-arm generation so the arms only consult flags that
/// were actually registered on the clap `Command` — calling `get_flag` on an
/// unregistered id panics at runtime.
#[derive(Clone, Copy)]
pub(crate) struct MetaFlags {
    pub manual: bool,
    pub input_schema: bool,
    pub output_schema: bool,
}

impl Parse for CliArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = CliArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;

            // Bare flags (no `= value`)
            match ident.to_string().as_str() {
                "no_sync" => {
                    args.no_sync = true;
                    if input.peek(Token![,]) {
                        input.parse::<Token![,]>()?;
                    }
                    continue;
                }
                "no_async" => {
                    args.no_async = true;
                    if input.peek(Token![,]) {
                        input.parse::<Token![,]>()?;
                    }
                    continue;
                }
                "description_prefix" if !input.peek(Token![=]) => {
                    args.description_prefix = Some(true);
                    if input.peek(Token![,]) {
                        input.parse::<Token![,]>()?;
                    }
                    continue;
                }
                _ => {}
            }

            input.parse::<Token![=]>()?;

            match ident.to_string().as_str() {
                "name" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.name = Some(lit.value());
                }
                "version" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.version = Some(lit.value());
                }
                "description" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.description = Some(lit.value());
                }
                "homepage" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.homepage = Some(lit.value());
                }
                "global" => {
                    let content;
                    syn::bracketed!(content in input);
                    while !content.is_empty() {
                        let flag: syn::Ident = content.parse()?;
                        let help = if content.peek(Token![=]) {
                            content.parse::<Token![=]>()?;
                            let lit: syn::LitStr = content.parse()?;
                            Some(lit.value())
                        } else {
                            None
                        };
                        args.global.push((flag.to_string(), help));
                        if content.peek(Token![,]) {
                            content.parse::<Token![,]>()?;
                        }
                    }
                }
                "defaults" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.defaults = Some(lit.value());
                }
                "description_prefix" => {
                    let lit: syn::LitBool = input.parse()?;
                    args.description_prefix = Some(lit.value());
                }
                "manual" => {
                    let lit: syn::LitBool = input.parse()?;
                    args.manual = Some(lit.value());
                }
                "input_schema" => {
                    let lit: syn::LitBool = input.parse()?;
                    args.input_schema = Some(lit.value());
                }
                "output_schema" => {
                    let lit: syn::LitBool = input.parse()?;
                    args.output_schema = Some(lit.value());
                }
                other => {
                    if other == "about" {
                        return Err(syn::Error::new(
                            ident.span(),
                            "unknown argument `about` — renamed to `description` in 0.4.0\n\
                             \n\
                             Example: #[cli(description = \"My CLI tool\")]",
                        ));
                    }
                    if other == "name_prefix" {
                        return Err(syn::Error::new(
                            ident.span(),
                            "unknown argument `name_prefix` — renamed to `description_prefix`\n\
                             \n\
                             Example: #[cli(description_prefix = false)]",
                        ));
                    }
                    const VALID: &[&str] = &[
                        "name", "version", "description", "homepage", "global",
                        "defaults", "no_sync", "no_async", "description_prefix",
                        "manual", "input_schema", "output_schema",
                    ];
                    let suggestion = crate::did_you_mean(other, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        ident.span(),
                        format!(
                            "unknown argument `{other}`{suggestion}\n\
                             \n\
                             Valid arguments: name, version, description, homepage, global, defaults, no_sync, no_async, description_prefix, manual, input_schema, output_schema\n\
                             \n\
                             Example: #[cli(name = \"my-app\", description = \"My CLI tool\")]\n\
                             Bare flags: #[cli(no_sync)] or #[cli(no_async)]\n\
                             \n\
                             Related: #[program] preset (CLI + markdown docs), #[markdown] (standalone docs)"
                        ),
                    ));
                }
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

/// Check if a method has `#[cli(skip)]`, `#[cli(helper)]`, or `#[server(skip)]`.
///
/// `#[cli(helper)]` is a self-documenting alias for `#[cli(skip)]` — use it on
/// display formatters, internal logic, and other methods that should not become
/// CLI subcommands. Alternatively, place helper methods in a separate impl block
/// (without `#[cli]`).
fn has_cli_skip(method: &MethodInfo) -> bool {
    if has_server_skip(method) {
        return true;
    }
    for attr in &method.method.attrs {
        if attr.path().is_ident("cli") {
            let mut found = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("skip") || meta.path.is_ident("helper") {
                    found = true;
                }
                if meta.input.peek(syn::Token![=]) {
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                }
                Ok(())
            });
            if found {
                return true;
            }
        }
    }
    false
}

/// Check if a method has `#[cli(default)]`.
fn has_cli_default(method: &MethodInfo) -> bool {
    for attr in &method.method.attrs {
        if attr.path().is_ident("cli") {
            let mut found = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("default") {
                    found = true;
                }
                if meta.input.peek(syn::Token![=]) {
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                }
                Ok(())
            });
            if found {
                return true;
            }
        }
    }
    false
}

/// Check if a method has `#[cli(manual = false)]` — excludes this leaf/mount from
/// the aggregated `--manual` reference document while leaving the command itself
/// intact. Distinct from `#[cli(hidden)]`, which also removes it from help.
fn has_cli_manual_false(method: &MethodInfo) -> bool {
    for attr in &method.method.attrs {
        if attr.path().is_ident("cli") {
            let mut disabled = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("manual") && meta.input.peek(syn::Token![=]) {
                    let value = meta.value()?;
                    let lit: syn::LitBool = value.parse()?;
                    if !lit.value() {
                        disabled = true;
                    }
                } else if meta.input.peek(syn::Token![=]) {
                    let _: syn::Expr = meta.value()?.parse()?;
                }
                Ok(())
            });
            if disabled {
                return true;
            }
        }
    }
    false
}

/// Compile error if any leaf/slug parameter's kebab flag name collides with a
/// **currently-injected** global meta-surface flag. Disabling a meta-surface frees
/// its name. See docs/design/cli-manual-projection.md, "Collision guard".
fn check_reserved_flag_collisions(
    partitioned: &server_less_parse::PartitionedMethods,
    meta: MetaFlags,
    global_flags: &[String],
) -> syn::Result<()> {
    // Build the reserved set for a command whose meta-surfaces are governed by
    // `surfaces`. (flag-name, "what reserves it"). The four always-on format flags
    // are unconditional; the three meta-surfaces are reserved only while enabled.
    let reserved_for = |surfaces: MetaFlags| -> Vec<(&'static str, &'static str)> {
        let mut r: Vec<(&str, &str)> = vec![
            ("json", "the --json output format"),
            ("jsonl", "the --jsonl output format"),
            ("jq", "the --jq output filter"),
            ("params-json", "the --params-json bulk input flag"),
        ];
        if surfaces.manual {
            r.push((
                "manual",
                "the --manual reference surface (disable with #[cli(manual = false)])",
            ));
        }
        if surfaces.input_schema {
            r.push((
                "input-schema",
                "the --input-schema surface (disable with #[cli(input_schema = false)])",
            ));
        }
        if surfaces.output_schema {
            r.push((
                "output-schema",
                "the --output-schema surface (disable with #[cli(output_schema = false)])",
            ));
        }
        r
    };

    // Leaf params register on *this* command, so they collide with this command's
    // injected flags — governed by `meta`. Slug-mount params register on the *child*
    // command (the mount's own `#[cli]`), whose meta-surfaces default on and are not
    // visible here; reserve all three conservatively so we never miss a collision the
    // child would hit at clap-build time.
    let all_on = MetaFlags { manual: true, input_schema: true, output_schema: true };
    let leaf_reserved = reserved_for(meta);
    let slug_reserved = reserved_for(all_on);

    // Declared `global = [...]` flags are registered on the root with `.global(true)`,
    // so they propagate into every subcommand's matches. A regular parameter whose flag
    // name matches one would make clap panic at runtime (duplicate arg id) — and, since
    // globals are delivered solely through the `CliGlobals` sink, such a param would
    // *look* like it receives the global but never does. Reserve every declared global's
    // kebab name on both leaf and slug commands so the collision is a loud compile error,
    // never a silent footgun. (This is what replaces the legacy receive-via-matching-param
    // path: a matching param is now rejected, not silently auto-filled.)
    let global_reserved: Vec<(String, &'static str)> = global_flags
        .iter()
        .map(|g| {
            (
                g.replace('_', "-"),
                "a declared `global = [...]` flag — delivered via the CliGlobals sink, \
                 not method params",
            )
        })
        .collect();

    let groups = [
        (&partitioned.leaf, &leaf_reserved),
        (&partitioned.slug_mounts, &slug_reserved),
    ];
    for (methods, reserved) in groups {
        for m in methods.iter() {
            let (_, regular) = partition_context_params(&m.params)?;
            for p in &regular {
                let kebab = cli_param_name(p);
                if let Some((flag, what)) = reserved.iter().find(|(name, _)| *name == kebab) {
                    return Err(syn::Error::new(
                        p.name.span(),
                        format!(
                            "parameter `{param}` collides with the injected `--{flag}` global flag — {what}\n\
                             \n\
                             Each #[cli] command receives built-in global flags; a parameter whose \
                             flag name matches one would make clap panic at runtime. Rename the Rust \
                             parameter, or disable the conflicting meta-surface (e.g. \
                             #[cli(manual = false)]).",
                            param = p.name_str(),
                        ),
                    ));
                }
                if let Some((flag, what)) =
                    global_reserved.iter().find(|(name, _)| name == &kebab)
                {
                    return Err(syn::Error::new(
                        p.name.span(),
                        format!(
                            "parameter `{param}` collides with `--{flag}` — {what}\n\
                             \n\
                             A declared `global = [...]` flag is registered on the root with \
                             `.global(true)` and is delivered only through the `CliGlobals` sink \
                             (`set_global_flag`). A method parameter that shares its flag name would \
                             collide with the root flag at clap-build time and would never be \
                             auto-filled from the global. Rename the parameter, and read the global's \
                             value from your `CliGlobals` impl instead.",
                            param = p.name_str(),
                        ),
                    ));
                }
            }
        }
    }
    Ok(())
}

/// Check if a method has `#[cli(hidden)]` or `#[server(hidden)]`.
fn has_cli_hidden(method: &MethodInfo) -> bool {
    if has_server_hidden(method) {
        return true;
    }
    for attr in &method.method.attrs {
        if attr.path().is_ident("cli") {
            let mut found = false;
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("hidden") {
                    found = true;
                }
                if meta.input.peek(syn::Token![=]) {
                    let _: proc_macro2::TokenStream = meta.value()?.parse()?;
                }
                Ok(())
            });
            if found {
                return true;
            }
        }
    }
    false
}

/// Extract `#[cli(display_with = "fn_name")]` from a method, if present.
fn get_display_with(method: &MethodInfo) -> Option<syn::Path> {
    for attr in &method.method.attrs {
        if attr.path().is_ident("cli") {
            let mut found = None;
            let result = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("display_with") {
                    let value = meta.value()?;
                    let lit: syn::LitStr = value.parse()?;
                    found = Some(lit.parse::<syn::Path>()?);
                    Ok(())
                } else {
                    // Skip unrecognized keys; they're handled elsewhere.
                    // Consume the value if present (key = value) or skip bare flags.
                    // Use syn::Expr (not TokenStream) to avoid greedily consuming subsequent
                    // comma-separated keys like `name = "foo", display_with = "bar"`.
                    if meta.input.peek(Token![=]) {
                        let _: syn::Expr = meta.value()?.parse()?;
                    }
                    Ok(())
                }
            });
            if result.is_ok() {
                return found;
            }
        }
    }
    None
}

/// CLI-facing name for a method: `wire_name` if set, otherwise kebab-case of method name.
fn cli_name(method: &MethodInfo) -> String {
    method.wire_name_or(|n| n.to_kebab_case())
}

/// CLI-facing flag/arg name for a parameter: `#[param(name = "...")]` (`wire_name`) verbatim
/// if set, otherwise kebab-case of the Rust identifier. Used as the clap `Arg` id, the
/// `--long` flag, and the `get_flag`/`get_one` key, so the rename is honored end-to-end
/// (advertisement and extraction stay in lockstep). Honoring `wire_name` here is what
/// converts `#[param(name)]` from *ignored* to *macro-terminated*.
fn cli_param_name(param: &ParamInfo) -> String {
    match &param.wire_name {
        Some(w) => w.clone(),
        None => param.name_str().to_kebab_case(),
    }
}

/// Convert a `#[param(default = ...)]` value (stored by the parser as a Rust-literal
/// repr — `"\"foo\""` for strings, `"10"` for ints, `"true"` for bools) into the string
/// clap's `.default_value(...)` expects. String literals are unwrapped to their content;
/// numeric/bool literals pass through. clap re-parses the string through the arg's value
/// parser, so this round-trips back to the param's type.
fn clap_default_value(raw: &str) -> String {
    if raw.len() >= 2 && raw.starts_with('"') && raw.ends_with('"') {
        raw[1..raw.len() - 1].to_string()
    } else {
        raw.to_string()
    }
}

/// Build an ordered list of group display names.
///
/// When a registry exists, uses declaration order from `groups(...)`.
/// Only includes groups that have at least one method assigned.
fn build_group_order(
    methods: &[&MethodInfo],
    registry: &Option<server_less_parse::GroupRegistry>,
) -> syn::Result<Vec<String>> {
    match registry {
        Some(reg) => {
            // Use registry declaration order, filtered to groups with methods
            let used: std::collections::HashSet<String> = methods
                .iter()
                .filter_map(|m| m.group.clone())
                .collect();
            Ok(reg
                .groups
                .iter()
                .filter(|(id, _)| used.contains(id))
                .map(|(_, display)| display.clone())
                .collect())
        }
        None => {
            // No registry — resolve_method_group will error if any method has a group,
            // so this path only produces an empty vec.
            for m in methods {
                resolve_method_group(m, registry)?;
            }
            Ok(vec![])
        }
    }
}

/// Strip `#[cli(...)]` and `#[server(...)]` attributes from methods in the
/// impl block so they don't appear in the emitted user code.
fn strip_cli_attrs(impl_block: &ItemImpl) -> ItemImpl {
    let mut block = impl_block.clone();
    // Strip #[server(...)] from impl-level attrs (e.g. groups(...))
    block
        .attrs
        .retain(|attr| !attr.path().is_ident("server"));
    for item in &mut block.items {
        if let syn::ImplItem::Fn(method) = item {
            method
                .attrs
                .retain(|attr| !attr.path().is_ident("cli") && !attr.path().is_ident("server"));
            // Strip #[param(...)] from function parameters
            for input in &mut method.sig.inputs {
                if let syn::FnArg::Typed(pat_type) = input {
                    pat_type.attrs.retain(|attr| !attr.path().is_ident("param"));
                }
            }
        }
    }
    block
}

// partition_methods is now shared from server_less_parse

pub(crate) fn expand_cli(args: CliArgs, mut impl_block: ItemImpl) -> syn::Result<TokenStream2> {
    crate::reject_generic_impl(&impl_block)?;
    let app_meta = extract_app_meta(&mut impl_block.attrs);
    let args = CliArgs {
        name: args.name.or(app_meta.name),
        description: args.description.or(app_meta.description),
        version: args.version.or_else(|| app_meta.version.into_explicit()),
        homepage: args.homepage.or(app_meta.homepage),
        ..args
    };

    let struct_name = get_impl_name(&impl_block)?;
    let (impl_generics, _ty_generics, where_clause) = impl_block.generics.split_for_impl();
    let self_ty = &impl_block.self_ty;
    let methods = extract_methods(&impl_block)?;


    // NOTE: to_kebab_case() may produce unexpected forms for acronym-heavy names
    // (e.g. `HTTPServer` → `h-t-t-p-server`). Use `name = "..."` in `#[cli]` or `#[app]` to override.
    let app_name = args
        .name
        .unwrap_or_else(|| struct_name.to_string().to_kebab_case());
    let version_tokens = match args.version {
        Some(ref v) => quote! { #v },
        None => quote! { ::std::env!("CARGO_PKG_VERSION") },
    };
    let about = match (args.description.as_deref(), args.description_prefix) {
        (Some(desc), Some(false)) => desc.to_string(),
        (Some(desc), _) => format!("{app_name} - {desc}"),
        (None, _) => String::new(),
    };
    let global_flags_with_help = args.global;
    let global_flags: Vec<String> = global_flags_with_help
        .iter()
        .map(|(name, _)| name.clone())
        .collect();
    // When `global = [...]` is declared, force the `Self: CliGlobals` bound even if the
    // impl has no leaf methods to deliver from (mount-only services). The per-leaf
    // delivery already requires the bound; this covers the leaf-less edge so the
    // "declared global ⇒ named sink" invariant holds unconditionally. No blanket
    // default impl of `CliGlobals` exists, so this is a hard compile error on omission.
    let globals_bound_assert = if global_flags.is_empty() {
        quote! {}
    } else {
        quote! {
            let _ = <Self as ::server_less::CliGlobals>::set_global_flag;
        }
    };

    let has_defaults = args.defaults.is_some();
    let defaults_fn_ident = args
        .defaults
        .as_ref()
        .map(|name| syn::Ident::new(name, proc_macro2::Span::call_site()));
    let no_sync = args.no_sync;
    let no_async = args.no_async;

    // Injected meta-surface flags (default-on). When a toggle is `false` the flag
    // is not registered and the arms that consult it are elided.
    let meta = MetaFlags {
        manual: args.manual.unwrap_or(true),
        input_schema: args.input_schema.unwrap_or(true),
        output_schema: args.output_schema.unwrap_or(true),
    };

    for m in &methods {
        validate_server_attrs(m)?;
    }
    let partitioned = partition_methods(&methods, has_cli_skip);

    // Reserved-name collision guard: a regular parameter whose kebab flag name
    // collides with a *currently-injected* global flag is a compile error spanned
    // to the parameter. Disabling a meta-surface frees its name.
    check_reserved_flag_collisions(&partitioned, meta, &global_flags)?;

    // Resolve method groups — consider all methods (leaf + mounts) for group discovery
    let group_registry = extract_groups(&impl_block)?;
    let all_methods: Vec<&MethodInfo> = partitioned
        .leaf
        .iter()
        .chain(partitioned.static_mounts.iter())
        .chain(partitioned.slug_mounts.iter())
        .copied()
        .collect();
    let group_order = build_group_order(&all_methods, &group_registry)?;
    let has_groups = !group_order.is_empty();

    // Generate subcommands for leaf methods.
    // When groups exist, hide all leaf subcommands from clap's help — we render
    // them ourselves via `after_help` because clap doesn't support multiple
    // subcommand sections (clap-rs/clap#1553).
    // Each entry is a `let cmd = cmd.subcommand(...)` statement so that
    // #[cfg(...)] can be applied per-subcommand.
    let leaf_subcommands: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let sub = generate_leaf_subcommand(
                m,
                has_defaults,
                has_cli_hidden(m) || has_groups,
            )?;
            let cfg_attrs = &m.cfg_attrs;
            Ok(quote! {
                #(#cfg_attrs)*
                let __cmd = __cmd.subcommand(#sub);
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;

    // Build grouped help text as `after_help` content
    let grouped_after_help = if has_groups {
        #[allow(clippy::type_complexity)]
        let mut sections: Vec<(Option<String>, Vec<(String, String)>)> = Vec::new();

        // Ungrouped leaf methods first
        let mut ungrouped = Vec::new();
        for m in &partitioned.leaf {
            if has_cli_hidden(m) {
                continue;
            }
            if resolve_method_group(m, &group_registry)?.is_none() {
                let name = cli_name(m);
                let (about, _) = split_docs(&m.docs);
                ungrouped.push((name, about));
            }
        }
        // Static mounts — ungrouped ones only
        for m in &partitioned.static_mounts {
            if !has_cli_hidden(m) && resolve_method_group(m, &group_registry)?.is_none() {
                let name = cli_name(m);
                let (about, _) = split_docs(&m.docs);
                ungrouped.push((name, about));
            }
        }
        // Slug mounts — ungrouped ones only
        for m in &partitioned.slug_mounts {
            if !has_cli_hidden(m) && resolve_method_group(m, &group_registry)?.is_none() {
                let name = cli_name(m);
                let (about, _) = split_docs(&m.docs);
                ungrouped.push((name, about));
            }
        }
        if !ungrouped.is_empty() {
            sections.push((None, ungrouped));
        }

        // Grouped methods in registry order (leaf + mounts)
        for group in &group_order {
            let mut entries = Vec::new();
            for m in partitioned
                .leaf
                .iter()
                .chain(partitioned.static_mounts.iter())
                .chain(partitioned.slug_mounts.iter())
            {
                if has_cli_hidden(m) {
                    continue;
                }
                if resolve_method_group(m, &group_registry)?.as_deref() == Some(group.as_str()) {
                    let name = cli_name(m);
                    let (about, _) = split_docs(&m.docs);
                    entries.push((name, about));
                }
            }
            if !entries.is_empty() {
                sections.push((Some(group.clone()), entries));
            }
        }

        // Column width for alignment
        let max_width = sections
            .iter()
            .flat_map(|(_, entries)| entries.iter())
            .map(|(name, _)| name.len())
            .max()
            .unwrap_or(0);

        let mut text = String::new();
        for (heading, entries) in &sections {
            match heading {
                Some(h) => text.push_str(&format!("\x1b[1;4m{h}:\x1b[0m\n")),
                None => text.push_str("\x1b[1;4mCommands:\x1b[0m\n"),
            }
            for (name, about) in entries {
                if about.is_empty() {
                    text.push_str(&format!("  {name}\n"));
                } else {
                    text.push_str(&format!(
                        "  \x1b[1m{name:<width$}\x1b[0m  {about}\n",
                        width = max_width
                    ));
                }
            }
            text.push('\n');
        }

        Some(quote! { .after_help(#text).subcommand_value_name("COMMAND") })
    } else {
        None
    };

    // Generate subcommands for static mounts.
    // When groups are active, mounts are hidden from clap's Commands section but
    // get an explicit bin_name to preserve parent name in usage lines.
    let static_mount_subcommands: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_subcommand(m, has_cli_hidden(m) || has_groups))
        .collect::<syn::Result<Vec<_>>>()?;

    // Generate subcommands for slug mounts
    let slug_mount_subcommands: Vec<_> = partitioned
        .slug_mounts
        .iter()
        .map(|m| generate_slug_mount_subcommand(m, has_cli_hidden(m) || has_groups))
        .collect::<syn::Result<Vec<_>>>()?;

    // Find the default action (if any) — the method marked #[cli(default)].
    // It still appears as a normal subcommand AND runs when no subcommand is given.
    // Emit a compile error if more than one method is marked as default.
    let mut default_methods = partitioned.leaf.iter().filter(|m| has_cli_default(m));
    let default_method = default_methods.next();
    if let Some(second) = default_methods.next() {
        let first_name = default_method
            .map(|m| m.method.sig.ident.to_string())
            .unwrap_or_default();
        return Err(syn::Error::new_spanned(
            &second.method.sig.ident,
            format!(
                "only one method may be marked as default; first default is '{first_name}'"
            ),
        ));
    }

    // Parent-level args for the default action so that flags like
    // `app --flag` are parsed (and shown in `app --help`) when no subcommand is specified.
    let default_parent_args: Vec<TokenStream2> = if let Some(dm) = default_method {
        let (_, regular_params) = partition_context_params(&dm.params)?;
        let mut pos_idx = 0usize;
        regular_params
            .iter()
            .map(|p| {
                let idx = if p.is_positional {
                    pos_idx += 1;
                    Some(pos_idx)
                } else {
                    None
                };
                generate_arg(p, has_defaults, idx)
            })
            .collect()
    } else {
        vec![]
    };

    // None arm: runs the default action when no subcommand is given.
    // `sub_matches = matches` so the same dispatch body works unchanged.
    let default_none_arm: Option<TokenStream2> = if let Some(dm) = default_method {
        Some(generate_leaf_match_arm(
            dm,
            &global_flags,
            &defaults_fn_ident,
            true,
            false,
            meta,
        )?)
    } else {
        None
    };
    let async_default_none_arm: Option<TokenStream2> = if let Some(dm) = default_method {
        Some(generate_leaf_match_arm(
            dm,
            &global_flags,
            &defaults_fn_ident,
            true,
            true,
            meta,
        )?)
    } else {
        None
    };

    // Generate match arms for leaf methods
    let leaf_match_arms: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let arm = generate_leaf_match_arm(m, &global_flags, &defaults_fn_ident, false, false, meta)?;
            let cfg_attrs = &m.cfg_attrs;
            Ok(quote! {
                #(#cfg_attrs)*
                #arm
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;
    let async_leaf_match_arms: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let arm = generate_leaf_match_arm(m, &global_flags, &defaults_fn_ident, false, true, meta)?;
            let cfg_attrs = &m.cfg_attrs;
            Ok(quote! {
                #(#cfg_attrs)*
                #arm
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;

    // Generate match arms for static mounts
    let static_mount_arms: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_arm(m))
        .collect::<syn::Result<Vec<_>>>()?;
    let async_static_mount_arms: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_arm_async(m))
        .collect::<syn::Result<Vec<_>>>()?;

    // Generate match arms for slug mounts
    let slug_mount_arms: Vec<_> = partitioned
        .slug_mounts
        .iter()
        .map(|m| generate_slug_mount_arm(m))
        .collect::<syn::Result<Vec<_>>>()?;
    let async_slug_mount_arms: Vec<_> = partitioned
        .slug_mounts
        .iter()
        .map(|m| generate_slug_mount_arm_async(m))
        .collect::<syn::Result<Vec<_>>>()?;

    // ── Manual (--manual) node builders ───────────────────────────────
    // One per leaf (its own reference entry) + recursion into each mount's
    // subtree. Hidden methods are excluded from the aggregate, matching how
    // they are excluded from help. `#[cfg(...)]` is preserved per-method so
    // conditionally-compiled commands don't appear in the manual when absent.
    let manual_node_builders: Vec<TokenStream2> = {
        let mut builders = Vec::new();
        for m in &partitioned.leaf {
            if has_cli_hidden(m) || has_cli_manual_false(m) {
                continue;
            }
            let node = generate_leaf_manual_node(m)?;
            let cfg_attrs = &m.cfg_attrs;
            builders.push(quote! {
                #(#cfg_attrs)*
                #node
            });
        }
        for m in &partitioned.static_mounts {
            if has_cli_hidden(m) || has_cli_manual_false(m) {
                continue;
            }
            let node = generate_static_mount_manual_node(m)?;
            let cfg_attrs = &m.cfg_attrs;
            builders.push(quote! {
                #(#cfg_attrs)*
                #node
            });
        }
        for m in &partitioned.slug_mounts {
            if has_cli_hidden(m) || has_cli_manual_false(m) {
                continue;
            }
            let node = generate_slug_mount_manual_node(m)?;
            let cfg_attrs = &m.cfg_attrs;
            builders.push(quote! {
                #(#cfg_attrs)*
                #node
            });
        }
        builders
    };

    // Build subcommand documentation
    let subcommand_docs: Vec<String> = partitioned
        .leaf
        .iter()
        .filter(|m| !has_cli_hidden(m))
        .map(|m| {
            let name = cli_name(m);
            match &m.docs {
                Some(doc) => format!("- `{name}` — {doc}"),
                None => format!("- `{name}`"),
            }
        })
        .chain(
            partitioned
                .static_mounts
                .iter()
                .filter(|m| !has_cli_hidden(m))
                .map(|m| {
                    let name = cli_name(m);
                    format!("- `{name}` (subcommand group)")
                }),
        )
        .chain(
            partitioned
                .slug_mounts
                .iter()
                .filter(|m| !has_cli_hidden(m))
                .map(|m| {
                    let name = cli_name(m);
                    format!("- `{name} <arg>` (subcommand group)")
                }),
        )
        .collect();
    let cli_command_doc = if subcommand_docs.is_empty() {
        "Create a clap Command for this CLI.".to_string()
    } else {
        format!(
            "Create a clap Command for this CLI.\n\n# Subcommands\n\n{}",
            subcommand_docs.join("\n")
        )
    };

    // Emit the impl block only if this is the highest-priority protocol macro present.
    // When multiple protocol macros are stacked, exactly one emits the impl block;
    // others skip it to prevent duplicate method definitions.
    // Emit the impl block only if this is the highest-priority protocol macro present.
    // Keep sibling protocol attrs on the re-emitted impl so the pipeline processes them next.
    // Only strip cli-specific method-level attrs; leave #[http], #[mcp], etc. intact.
    let clean_impl_block = if crate::is_protocol_impl_emitter(&impl_block, "cli") {
        let stripped = strip_cli_attrs(&impl_block);
        quote! { #stripped }
    } else {
        quote! {}
    };

    // Generate global flag args on root command
    let global_flag_args: Vec<_> = global_flags_with_help
        .iter()
        .map(|(flag, help)| {
            let kebab = flag.replace('_', "-");
            let help_clause = help
                .as_deref()
                .map(|h| quote! { .help(#h) })
                .unwrap_or_default();
            quote! {
                .arg(
                    ::server_less::clap::Arg::new(#kebab)
                        .long(#kebab)
                        .action(::server_less::clap::ArgAction::SetTrue)
                        .global(true)
                        #help_clause
                )
            }
        })
        .collect();

    // Whole-subtree manual aggregation. `cli_manual_nodes` materializes the
    // reference document for the subtree rooted at this node: each leaf's own
    // entry, plus (via the `CliSubcommand` trait) every mount child's subtree.
    // The aggregation is compile-time codegen composed through the same mount
    // recursion the dispatcher uses — see docs/design/cli-manual-projection.md.
    let manual_nodes_method = quote! {
        fn cli_manual_nodes(&self, __prefix: &str) -> Vec<::server_less::CliManualNode> {
            let mut __nodes: Vec<::server_less::CliManualNode> = Vec::new();
            #(#manual_node_builders)*
            __nodes
        }
    };

    // Top-of-dispatch `--manual` interception: when set and no further subcommand
    // is selected, this node is the invoked root of the subtree → emit it. A
    // selected leaf/mount subcommand falls through: a leaf handles `--manual` in
    // its own arm, a mount recurses into the child's dispatch. This runs *before*
    // any `#[cli(default)]` None arm so `tool --manual` means "manual of the tree",
    // not "run the default action".
    let manual_dispatch_intercept = if meta.manual {
        let emit = manual_emit_tokens(&syn::Ident::new(
            "matches",
            proc_macro2::Span::call_site(),
        ));
        quote! {
            if matches.get_flag("manual") && matches.subcommand().is_none() {
                let __nodes = <Self as ::server_less::CliSubcommand>::cli_manual_nodes(self, "");
                #emit
                return Ok(());
            }
        }
    } else {
        quote! {}
    };

    // Built-in output formatting flags. `--json`/`--jsonl`/`--jq`/`--params-json`
    // are always present; the meta-surface flags are gated by their toggle so a
    // disabled surface neither appears in `--help` nor is queried at dispatch.
    let input_schema_flag = meta.input_schema.then(|| quote! {
        .arg(
            ::server_less::clap::Arg::new("input-schema")
                .long("input-schema")
                .action(::server_less::clap::ArgAction::SetTrue)
                .global(true)
                .help("Print JSON Schema of the subcommand's input parameters and exit")
        )
    });
    let output_schema_flag = meta.output_schema.then(|| quote! {
        .arg(
            ::server_less::clap::Arg::new("output-schema")
                .long("output-schema")
                .action(::server_less::clap::ArgAction::SetTrue)
                .global(true)
                .help("Print JSON Schema of the subcommand's return type and exit")
        )
    });
    let manual_flag = meta.manual.then(|| quote! {
        .arg(
            ::server_less::clap::Arg::new("manual")
                .long("manual")
                .action(::server_less::clap::ArgAction::SetTrue)
                .global(true)
                .help("Emit the reference manual for the command subtree rooted here and exit")
        )
    });
    let format_flags = quote! {
        .arg(
            ::server_less::clap::Arg::new("jsonl")
                .long("jsonl")
                .action(::server_less::clap::ArgAction::SetTrue)
                .global(true)
                .help("Output one JSON object per line (for arrays)")
        )
        .arg(
            ::server_less::clap::Arg::new("json")
                .long("json")
                .action(::server_less::clap::ArgAction::SetTrue)
                .global(true)
                .help("Output machine-readable JSON")
        )
        .arg(
            ::server_less::clap::Arg::new("jq")
                .long("jq")
                .global(true)
                .help("Filter output through jq expression")
        )
        #input_schema_flag
        #output_schema_flag
        #manual_flag
        .arg(
            ::server_less::clap::Arg::new("params-json")
                .long("params-json")
                .global(true)
                .help("Provide all parameters as a JSON object instead of individual flags")
        )
    };

    // Shell completions + man page (clap_complete / clap_mangen). Gated behind the
    // `completions` feature so the clap_complete/clap_mangen deps stay opt-in.
    #[cfg(feature = "completions")]
    let completions_methods = quote! {
        /// Write a shell completion script for `shell` to `out`.
        ///
        /// ```ignore
        /// MyApp::cli_completions(::server_less::clap_complete::Shell::Bash, &mut ::std::io::stdout());
        /// ```
        pub fn cli_completions<__W: ::std::io::Write>(
            shell: ::server_less::clap_complete::Shell,
            out: &mut __W,
        ) {
            let mut __cmd = <Self as ::server_less::CliSubcommand>::cli_command();
            let __bin = __cmd.get_name().to_string();
            ::server_less::clap_complete::generate(shell, &mut __cmd, __bin, out);
        }

        /// Render a roff man page for this CLI to `out`.
        pub fn cli_manpage<__W: ::std::io::Write>(out: &mut __W) -> ::std::io::Result<()> {
            let __cmd = <Self as ::server_less::CliSubcommand>::cli_command();
            ::server_less::clap_mangen::Man::new(__cmd).render(out)
        }
    };
    #[cfg(not(feature = "completions"))]
    let completions_methods = quote! {};

    let sync_entrypoints = if !no_sync {
        quote! {
            /// Run the CLI application.
            ///
            /// Parses process arguments and dispatches to the matching method.
            /// Async methods are driven by an internally-created Tokio runtime —
            /// add `tokio` to your dependencies if any methods are `async`.
            ///
            /// If you already have an async runtime or prefer a different one
            /// (async-std, smol, etc.), use [`cli_run_async`] instead and drive
            /// it with your own `#[runtime::main]`.
            pub fn cli_run(&self) -> ::std::result::Result<(), Box<dyn ::std::error::Error>> {
                if ::server_less::tokio::runtime::Handle::try_current().is_ok() {
                    return Err(
                        "cli_run() cannot be called from within an async context (e.g. #[tokio::test] or #[tokio::main]). \\
                         Use cli_run_async() instead.".into()
                    );
                }
                let matches = Self::cli_command().get_matches();
                <Self as ::server_less::CliSubcommand>::cli_dispatch(self, &matches)
            }

            /// Run the CLI with custom arguments.
            ///
            /// Like [`cli_run`] but accepts an iterator of arguments instead of process args.
            /// Useful for testing.
            pub fn cli_run_with<__CliI, __CliArg>(&self, args: __CliI) -> ::std::result::Result<(), Box<dyn ::std::error::Error>>
            where
                __CliI: IntoIterator<Item = __CliArg>,
                __CliArg: Into<::std::ffi::OsString> + Clone,
            {
                if ::server_less::tokio::runtime::Handle::try_current().is_ok() {
                    return Err(
                        "cli_run_with() cannot be called from within an async context (e.g. #[tokio::test] or #[tokio::main]). \\
                         Use cli_run_with_async() instead.".into()
                    );
                }
                let matches = Self::cli_command().get_matches_from(args);
                <Self as ::server_less::CliSubcommand>::cli_dispatch(self, &matches)
            }
        }
    } else {
        quote! {}
    };

    let async_entrypoint = if !no_async {
        quote! {
            /// Run the CLI application asynchronously.
            ///
            /// Parses process arguments and awaits the dispatched method directly,
            /// without creating an internal runtime. Use this when you already have
            /// an async runtime (e.g. `#[tokio::main]` or `async_std::main`).
            pub async fn cli_run_async(&self) -> ::std::result::Result<(), Box<dyn ::std::error::Error>> {
                let matches = Self::cli_command().get_matches();
                <Self as ::server_less::CliSubcommand>::cli_dispatch_async(self, &matches).await
            }

            /// Run the CLI asynchronously with custom arguments.
            ///
            /// Like [`cli_run_async`] but accepts an iterator of arguments instead of process args.
            /// Useful for testing async CLI dispatch.
            pub async fn cli_run_with_async<__CliI, __CliArg>(&self, args: __CliI) -> ::std::result::Result<(), Box<dyn ::std::error::Error>>
            where
                __CliI: IntoIterator<Item = __CliArg>,
                __CliArg: Into<::std::ffi::OsString> + Clone,
            {
                let matches = Self::cli_command().get_matches_from(args);
                <Self as ::server_less::CliSubcommand>::cli_dispatch_async(self, &matches).await
            }
        }
    } else {
        quote! {}
    };

    // Config subcommand — wired in when `config_ty` is provided (via #[program(config = ...)])
    #[cfg(feature = "config")]
    let (config_methods, config_subcommand_addition, config_dispatch_arm) =
        if let Some(ref config_ty) = args.config_ty {
            let cmd_name = args.config_cmd_name.as_deref().unwrap_or("config");
            crate::config_cmd::generate_all(self_ty, config_ty, cmd_name, &app_name)
        } else {
            (quote! {}, quote! {}, quote! {})
        };
    #[cfg(not(feature = "config"))]
    let (config_methods, config_subcommand_addition, config_dispatch_arm) =
        (quote! {}, quote! {}, quote! {});

    Ok(quote! {
        #clean_impl_block

        impl #impl_generics ::server_less::CliSubcommand for #self_ty #where_clause {
            fn cli_command() -> ::server_less::clap::Command {
                let mut __cmd = ::server_less::clap::Command::new(#app_name)
                    .version(#version_tokens)
                    .about(#about)
                    #(#global_flag_args)*
                    #format_flags
                    #grouped_after_help
                    #(.arg(#default_parent_args))*
                    #(.subcommand(#static_mount_subcommands))*
                    #(.subcommand(#slug_mount_subcommands))*
                    #config_subcommand_addition;
                #(#leaf_subcommands)*
                __cmd
            }

            #manual_nodes_method

            fn cli_dispatch(&self, matches: &::server_less::clap::ArgMatches) -> ::std::result::Result<(), Box<dyn ::std::error::Error>> {
                #globals_bound_assert
                #manual_dispatch_intercept
                match matches.subcommand() {
                    #(#leaf_match_arms)*
                    #(#static_mount_arms)*
                    #(#slug_mount_arms)*
                    #config_dispatch_arm
                    #default_none_arm
                    _ => {
                        Self::cli_command().print_help()?;
                        Ok(())
                    }
                }
            }

            fn cli_dispatch_async<'__a>(
                &'__a self,
                matches: &'__a ::server_less::clap::ArgMatches,
            ) -> impl ::std::future::Future<Output = ::std::result::Result<(), Box<dyn ::std::error::Error>>> + '__a {
                async move {
                    #globals_bound_assert
                    #manual_dispatch_intercept
                    match matches.subcommand() {
                        #(#async_leaf_match_arms)*
                        #(#async_static_mount_arms)*
                        #(#async_slug_mount_arms)*
                        #config_dispatch_arm
                        #async_default_none_arm
                        _ => {
                            Self::cli_command().print_help()?;
                            Ok(())
                        }
                    }
                }
            }
        }

        impl #impl_generics #self_ty #where_clause {
            #[doc = #cli_command_doc]
            pub fn cli_command() -> ::server_less::clap::Command {
                <Self as ::server_less::CliSubcommand>::cli_command()
            }

            #sync_entrypoints
            #async_entrypoint
            #completions_methods
        }

        #config_methods
    })
}

/// Split a doc string at the first blank line into (about, after_help).
///
/// If there's no blank line, returns the full string as about and None for after_help.
fn split_docs(docs: &Option<String>) -> (String, Option<String>) {
    let full = match docs {
        Some(s) => s.clone(),
        None => return (String::new(), None),
    };
    // Look for a blank line (empty line between paragraphs)
    if let Some(pos) = full.find("\n\n") {
        let about = full[..pos].to_string();
        let after = full[pos + 2..].to_string();
        if after.is_empty() {
            (about, None)
        } else {
            (about, Some(after))
        }
    } else {
        (full, None)
    }
}

fn generate_leaf_subcommand(
    method: &MethodInfo,
    has_defaults: bool,
    hidden: bool,
) -> syn::Result<TokenStream2> {
    let name = cli_name(method);
    let (about, after_help) = split_docs(&method.docs);
    let after_help_token = after_help.map(|h| quote! { .after_help(#h) });
    let hide = hidden.then(|| quote! { .hide(true) });

    // Filter out Context parameters - they're injected, not CLI args
    let (_, regular_params) = partition_context_params(&method.params)?;

    // Every regular param becomes a clap arg. Params can never name a declared global
    // flag (that is a compile error in `check_reserved_flag_collisions`), so there is
    // nothing to filter — globals live solely on the root and reach the body via the
    // `CliGlobals` sink, not method params.
    let mut pos_idx = 0usize;
    let args: Vec<_> = regular_params
        .iter()
        .map(|p| {
            let idx = if p.is_positional {
                pos_idx += 1;
                Some(pos_idx)
            } else {
                None
            };
            generate_arg(p, has_defaults, idx)
        })
        .collect();

    Ok(quote! {
        ::server_less::clap::Command::new(#name)
            .about(#about)
            #after_help_token
            #hide
            #(.arg(#args))*
    })
}

fn generate_static_mount_subcommand(
    method: &MethodInfo,
    hidden: bool,
) -> syn::Result<TokenStream2> {
    let name = cli_name(method);
    let (about, after_help) = split_docs(&method.docs);
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;
    let hide = hidden.then(|| quote! { __cmd = __cmd.hide(true); });
    let after_help_set = after_help.map(|h| quote! { __cmd = __cmd.after_help(#h); });

    Ok(quote! {
        {
            let mut __cmd = <#inner_ty as ::server_less::CliSubcommand>::cli_command()
                .name(#name);
            if !#about.is_empty() {
                __cmd = __cmd.about(#about);
            }
            #after_help_set
            #hide
            __cmd
        }
    })
}

fn generate_slug_mount_subcommand(
    method: &MethodInfo,
    hidden: bool,
) -> syn::Result<TokenStream2> {
    let name = cli_name(method);
    let (about, after_help) = split_docs(&method.docs);
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;
    let hide = hidden.then(|| quote! { __cmd = __cmd.hide(true); });
    let after_help_set = after_help.map(|h| quote! { __cmd = __cmd.after_help(#h); });

    let (_, regular_params) = partition_context_params(&method.params)?;

    // Generate positional args for slug params (before subcommands)
    let slug_args: Vec<_> = regular_params
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let param_name = cli_param_name(p);
            let idx = i + 1; // clap indices are 1-based
            quote! {
                ::server_less::clap::Arg::new(#param_name)
                    .required(true)
                    .index(#idx)
                    .help(concat!("The ", #param_name))
            }
        })
        .collect();

    Ok(quote! {
        {
            let mut __cmd = <#inner_ty as ::server_less::CliSubcommand>::cli_command()
                .name(#name);
            if !#about.is_empty() {
                __cmd = __cmd.about(#about);
            }
            #after_help_set
            #hide
            #(__cmd = __cmd.arg(#slug_args);)*
            __cmd
        }
    })
}

/// Map a syn::Type to a JSON Schema `serde_json::json!(...)` token expression.
///
/// Uses AST inspection instead of string matching so that `Vec<String>` → array
/// and `Option<String>` → string (not "null|object").
fn type_to_json_schema(ty: &Option<syn::Type>) -> TokenStream2 {
    let Some(ty) = ty else {
        return quote! { ::server_less::serde_json::json!({"type": "null"}) };
    };
    type_to_json_schema_ty(ty)
}

fn type_to_json_schema_ty(ty: &syn::Type) -> TokenStream2 {
    use syn::{GenericArgument, PathArguments, Type};
    match ty {
        Type::Path(type_path) => {
            let Some(segment) = type_path.path.segments.last() else {
                return quote! { ::server_less::serde_json::json!({"type": "object"}) };
            };
            match segment.ident.to_string().as_str() {
                "String" => quote! { ::server_less::serde_json::json!({"type": "string"}) },
                "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "isize"
                | "usize" => quote! { ::server_less::serde_json::json!({"type": "integer"}) },
                "f32" | "f64" => quote! { ::server_less::serde_json::json!({"type": "number"}) },
                "bool" => quote! { ::server_less::serde_json::json!({"type": "boolean"}) },
                "Vec" => {
                    // Recurse into Vec<T> — items schema mirrors the inner type
                    if let PathArguments::AngleBracketed(args) = &segment.arguments
                        && let Some(GenericArgument::Type(inner)) = args.args.first()
                    {
                        let items_schema = type_to_json_schema_ty(inner);
                        return quote! {
                            {
                                let __items = #items_schema;
                                ::server_less::serde_json::json!({"type": "array", "items": __items})
                            }
                        };
                    }
                    quote! { ::server_less::serde_json::json!({"type": "array", "items": {}}) }
                }
                "HashMap" | "BTreeMap" | "IndexMap" => {
                    quote! { ::server_less::serde_json::json!({"type": "object", "additionalProperties": true}) }
                }
                "Option" => {
                    // Recurse into Option<T> — schema mirrors the inner type
                    if let PathArguments::AngleBracketed(args) = &segment.arguments
                        && let Some(GenericArgument::Type(inner)) = args.args.first()
                    {
                        return type_to_json_schema_ty(inner);
                    }
                    quote! { ::server_less::serde_json::json!({"type": "object"}) }
                }
                _ => quote! { ::server_less::serde_json::json!({"type": "object"}) },
            }
        }
        Type::Reference(r) => {
            if let Type::Path(tp) = r.elem.as_ref()
                && tp.path.is_ident("str")
            {
                quote! { ::server_less::serde_json::json!({"type": "string"}) }
            } else {
                type_to_json_schema_ty(&r.elem)
            }
        }
        Type::Slice(_) => {
            quote! { ::server_less::serde_json::json!({"type": "array", "items": {}}) }
        }
        _ => quote! { ::server_less::serde_json::json!({"type": "object"}) },
    }
}

fn generate_arg(
    param: &ParamInfo,
    _has_defaults: bool,
    positional_index: Option<usize>,
) -> TokenStream2 {
    let name = cli_param_name(param);

    let short = param.short_flag.map(|c| quote! { .short(#c) });

    // Honor `#[param(default = ...)]` for value-bearing args. Bool flags are SetTrue
    // (their default is implicitly absent=false) and vecs accumulate, so a scalar
    // default applies only to positional / optional / required value args.
    let default_clause = match &param.default_value {
        Some(raw) if !param.is_bool && !param.is_vec => {
            let dv = clap_default_value(raw);
            quote! { .default_value(#dv) }
        }
        _ => quote! {},
    };

    // Compute the leaf type for the value parser (strip Vec<> / Option<> wrappers).
    // SchemaValueParser<T> requires T: JsonSchema + FromStr; for non-enum types it
    // is a transparent pass-through, so emitting it unconditionally is harmless.
    #[cfg(feature = "jsonschema")]
    let value_parser = if param.is_bool {
        quote! {}
    } else {
        let inner: syn::Type = if param.is_vec {
            param.vec_inner.clone().unwrap_or_else(|| param.ty.clone())
        } else if param.is_optional {
            extract_option_type(&param.ty).unwrap_or_else(|| param.ty.clone())
        } else {
            param.ty.clone()
        };
        quote! { .value_parser(::server_less::SchemaValueParser::<#inner>::new()) }
    };
    #[cfg(not(feature = "jsonschema"))]
    let value_parser = quote! {};

    if param.is_bool {
        let help = match &param.help_text {
            Some(text) => quote! { .help(#text) },
            None => quote! { .help(concat!("Enable ", #name)) },
        };
        quote! {
            ::server_less::clap::Arg::new(#name)
                .long(#name)
                #short
                .action(::server_less::clap::ArgAction::SetTrue)
                #help
        }
    } else if param.is_vec {
        let help = match &param.help_text {
            Some(text) => quote! { .help(#text) },
            None => quote! { .help(concat!("Repeatable: ", #name)) },
        };
        quote! {
            ::server_less::clap::Arg::new(#name)
                .long(#name)
                #short
                .action(::server_less::clap::ArgAction::Append)
                .value_delimiter(',')
                .required(false)
                #value_parser
                #help
        }
    } else if param.is_positional {
        let idx = positional_index.unwrap_or(1);
        let help = match &param.help_text {
            Some(text) => quote! { .help(#text) },
            None => quote! { .help(concat!("The ", #name)) },
        };
        quote! {
            ::server_less::clap::Arg::new(#name)
                .required(false)
                .index(#idx)
                #value_parser
                #default_clause
                #help
        }
    } else if param.is_optional {
        let help = match &param.help_text {
            Some(text) => quote! { .help(#text) },
            None => quote! { .help(concat!("Optional: ", #name)) },
        };
        quote! {
            ::server_less::clap::Arg::new(#name)
                .long(#name)
                #short
                .required(false)
                #value_parser
                #default_clause
                #help
        }
    } else {
        let help = match &param.help_text {
            Some(text) => quote! { .help(#text) },
            None => quote! { .help(concat!("Required: ", #name)) },
        };
        quote! {
            ::server_less::clap::Arg::new(#name)
                .long(#name)
                #short
                .required(false)
                #value_parser
                #default_clause
                #help
        }
    }
}

fn generate_leaf_match_arm(
    method: &MethodInfo,
    global_flags: &[String],
    defaults_fn_ident: &Option<syn::Ident>,
    // When true: generates `None =>` arm (default action, no subcommand given)
    // with `let sub_matches = matches;` so the body is identical.
    // When false: generates the normal `Some(("name", sub_matches)) =>` arm.
    none_arm: bool,
    // When true: generates async dispatch (`.await` instead of `block_on`).
    for_async: bool,
    // Which injected meta-surface flags are enabled — gates the schema/manual arms
    // so `get_flag` is never called on an unregistered id.
    meta: MetaFlags,
) -> syn::Result<TokenStream2> {
    let subcommand_name = cli_name(method);
    let method_name = &method.name;

    // Partition Context vs regular parameters
    let (context_param, regular_params) = partition_context_params(&method.params)?;

    // ── Input schema (compile-time JSON) ──────────────────────────────
    let input_schema = {
        let mut props = Vec::new();
        let mut required = Vec::new();
        for p in &regular_params {
            let name_str = p.name_str();
            let schema = type_to_json_schema(&Some(p.ty.clone()));
            props.push(quote! {
                __props.insert(#name_str.to_string(), #schema);
            });
            if !p.is_optional && !p.is_bool {
                required.push(quote! { #name_str });
            }
        }
        quote! {
            let mut __props = ::server_less::serde_json::Map::new();
            #(#props)*
            let __schema = ::server_less::serde_json::json!({
                "type": "object",
                "properties": ::server_less::serde_json::Value::Object(__props),
                "required": [#(#required),*],
            });
            println!("{}", ::server_less::serde_json::to_string_pretty(&__schema)?);
            return Ok(());
        }
    };

    // ── Output schema ──────────────────────────────────────────────────
    let output_ty = if method.return_info.is_result {
        &method.return_info.ok_type
    } else if method.return_info.is_option {
        &method.return_info.some_type
    } else if method.return_info.is_unit {
        &None
    } else {
        &method.return_info.ty
    };
    // When the `jsonschema` feature is enabled, emit a runtime schemars call so
    // user-defined structs produce full field-level schemas. When disabled, fall
    // back to the compile-time type-string heuristic (primitives only).
    #[cfg(feature = "jsonschema")]
    let output_schema = if let Some(ty) = output_ty {
        quote! {
            let __schema = ::server_less::cli_schema_for::<#ty>();
            println!("{}", ::server_less::serde_json::to_string_pretty(&__schema)?);
            return Ok(());
        }
    } else {
        quote! {
            println!("{{\"type\": \"null\"}}");
            return Ok(());
        }
    };
    #[cfg(not(feature = "jsonschema"))]
    let output_schema = {
        let output_schema_expr = type_to_json_schema(output_ty);
        quote! {
            let __schema = #output_schema_expr;
            println!("{}", ::server_less::serde_json::to_string_pretty(&__schema)?);
            return Ok(());
        }
    };

    // ── Param extraction: normal CLI args ─────────────────────────────
    let mut arg_extractions = Vec::new();
    let mut arg_names = Vec::new();

    // Generate Context extraction if needed
    if context_param.is_some() {
        let (_extraction, call) = generate_cli_context_extraction();
        arg_extractions.push(quote! {
            let __ctx = #call;
        });
        arg_names.push(quote! { __ctx });
    }

    // Generate regular parameter extractions
    for p in &regular_params {
        let name = &p.name;
        let name_str = cli_param_name(p);

        if p.is_bool {
            arg_extractions.push(quote! {
                let #name: bool = sub_matches.get_flag(#name_str);
            });
        } else if p.is_vec {
            // When jsonschema is active, the value_parser stores inner type T directly.
            // Otherwise, values are stored as String and parsed here.
            #[cfg(feature = "jsonschema")]
            {
                let inner = p.vec_inner.as_ref().unwrap_or(&p.ty);
                arg_extractions.push(quote! {
                    let #name = sub_matches
                        .get_many::<#inner>(#name_str)
                        .map(|vs| vs.cloned().collect())
                        .unwrap_or_default();
                });
            }
            #[cfg(not(feature = "jsonschema"))]
            arg_extractions.push(quote! {
                let #name: Vec<String> = sub_matches
                    .get_many::<String>(#name_str)
                    .map(|vs| vs.cloned().collect())
                    .unwrap_or_default();
            });
        } else if p.is_optional {
            let ty = &p.ty;
            // When jsonschema is active, value is stored as inner T; wrap in Option.
            #[cfg(feature = "jsonschema")]
            {
                let inner = extract_option_type(&p.ty).unwrap_or_else(|| p.ty.clone());
                arg_extractions.push(quote! {
                    let #name: #ty = sub_matches
                        .get_one::<#inner>(#name_str)
                        .cloned();
                });
            }
            #[cfg(not(feature = "jsonschema"))]
            arg_extractions.push(quote! {
                let #name: #ty = sub_matches
                    .get_one::<String>(#name_str)
                    .and_then(|s| s.parse().ok());
            });
        } else if let Some(defaults_fn) = defaults_fn_ident {
            let ty = &p.ty;
            // When jsonschema is active, successfully parsed values are stored as T.
            // The defaults path still parses from a string.
            #[cfg(feature = "jsonschema")]
            arg_extractions.push(quote! {
                let #name: #ty = if let Some(__val) = sub_matches.get_one::<#ty>(#name_str) {
                    __val.clone()
                } else if let Some(__default) = self.#defaults_fn(#name_str) {
                    __default.parse()?
                } else {
                    return Err(format!("Missing required argument: {}", #name_str).into());
                };
            });
            #[cfg(not(feature = "jsonschema"))]
            arg_extractions.push(quote! {
                let #name: #ty = if let Some(__val) = sub_matches.get_one::<String>(#name_str) {
                    __val.parse()?
                } else if let Some(__default) = self.#defaults_fn(#name_str) {
                    __default.parse()?
                } else {
                    return Err(format!("Missing required argument: {}", #name_str).into());
                };
            });
        } else {
            let ty = &p.ty;
            // When jsonschema is active, value is stored as T by the value_parser.
            #[cfg(feature = "jsonschema")]
            arg_extractions.push(quote! {
                let #name: #ty = sub_matches
                    .get_one::<#ty>(#name_str)
                    .cloned()
                    .ok_or_else(|| format!("Missing required argument: {}", #name_str))?;
            });
            #[cfg(not(feature = "jsonschema"))]
            arg_extractions.push(quote! {
                let #name: #ty = sub_matches
                    .get_one::<String>(#name_str)
                    .map(|s| s.parse())
                    .transpose()?
                    .ok_or_else(|| format!("Missing required argument: {}", #name_str))?;
            });
        }
        arg_names.push(quote! { #name });
    }

    // ── Param extraction: --params-json ───────────────────────────────
    let mut json_extractions = Vec::new();
    let mut json_arg_names = Vec::new();

    if context_param.is_some() {
        let (_extraction, call) = generate_cli_context_extraction();
        json_extractions.push(quote! {
            let __ctx = #call;
        });
        json_arg_names.push(quote! { __ctx });
    }

    for p in &regular_params {
        let name = &p.name;
        let name_str = p.name_str();
        let ty = &p.ty;

        if p.is_bool {
            json_extractions.push(quote! {
                let #name: bool = __json_obj.get(#name_str)
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false);
            });
        } else if p.is_optional {
            json_extractions.push(quote! {
                let #name: #ty = __json_obj.get(#name_str)
                    .and_then(|v| ::server_less::serde_json::from_value(v.clone()).ok());
            });
        } else if p.is_vec {
            let elem_ty = p.vec_inner.as_ref().unwrap_or(ty);
            json_extractions.push(quote! {
                let #name: Vec<#elem_ty> = __json_obj.get(#name_str)
                    .map(|v| ::server_less::serde_json::from_value(v.clone()))
                    .transpose()
                    .map_err(|e| format!("Invalid value for '{}': {}", #name_str, e))?
                    .unwrap_or_default();
            });
        } else {
            json_extractions.push(quote! {
                let #name: #ty = __json_obj.get(#name_str)
                    .ok_or_else(|| format!("Missing required field '{}' in --params-json", #name_str))
                    .and_then(|v| ::server_less::serde_json::from_value(v.clone())
                        .map_err(|e| format!("Invalid value for '{}': {}", #name_str, e)))?;
            });
        }
        json_arg_names.push(quote! { #name });
    }

    // ── Method call ───────────────────────────────────────────────────
    let gen_call = |names: &[TokenStream2]| -> TokenStream2 {
        if method.return_info.is_unit {
            if method.is_async {
                if for_async {
                    quote! { self.#method_name(#(#names),*).await; }
                } else {
                    quote! {
                        ::server_less::tokio::runtime::Runtime::new()?
                            .block_on(self.#method_name(#(#names),*));
                    }
                }
            } else {
                quote! {
                    self.#method_name(#(#names),*);
                }
            }
        } else if method.is_async {
            if for_async {
                quote! { let result = self.#method_name(#(#names),*).await; }
            } else {
                quote! {
                    let result = ::server_less::tokio::runtime::Runtime::new()?
                        .block_on(self.#method_name(#(#names),*));
                }
            }
        } else {
            quote! {
                let result = self.#method_name(#(#names),*);
            }
        }
    };

    let call = gen_call(&arg_names);
    let json_call = gen_call(&json_arg_names);

    // Extract output format flags
    let format_extraction = quote! {
        let __jsonl = sub_matches.get_flag("jsonl");
        let __json = sub_matches.get_flag("json");
        let __jq: Option<&String> = sub_matches.get_one::<String>("jq");
    };

    let display_with = get_display_with(method);

    // Determine the effective inner type for default Display detection
    let inner_ty = if method.return_info.is_result {
        method.return_info.ok_type.as_ref()
    } else if method.return_info.is_option {
        method.return_info.some_type.as_ref()
    } else {
        method.return_info.ty.as_ref()
    };

    // Generate the display logic for a value binding
    let gen_value_display = |value_ident: &syn::Ident| -> TokenStream2 {
        // JSON flags always win; display_with only governs text output
        let text_display = if let Some(ref display_fn) = display_with {
            quote! {
                let __display = self.#display_fn(&#value_ident);
                println!("{}", __display);
            }
        } else if let Some(ty) = inner_ty {
            if is_unit_type(ty) {
                quote! { println!("Done"); }
            } else if extract_vec_type(ty).is_some() {
                quote! {
                    for __item in &#value_ident {
                        println!("{}", __item);
                    }
                }
            } else if extract_map_type(ty).is_some() {
                quote! {
                    for (__k, __v) in &#value_ident {
                        println!("{}: {}", __k, __v);
                    }
                }
            } else {
                quote! { println!("{}", #value_ident); }
            }
        } else {
            quote! { println!("{}", #value_ident); }
        };

        quote! {
            if __json || __jsonl || __jq.is_some() {
                let __formatted = ::server_less::cli_format_output(
                    ::server_less::serde_json::to_value(&#value_ident)?,
                    __jsonl, __json, __jq.map(|s| s.as_str()),
                )?;
                println!("{}", __formatted);
            } else {
                #text_display
            }
        }
    };

    let value_ident = syn::Ident::new("value", proc_macro2::Span::call_site());

    let output = if method.return_info.is_unit {
        quote! { println!("Done"); }
    } else if method.return_info.is_result {
        let display_code = gen_value_display(&value_ident);
        quote! {
            match result {
                Ok(value) => {
                    #display_code
                }
                Err(err) => {
                    // Structured errors for programmatic consumers: under
                    // `--json`/`--jsonl`/`--jq`, emit `{"error": "<msg>"}` on
                    // stdout so callers get a parseable object instead of plain
                    // text on stderr. Exit non-zero in every format.
                    let __err_msg = ::std::format!("{}", err);
                    if __json || __jsonl || __jq.is_some() {
                        let __err_val = ::server_less::serde_json::json!({ "error": __err_msg });
                        match ::server_less::cli_format_output(
                            __err_val, __jsonl, __json, __jq.map(|s| s.as_str()),
                        ) {
                            Ok(__formatted) => println!("{}", __formatted),
                            Err(_) => eprintln!("{}", __err_msg),
                        }
                    } else {
                        eprintln!("{}", __err_msg);
                    }
                    ::std::process::exit(1);
                }
            }
        }
    } else if method.return_info.is_option {
        let display_code = gen_value_display(&value_ident);
        quote! {
            match result {
                Some(value) => {
                    #display_code
                }
                None => {
                    if __json || __jsonl || __jq.is_some() {
                        let __formatted = ::server_less::cli_format_output(
                            ::server_less::serde_json::Value::Null,
                            __jsonl, __json, __jq.map(|s| s.as_str()),
                        )?;
                        println!("{}", __formatted);
                    } else {
                        eprintln!("Not found");
                        ::std::process::exit(1);
                    }
                }
            }
        }
    } else if method.return_info.is_iterator {
        // Streaming path: avoid collecting the whole iterator into memory.
        // --json and --jq collect first (documented as unsafe for infinite iterators).
        // Default and --jsonl stream one JSON line per item.
        quote! {
            if __json || __jq.is_some() {
                let __collected: Vec<_> = result.collect();
                let __formatted = ::server_less::cli_format_output(
                    ::server_less::serde_json::to_value(&__collected)?,
                    false, __json, __jq.map(|s| s.as_str()),
                )?;
                println!("{}", __formatted);
            } else {
                for __item in result {
                    println!("{}", ::server_less::serde_json::to_string(&__item)?);
                }
            }
        }
    } else {
        let result_ident = syn::Ident::new("result", proc_macro2::Span::call_site());
        let display_code = gen_value_display(&result_ident);
        quote! {
            #display_code
        }
    };

    // --manual on a leaf: emit just this command's reference entry (a one-node
    // manual). The aggregate at a container is handled in `cli_dispatch`; here we
    // are at the leaf the user navigated to, so its subtree is itself.
    let leaf_manual_node = generate_leaf_manual_node(method)?;
    let manual_emit = manual_emit_tokens(&syn::Ident::new(
        "sub_matches",
        proc_macro2::Span::call_site(),
    ));
    // Each meta-surface arm is gated on its toggle: a disabled flag is never
    // registered, and `get_flag` on an unregistered id panics at runtime.
    let manual_arm = meta.manual.then(|| quote! {
        // --manual: emit this command's reference entry and exit (before running).
        if sub_matches.get_flag("manual") {
            let mut __nodes: Vec<::server_less::CliManualNode> = Vec::new();
            let __prefix: &str = "";
            #leaf_manual_node
            #manual_emit
            return Ok(());
        }
    });
    let input_schema_arm = meta.input_schema.then(|| quote! {
        if sub_matches.get_flag("input-schema") {
            #input_schema
        }
    });
    let output_schema_arm = meta.output_schema.then(|| quote! {
        if sub_matches.get_flag("output-schema") {
            #output_schema
        }
    });

    // ── Global flag delivery (the capability-wiring invariant) ─────────
    // Every declared `global = [...]` flag is delivered to the `CliGlobals` sink
    // before the method runs. The call names the sink by trait, so omitting the
    // `impl CliGlobals` is a compile error — a declared global can never be
    // advertised-but-inert. Globals are `.global(true)`, so `sub_matches` (the
    // leaf's matches, or the root for the default `None` arm) sees their values.
    // Delivery happens after the schema/manual short-circuits (which exit without
    // running the method) and before either extraction path, so both the normal
    // and `--params-json` invocations receive the globals.
    let global_delivery: Vec<TokenStream2> = global_flags
        .iter()
        .map(|flag| {
            let kebab = flag.replace('_', "-");
            quote! {
                <Self as ::server_less::CliGlobals>::set_global_flag(
                    self, #kebab, sub_matches.get_flag(#kebab),
                );
            }
        })
        .collect();

    let arm_body = quote! {
        #manual_arm
        // Schema flags: print and exit without running the method
        #input_schema_arm
        #output_schema_arm

        #(#global_delivery)*

        // --params-json: extract all params from JSON blob
        if let Some(__params_json_str) = sub_matches.get_one::<String>("params-json") {
            let __json_obj: ::server_less::serde_json::Value = ::server_less::serde_json::from_str(__params_json_str)
                .map_err(|e| format!("Invalid JSON in --params-json: {}", e))?;
            let __json_obj = __json_obj.as_object()
                .ok_or_else(|| "Expected a JSON object for --params-json".to_string())?;
            #(#json_extractions)*
            #json_call
            #format_extraction
            #output
        } else {
            // Normal CLI arg extraction
            #(#arg_extractions)*
            #call
            #format_extraction
            #output
        }
        Ok(())
    };

    Ok(if none_arm {
        // Default action: no subcommand given — bind `sub_matches` to the
        // parent's ArgMatches (which holds the hidden default-action args).
        quote! {
            None => {
                let sub_matches = matches;
                #arm_body
            }
        }
    } else {
        quote! {
            Some((#subcommand_name, sub_matches)) => {
                #arm_body
            }
        }
    })
}

/// Tokens that format a `__nodes: Vec<CliManualNode>` binding according to the
/// active format flags (`--json` / `--jsonl` / `--jq`), falling back to
/// human-readable text when no format flag is set. `matches_ident` is the
/// `ArgMatches` to read the format flags from (the global flags propagate to
/// every level, so either the leaf's `sub_matches` or the dispatch `matches`
/// works).
fn manual_emit_tokens(matches_ident: &syn::Ident) -> TokenStream2 {
    quote! {
        let __json = #matches_ident.get_flag("json");
        let __jsonl = #matches_ident.get_flag("jsonl");
        let __jq: Option<&String> = #matches_ident.get_one::<String>("jq");
        if __json || __jsonl || __jq.is_some() {
            let __doc = ::server_less::cli_manual_to_json(&__nodes);
            let __formatted = ::server_less::cli_format_output(
                __doc, __jsonl, __json, __jq.map(|s| s.as_str()),
            )?;
            println!("{}", __formatted);
        } else {
            print!("{}", ::server_less::cli_manual_to_text(&__nodes));
        }
    }
}

/// Expression that evaluates to the input-parameters JSON Schema (`serde_json::Value`)
/// for a leaf method. Mirrors the `input-schema` flag's compile-time JSON, but yields
/// a value instead of printing — used by the `--manual` aggregate.
fn leaf_input_schema_expr(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let (_, regular_params) = partition_context_params(&method.params)?;
    let mut props = Vec::new();
    let mut required = Vec::new();
    for p in &regular_params {
        let name_str = p.name_str();
        let schema = type_to_json_schema(&Some(p.ty.clone()));
        props.push(quote! {
            __props.insert(#name_str.to_string(), #schema);
        });
        if !p.is_optional && !p.is_bool {
            required.push(quote! { #name_str });
        }
    }
    Ok(quote! {
        {
            let mut __props = ::server_less::serde_json::Map::new();
            #(#props)*
            ::server_less::serde_json::json!({
                "type": "object",
                "properties": ::server_less::serde_json::Value::Object(__props),
                "required": [#(#required),*],
            })
        }
    })
}

/// Expression that evaluates to the return-type JSON Schema (`serde_json::Value`)
/// for a leaf method. Mirrors the `output-schema` flag, but yields a value instead
/// of printing — used by the `--manual` aggregate.
fn leaf_output_schema_expr(method: &MethodInfo) -> TokenStream2 {
    let output_ty = if method.return_info.is_result {
        &method.return_info.ok_type
    } else if method.return_info.is_option {
        &method.return_info.some_type
    } else if method.return_info.is_unit {
        &None
    } else {
        &method.return_info.ty
    };
    #[cfg(feature = "jsonschema")]
    {
        if let Some(ty) = output_ty {
            quote! { ::server_less::cli_schema_for::<#ty>() }
        } else {
            quote! { ::server_less::serde_json::json!({"type": "null"}) }
        }
    }
    #[cfg(not(feature = "jsonschema"))]
    {
        type_to_json_schema(output_ty)
    }
}

/// Build the `CliManualNode` for a single leaf method, with its command path
/// computed as `prefix` + the leaf's CLI name.
fn generate_leaf_manual_node(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let name = cli_name(method);
    let input_schema = leaf_input_schema_expr(method)?;
    let output_schema = leaf_output_schema_expr(method);
    let (about, _) = split_docs(&method.docs);
    let description = if about.is_empty() {
        quote! { ::std::option::Option::None }
    } else {
        quote! { ::std::option::Option::Some(#about.to_string()) }
    };
    Ok(quote! {
        {
            let __path = if __prefix.is_empty() {
                #name.to_string()
            } else {
                format!("{} {}", __prefix, #name)
            };
            __nodes.push(::server_less::CliManualNode {
                path: __path,
                description: #description,
                input_schema: #input_schema,
                output_schema: #output_schema,
            });
        }
    })
}

/// Recurse into a **static** mount point (`fn(&self) -> &T`): extend the prefix
/// with the mount's CLI name and append the child type's subtree of manual nodes.
fn generate_static_mount_manual_node(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let name = cli_name(method);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;
    Ok(quote! {
        {
            let __child_prefix = if __prefix.is_empty() {
                #name.to_string()
            } else {
                format!("{} {}", __prefix, #name)
            };
            let __delegate = self.#method_name();
            __nodes.extend(
                <#inner_ty as ::server_less::CliSubcommand>::cli_manual_nodes(__delegate, &__child_prefix)
            );
        }
    })
}

/// Surface a **slug** mount point (`fn(&self, id) -> &T`) in the manual.
///
/// A slug mount's child is parameterized by a runtime value the manual cannot
/// synthesize, so we cannot construct an instance of the child to recurse into.
/// We therefore emit a single container node naming the mount and its slug
/// parameters, with the child type recorded in the description. The subtree's
/// per-leaf detail is reachable by invoking `tool <slug-mount> <id> --manual`.
fn generate_slug_mount_manual_node(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let name = cli_name(method);
    let (_, regular_params) = partition_context_params(&method.params)?;
    let slug_names: Vec<String> = regular_params
        .iter()
        .map(|p| format!("<{}>", cli_param_name(p)))
        .collect();
    let slug_suffix = if slug_names.is_empty() {
        String::new()
    } else {
        format!(" {}", slug_names.join(" "))
    };
    let (about, _) = split_docs(&method.docs);
    let desc_base = if about.is_empty() {
        "command group, selected by an <id> argument; run with an id value and --manual to see its subcommands"
            .to_string()
    } else {
        format!(
            "{about} — command group, selected by an <id> argument; run with an id value and --manual to see its subcommands"
        )
    };
    let path_suffix = slug_suffix.clone();
    Ok(quote! {
        {
            let __path = if __prefix.is_empty() {
                format!("{}{}", #name, #path_suffix)
            } else {
                format!("{} {}{}", __prefix, #name, #path_suffix)
            };
            __nodes.push(::server_less::CliManualNode {
                path: __path,
                description: ::std::option::Option::Some(#desc_base.to_string()),
                input_schema: ::server_less::serde_json::json!({"type": "object"}),
                output_schema: ::server_less::serde_json::json!({"type": "object"}),
            });
        }
    })
}

fn generate_static_mount_arm(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let subcommand_name = cli_name(method);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(quote! {
        Some((#subcommand_name, sub_matches)) => {
            let __delegate = self.#method_name();
            <#inner_ty as ::server_less::CliSubcommand>::cli_dispatch(__delegate, sub_matches)
        }
    })
}

fn generate_static_mount_arm_async(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let subcommand_name = cli_name(method);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(quote! {
        Some((#subcommand_name, sub_matches)) => {
            let __delegate = self.#method_name();
            <#inner_ty as ::server_less::CliSubcommand>::cli_dispatch_async(__delegate, sub_matches).await
        }
    })
}

fn generate_slug_mount_arm(method: &MethodInfo) -> syn::Result<TokenStream2> {
    let subcommand_name = cli_name(method);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    let (_, regular_params) = partition_context_params(&method.params)?;

    let mut slug_extractions = Vec::new();
    let mut slug_names = Vec::new();

    for p in regular_params {
        let name = &p.name;
        let name_str = cli_param_name(p);
        let ty = &p.ty;

        slug_extractions.push(quote! {
            let #name: #ty = sub_matches
                .get_one::<String>(#name_str)
                .map(|s| s.parse())
                .transpose()?
                .ok_or_else(|| format!("Missing required argument: {}", #name_str))?;
        });
        slug_names.push(quote! { #name });
    }

    Ok(quote! {
        Some((#subcommand_name, sub_matches)) => {
            #(#slug_extractions)*
            let __delegate = self.#method_name(#(#slug_names),*);
            <#inner_ty as ::server_less::CliSubcommand>::cli_dispatch(__delegate, sub_matches)
        }
    })
}

fn generate_slug_mount_arm_async(
    method: &MethodInfo,
) -> syn::Result<TokenStream2> {
    let subcommand_name = cli_name(method);
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    let (_, regular_params) = partition_context_params(&method.params)?;

    let mut slug_extractions = Vec::new();
    let mut slug_names = Vec::new();

    for p in regular_params {
        let name = &p.name;
        let name_str = cli_param_name(p);
        let ty = &p.ty;

        slug_extractions.push(quote! {
            let #name: #ty = sub_matches
                .get_one::<String>(#name_str)
                .map(|s| s.parse())
                .transpose()?
                .ok_or_else(|| format!("Missing required argument: {}", #name_str))?;
        });
        slug_names.push(quote! { #name });
    }

    Ok(quote! {
        Some((#subcommand_name, sub_matches)) => {
            #(#slug_extractions)*
            let __delegate = self.#method_name(#(#slug_names),*);
            <#inner_ty as ::server_less::CliSubcommand>::cli_dispatch_async(__delegate, sub_matches).await
        }
    })
}