plexus-macros 0.7.0

Procedural macros for Plexus RPC activations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
//! Attribute parsing for Plexus RPC macros

use std::collections::HashMap;
use syn::{
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    spanned::Spanned,
    Expr, ExprLit, ExprPath, ExprTuple, FnArg, GenericArgument, ImplItem, ImplItemFn, Lit, Meta,
    MetaList, MetaNameValue, Pat, PathArguments, ReturnType, Token, Type,
};

/// A parameter resolved from the auth context via an arbitrary expression.
/// Created by `#[from_auth(self.db.validate_user)]` on a method parameter.
#[derive(Debug, Clone)]
pub struct AuthResolver {
    /// The parameter name in the method signature
    pub param_name: syn::Ident,
    /// The resolver expression (e.g. `self.db.validate_user`)
    pub resolver_expr: syn::Expr,
}

/// The fallback value written into `DeprecationInfo.removed_in` when a method
/// is tagged with `#[deprecated]` but neither supplies a `removed_in` key
/// (which rustc ignores) nor a companion `#[plexus_macros::removed_in("X")]`
/// attribute.
///
/// Matches the ticket IR-3 specification (Context table, row "None +
/// `#[deprecated(...)]`"): `removed_in: "unspecified"`.
pub(crate) const DEPRECATION_REMOVED_IN_UNSPECIFIED: &str = "unspecified";

/// Parsed `DeprecationInfo` assembled from a method's `#[deprecated(...)]` and
/// `#[plexus_macros::removed_in("X")]` attributes.
///
/// Fields mirror `plexus_core::plexus::DeprecationInfo` — the codegen layer
/// translates this into a `MethodSchema.deprecation = Some(DeprecationInfo { .. })`
/// initializer.
#[derive(Debug, Clone)]
pub struct ParsedDeprecation {
    /// Version at which deprecation began (`since` on `#[deprecated]`, or
    /// empty string if omitted).
    pub since: String,
    /// Planned removal version. Sourced from either `#[plexus_macros::removed_in("X")]`
    /// or a `removed_in = "X"` key inside `#[deprecated(...)]` (rustc ignores
    /// the latter; we don't). Falls back to
    /// `DEPRECATION_REMOVED_IN_UNSPECIFIED` when neither is supplied.
    pub removed_in: String,
    /// Migration guidance (`note` on `#[deprecated]`, or empty string).
    pub message: String,
}

/// Bidirectional channel type configuration
#[derive(Debug, Clone)]
pub enum BidirType {
    /// Not bidirectional
    None,
    /// Use StandardBidirChannel (StandardRequest, StandardResponse)
    Standard,
    /// Use custom request/response types
    Custom { request: String, response: String },
}

/// Per-method override for the activation-level request type.
///
/// Used in `#[plexus::method(request = ())]` to exempt individual methods from
/// the activation-level request extraction. When set to `Skip`, the dispatch
/// wrapper omits the `<ReqType>::extract(raw_ctx)?` call for that method, even
/// if the activation declares `request = MyType`.
///
/// `Type` variant is reserved for future use (per-method request type override).
#[derive(Debug, Clone)]
pub enum MethodRequestOverride {
    /// `request = ()` — skip extraction for this method entirely.
    Skip,
    /// `request = SomeType` — use a different request type for this method (future).
    #[allow(dead_code)]
    Type(syn::Type),
}

/// Parsed attributes for #[hub_method]
pub struct HubMethodAttrs {
    pub name: Option<String>,
    /// Explicit description from `description = "..."` attribute argument.
    /// When `Some`, this wins over `///` doc comments. When `None`, the method's
    /// doc comments are used as the default description (see `MethodInfo::from_fn`).
    pub description: Option<String>,
    /// Parameter descriptions: param_name -> description
    pub param_docs: HashMap<String, String>,
    /// Specific enum variants this method can return (for filtered schema generation)
    /// When specified, the return schema will only include these variants from the event enum.
    /// Format: returns(Variant1, Variant2, Error)
    pub returns_variants: Vec<String>,
    /// If true, this method streams multiple events over time.
    /// If false (default), it yields a single result.
    /// Used to determine client API: streaming -> AsyncGenerator, non-streaming -> Promise
    pub streaming: bool,
    /// Bidirectional channel type (from #[hub_method(bidirectional)] or #[hub_method(bidirectional(request = "...", response = "..."))])
    pub bidirectional: BidirType,
    /// HTTP method for REST endpoints (GET, POST, PUT, DELETE, PATCH)
    /// Stored as string during parsing, converted to enum in code generation
    pub http_method: Option<String>,
    /// Per-method request override. `Some(Skip)` means `request = ()` — this method
    /// bypasses the activation-level request extraction even if the activation has
    /// `request = MyType`. `None` means inherit the activation-level behavior.
    pub request_override: Option<MethodRequestOverride>,
    /// RED-2: explicit acknowledgment that this method is intentionally
    /// public (no auth). Set by `#[plexus_macros::method(public)]`. Suppresses
    /// the mixed-auth warning for this method.
    ///
    /// R-1 (AUTHZ-CORE-2): also emitted into the generated `MethodSchema` as
    /// the `public` flag — the method is exempt from the default-deny gate.
    /// `public` and `scope = "..."` together is a compile error (a public
    /// method has no required scope to enforce).
    pub public: bool,
    /// R-1 (AUTHZ-CORE-2): explicit required scopes from one or more
    /// `scope = "..."` arguments. Multi-scope means conjunction — the caller
    /// must satisfy ALL listed scopes (AND, not OR; AUTHZ-S01-output §4).
    /// Empty means the implicit `<activation>.<method>` rule applies at
    /// registry-build time (AUTHZ-CORE-4's `ScopeRegistry` resolves it; the
    /// IR carries nothing for the implicit case).
    ///
    /// Each literal is validated against the AUTHZ-CORE-4 scope grammar at
    /// macro-expansion time (see [`validate_scope_literal`]).
    pub scopes: Vec<String>,
    /// AUTH-3: `target = "param"` — the param that locates what this call
    /// acts on. Must name one of the method's RPC params (checked in
    /// [`MethodInfo::from_fn`]).
    pub target: Option<syn::LitStr>,
    /// BIDIR-8: `answer_by = "caller" | "person" | "grant:<g>"` — who may
    /// answer a question the method asks mid-call. Checked in
    /// [`MethodInfo::from_fn`] (the error names the method).
    pub answer_by: Option<syn::LitStr>,
    /// SYNAPSE-13: `group = "write"` — the method's group in a listing
    /// (OpenAPI's tag); emitted as `MethodSchema.group`.
    pub group: Option<String>,
    /// SYNAPSE-13: `example(note = "…", params = r#"{…}"#)`, repeatable —
    /// worked calls, emitted as `MethodSchema.examples`. The params are
    /// checked to be a JSON object here and to name only the method's
    /// params in [`MethodInfo::from_fn`].
    pub examples: Vec<ParsedExample>,
    /// SYNAPSE-13: `values(status = ["Pending", "Ready"], …)` — the values a
    /// param is meant to take, a non-enforcing hint emitted as
    /// `x-plexus-values` on the param's property. Checked to name params in
    /// [`MethodInfo::from_fn`].
    pub values: Vec<(syn::Ident, Vec<String>)>,
}

/// SYNAPSE-13: one `example(note = "…", params = r#"{…}"#)` on a method.
#[derive(Debug, Clone)]
pub struct ParsedExample {
    /// What the call does, in a line (optional).
    pub note: Option<String>,
    /// The params object, as JSON text (validated to be an object).
    pub params_json: String,
    /// The params object's keys, in order, to check against the method.
    pub keys: Vec<String>,
    /// Where the params literal is, for errors.
    pub span: proc_macro2::Span,
}

/// SYNAPSE-13: parse `example(note = "…", params = "{…}")`'s arguments.
fn parse_example(path: &syn::Path, tokens: proc_macro2::TokenStream) -> syn::Result<ParsedExample> {
    let usage = "example(...) takes note = \"what it does\" and params = r#\"{ JSON object }\"#, \
                 e.g. example(note = \"set MENGER-40 to Coding\", params = r#\"{\"id\": \"MENGER-40\", \"status\": \"Coding\"}\"#)";
    let parser = Punctuated::<MetaNameValue, Token![,]>::parse_terminated;
    let nested = syn::parse::Parser::parse2(parser, tokens)
        .map_err(|e| syn::Error::new(e.span(), format!("{e}; {usage}")))?;
    let mut note = None;
    let mut params: Option<syn::LitStr> = None;
    for nv in nested {
        let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = &nv.value else {
            return Err(syn::Error::new_spanned(&nv.value, format!("expected a string literal; {usage}")));
        };
        if nv.path.is_ident("note") {
            if note.is_some() {
                return Err(syn::Error::new_spanned(&nv.path, "example(...) takes one note"));
            }
            note = Some(s.value());
        } else if nv.path.is_ident("params") {
            if params.is_some() {
                return Err(syn::Error::new_spanned(&nv.path, "example(...) takes one params"));
            }
            params = Some(s.clone());
        } else {
            return Err(syn::Error::new_spanned(&nv.path, format!("unknown key in example(...); {usage}")));
        }
    }
    let Some(lit) = params else {
        return Err(syn::Error::new_spanned(path, format!("example(...) needs params; {usage}")));
    };
    let text = lit.value();
    let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
        syn::Error::new(lit.span(), format!("example params are not JSON: {e}"))
    })?;
    let serde_json::Value::Object(map) = &value else {
        return Err(syn::Error::new(lit.span(), "example params must be a JSON object of the method's params, e.g. {\"id\": \"MENGER-40\"}"));
    };
    let keys = map.keys().cloned().collect();
    Ok(ParsedExample { note, params_json: value.to_string(), keys, span: lit.span() })
}

/// SYNAPSE-13: parse `values(param = ["A", "B"], …)`'s arguments.
fn parse_values(tokens: proc_macro2::TokenStream) -> syn::Result<Vec<(syn::Ident, Vec<String>)>> {
    let usage = "values(...) takes param = [\"A\", \"B\", …] pairs, e.g. values(status = [\"Pending\", \"Ready\"])";
    let parser = Punctuated::<MetaNameValue, Token![,]>::parse_terminated;
    let nested = syn::parse::Parser::parse2(parser, tokens)
        .map_err(|e| syn::Error::new(e.span(), format!("{e}; {usage}")))?;
    let mut out: Vec<(syn::Ident, Vec<String>)> = Vec::new();
    for nv in nested {
        let Some(ident) = nv.path.get_ident().cloned() else {
            return Err(syn::Error::new_spanned(&nv.path, format!("expected a parameter name; {usage}")));
        };
        if out.iter().any(|(i, _)| *i == ident) {
            return Err(syn::Error::new_spanned(&ident, format!("values for `{ident}` are given twice")));
        }
        let Expr::Array(arr) = &nv.value else {
            return Err(syn::Error::new_spanned(&nv.value, format!("expected an array of string literals; {usage}")));
        };
        let mut vals = Vec::new();
        for el in &arr.elems {
            let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = el else {
                return Err(syn::Error::new_spanned(el, format!("expected a string literal; {usage}")));
            };
            vals.push(s.value());
        }
        if vals.is_empty() {
            return Err(syn::Error::new_spanned(&nv.value, format!("values for `{ident}` are empty; {usage}")));
        }
        out.push((ident, vals));
    }
    Ok(out)
}

/// R-1 (AUTHZ-CORE-2 acceptance criterion #3): validate a `scope = "..."`
/// literal against the AUTHZ-CORE-4 scope grammar pinned by AUTHZ-S01-output
/// §1/§4:
///
/// - bare `*` ("all scopes"), or
/// - ASCII dot-separated segments, each matching `[a-z][a-z0-9_]*`,
/// - optionally ending in a `.*` segment wildcard (segment-bounded:
///   `cone.*` matches `cone.send_message`, not `forms.list`).
///
/// Returns a human-readable description of the violation on failure. The
/// canonical `Scope::try_new` (AUTHZ-CORE-4 / R-0) enforces the same grammar
/// at registry-build time; this compile-time check fails fast at the literal.
pub fn validate_scope_literal(s: &str) -> Result<(), String> {
    if s == "*" {
        return Ok(());
    }
    if s.is_empty() {
        return Err("scope must not be empty".to_string());
    }
    let segments: Vec<&str> = s.split('.').collect();
    for (i, seg) in segments.iter().enumerate() {
        let is_last = i == segments.len() - 1;
        if *seg == "*" {
            if is_last && segments.len() > 1 {
                continue; // trailing `.*` segment wildcard
            }
            return Err(
                "`*` is only valid as the entire scope or as the trailing `.*` segment"
                    .to_string(),
            );
        }
        let mut chars = seg.chars();
        let valid = match chars.next() {
            Some(c) if c.is_ascii_lowercase() => {
                chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
            }
            _ => false,
        };
        if !valid {
            return Err(format!(
                "segment `{}` must match [a-z][a-z0-9_]*",
                seg
            ));
        }
    }
    Ok(())
}

impl Parse for HubMethodAttrs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut name = None;
        let mut description: Option<String> = None;
        let mut param_docs = HashMap::new();
        let mut returns_variants = Vec::new();
        let mut streaming = false;
        let mut bidirectional = BidirType::None;
        let mut http_method = None;
        let mut request_override: Option<MethodRequestOverride> = None;
        let mut public = false;
        // R-1 (AUTHZ-CORE-2): explicit `scope = "..."` literals plus the
        // spans needed to anchor the `public` + `scope` contradiction error.
        let mut scopes: Vec<String> = Vec::new();
        let mut public_span: Option<proc_macro2::Span> = None;
        let mut first_scope_span: Option<proc_macro2::Span> = None;
        // AUTH-3: `target = "param"`.
        let mut target: Option<syn::LitStr> = None;
        // BIDIR-8: `answer_by = "…"`.
        let mut answer_by: Option<syn::LitStr> = None;
        // SYNAPSE-13: group, examples, values.
        let mut group: Option<String> = None;
        let mut examples: Vec<ParsedExample> = Vec::new();
        let mut values: Vec<(syn::Ident, Vec<String>)> = Vec::new();

        if !input.is_empty() {
            let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
            for meta in metas {
                match meta {
                    Meta::Path(path) => {
                        if path.is_ident("override_call") {
                            // Deprecated: use streaming pattern instead
                            // e.g., return impl Stream<Item = MyEvent> and forward PlexusStreamItem
                            // into your event type
                            return Err(syn::Error::new_spanned(
                                &path,
                                "override_call is deprecated. Use the streaming pattern instead:\n\
                                 - Return `impl Stream<Item = YourEvent>` from the method\n\
                                 - Forward PlexusStreamItem variants into your event enum\n\
                                 - Add `streaming` attribute if the method yields multiple events\n\
                                 See plexus.call implementation for an example.",
                            ));
                        } else if path.is_ident("streaming") {
                            streaming = true;
                        } else if path.is_ident("bidirectional") {
                            bidirectional = BidirType::Standard;
                        } else if path.is_ident("public") {
                            // RED-2: explicit acknowledgment that this method
                            // intentionally bypasses activation-level auth.
                            // R-1: also emitted as the MethodSchema `public`
                            // flag (exempt from the default-deny gate).
                            public = true;
                            public_span = Some(path.span());
                        }
                    }
                    Meta::NameValue(MetaNameValue { path, value, .. }) => {
                        if path.is_ident("name") {
                            if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                                name = Some(s.value());
                            }
                        } else if path.is_ident("description") {
                            if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                                description = Some(s.value());
                            }
                        } else if path.is_ident("http_method") {
                            if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                                let method = s.value().to_uppercase();
                                // Validate HTTP method
                                match method.as_str() {
                                    "GET" | "POST" | "PUT" | "DELETE" | "PATCH" => {
                                        http_method = Some(method);
                                    }
                                    _ => {
                                        return Err(syn::Error::new_spanned(
                                            s,
                                            format!(
                                                "Invalid HTTP method '{}'. Valid methods: GET, POST, PUT, DELETE, PATCH",
                                                method
                                            ),
                                        ));
                                    }
                                }
                            }
                        } else if path.is_ident("target") {
                            // AUTH-3: the param that locates what the call acts on.
                            let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value else {
                                return Err(syn::Error::new_spanned(
                                    &path,
                                    "target = ... expects the name of a parameter as a string, \
                                     e.g. #[plexus_macros::method(target = \"id\")]",
                                ));
                            };
                            target = Some(s);
                        } else if path.is_ident("answer_by") {
                            // BIDIR-8: who may answer the method's questions.
                            let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value else {
                                return Err(syn::Error::new_spanned(
                                    &path,
                                    "answer_by = ... expects a string: `caller` (the default), `person`, \
                                     or `grant:<activation.method>`, e.g. \
                                     #[plexus_macros::method(answer_by = \"person\")]",
                                ));
                            };
                            answer_by = Some(s);
                        } else if path.is_ident("group") {
                            // SYNAPSE-13: the method's group in a listing.
                            let usage = "group = ... expects a non-empty string, e.g. \
                                         #[plexus_macros::method(group = \"write\")]";
                            let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value else {
                                return Err(syn::Error::new_spanned(&path, usage));
                            };
                            if s.value().trim().is_empty() {
                                return Err(syn::Error::new(s.span(), usage));
                            }
                            if group.is_some() {
                                return Err(syn::Error::new(s.span(), "a method has one group"));
                            }
                            group = Some(s.value().trim().to_string());
                        } else if path.is_ident("scope") {
                            // R-1 (AUTHZ-CORE-2): explicit required scope.
                            // Repeatable — `scope = "x.y", scope = "x.z"`
                            // means the caller must satisfy ALL (AND).
                            let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value else {
                                return Err(syn::Error::new_spanned(
                                    &path,
                                    "scope = ... expects a string literal, e.g. \
                                     #[plexus_macros::method(scope = \"facet.write\")]",
                                ));
                            };
                            let literal = s.value();
                            if let Err(why) = validate_scope_literal(&literal) {
                                return Err(syn::Error::new(
                                    s.span(),
                                    format!(
                                        "invalid scope literal `{}`: {}. Scopes are ASCII \
                                         dot-separated segments matching [a-z][a-z0-9_]*, \
                                         optionally ending in a `.*` segment wildcard, or \
                                         the bare `*` (AUTHZ-CORE-4 scope grammar; see \
                                         `Scope::try_new`).",
                                        literal, why,
                                    ),
                                ));
                            }
                            if first_scope_span.is_none() {
                                first_scope_span = Some(s.span());
                            }
                            scopes.push(literal);
                        } else if path.is_ident("request") {
                            // request = ()  → skip activation-level request extraction
                            // request = SomeType → use a different request type (future)
                            match value {
                                Expr::Tuple(ExprTuple { ref elems, .. }) if elems.is_empty() => {
                                    request_override = Some(MethodRequestOverride::Skip);
                                }
                                Expr::Path(ExprPath { ref path, .. }) => {
                                    // Convert the path expression to a Type
                                    let ty: Type = Type::Path(syn::TypePath {
                                        qself: None,
                                        path: path.clone(),
                                    });
                                    request_override = Some(MethodRequestOverride::Type(ty));
                                }
                                _ => {
                                    // Unknown form — ignore for forward compatibility
                                }
                            }
                        }
                    }
                    Meta::List(MetaList { path, tokens, .. }) => {
                        if path.is_ident("params") {
                            // Parse params(name = "desc", other = "desc2")
                            let parser = Punctuated::<Meta, Token![,]>::parse_terminated;
                            let nested = syn::parse::Parser::parse2(parser, tokens.clone())?;
                            for meta in nested {
                                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
                                    if let Some(ident) = path.get_ident() {
                                        if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                                            param_docs.insert(ident.to_string(), s.value());
                                        }
                                    }
                                }
                            }
                        } else if path.is_ident("example") {
                            // SYNAPSE-13: a worked call, repeatable.
                            examples.push(parse_example(&path, tokens.clone())?);
                        } else if path.is_ident("examples") {
                            return Err(syn::Error::new_spanned(
                                &path,
                                "write each example as its own example(note = \"…\", params = r#\"{…}\"#)",
                            ));
                        } else if path.is_ident("values") {
                            // SYNAPSE-13: the values a param is meant to take.
                            for (ident, vals) in parse_values(tokens.clone())? {
                                if values.iter().any(|(i, _)| *i == ident) {
                                    return Err(syn::Error::new_spanned(&ident, format!("values for `{ident}` are given twice")));
                                }
                                values.push((ident, vals));
                            }
                        } else if path.is_ident("returns") {
                            // Parse returns(Variant1, Variant2, Error)
                            let parser = Punctuated::<syn::Ident, Token![,]>::parse_terminated;
                            let nested = syn::parse::Parser::parse2(parser, tokens.clone())?;
                            for ident in nested {
                                returns_variants.push(ident.to_string());
                            }
                        } else if path.is_ident("bidirectional") {
                            // Parse bidirectional(request = "MyReq", response = "MyResp")
                            let parser = Punctuated::<Meta, Token![,]>::parse_terminated;
                            let nested = syn::parse::Parser::parse2(parser, tokens.clone())?;

                            let mut request = None;
                            let mut response = None;

                            for meta in nested {
                                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
                                    if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                                        if path.is_ident("request") {
                                            request = Some(s.value());
                                        } else if path.is_ident("response") {
                                            response = Some(s.value());
                                        }
                                    }
                                }
                            }

                            match (request, response) {
                                (Some(req), Some(resp)) => {
                                    bidirectional = BidirType::Custom { request: req, response: resp };
                                }
                                _ => {
                                    return Err(syn::Error::new_spanned(
                                        &path,
                                        "bidirectional(...) requires both request and response parameters: bidirectional(request = \"MyReq\", response = \"MyResp\")"
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }

        // R-1 (AUTHZ-CORE-2 acceptance criterion #2): `public` and
        // `scope = "..."` together is a contradiction — a public method has
        // no required scope to enforce.
        if public && !scopes.is_empty() {
            let span = public_span
                .or(first_scope_span)
                .unwrap_or_else(proc_macro2::Span::call_site);
            return Err(syn::Error::new(
                span,
                "a public method has no required scope; remove `public` or remove `scope = ...`",
            ));
        }

        Ok(HubMethodAttrs { name, description, param_docs, returns_variants, streaming, bidirectional, http_method, request_override, public, scopes, target, answer_by, group, examples, values })
    }
}

/// MACRO-13: what the `trait` key is called once the keyword is renamed.
const TRAIT_KEY: &str = "__plexus_trait";

/// Maximum word count for description
const MAX_DESCRIPTION_WORDS: usize = 15;

/// Parsed attributes for #[hub_methods]
pub struct HubMethodsAttrs {
    /// `namespace = "..."`. MACRO-13: optional — when absent, the stem of
    /// `impl FooActivation` (or the trait's name) in snake_case.
    pub namespace: Option<String>,
    /// MACRO-13: `trait = "Bar"` — names the activation's trait (and its
    /// client, and absent `namespace` its namespace) whatever the type is
    /// called. Without it the trait is named from the stem of
    /// `impl FooActivation`; it is always emitted.
    pub trait_attr: Option<syn::LitStr>,
    /// Span of the `trait` key, for diagnostics.
    pub trait_span: Option<proc_macro2::Span>,
    /// MACRO-13: `methods = marked` — only `#[method]`s are on the wire (the
    /// rule before MACRO-13). `false` (the default for an activation the name
    /// rule applies to): every `pub async fn` on `&self` returning
    /// `impl Stream<Item = E>` is.
    pub methods_marked: bool,
    /// Explicit version string, or None to use CARGO_PKG_VERSION at compile time
    pub version: Option<String>,
    /// Short description (max 15 words)
    pub description: Option<String>,
    /// Long description (optional, for detailed documentation)
    pub long_description: Option<String>,
    /// Explicit crate path override. `None` means the default resolver
    /// (`proc-macro-crate`) should pick the path at codegen time.
    pub crate_path: Option<String>,
    /// If true, generate resolve_handle that delegates to self.resolve_handle_impl()
    pub resolve_handle: bool,
    /// If true, this activation is a hub with children (calls self.plugin_children())
    pub hub: bool,
    /// IR-5: span of the `hub` flag, used to anchor the deprecation warning.
    pub hub_span: Option<proc_macro2::Span>,
    /// Stable UUID for this plugin instance (for handle routing)
    /// If not provided, a deterministic UUID is generated from namespace
    pub plugin_id: Option<String>,
    /// If set, namespace() will call this method instead of returning the constant
    /// e.g., namespace_fn = "runtime_namespace" generates: fn namespace(&self) -> &str { self.runtime_namespace() }
    pub namespace_fn: Option<String>,
    /// Activation-level request type (from `request = MyRequest`).
    /// When set, the dispatch code extracts this type from the raw HTTP context
    /// and injects fields into methods that declare `#[activation_param]`.
    pub request_type: Option<syn::Type>,
    /// Child activation field names (from `children = [field_a, field_b]`).
    /// When set, the generated `ChildRouter::get_child()` dispatches by field name,
    /// enabling type-safe `parent.child.method` hierarchical routing.
    /// Each ident must match both a struct field name and the child's namespace.
    pub children: Vec<syn::Ident>,
    /// IR-5: span of the `children = [...]` attribute, for deprecation warning.
    pub children_span: Option<proc_macro2::Span>,
    /// REQ-10: locked fields of the activation-level request struct.
    /// When non-empty, methods CANNOT use `#[plexus_macros::method(request = ())]`
    /// to drop activation-level extraction — the macro emits a compile error
    /// naming the locked fields. Field idents must be in the activation's
    /// request struct.
    pub required_fields: Vec<syn::Ident>,
    /// Span of the `required = [...]` attribute for diagnostics.
    pub required_fields_span: Option<proc_macro2::Span>,
    /// RED-6: declared auth posture for this activation.
    ///
    /// - `Required`: every method must have `#[from_auth]` OR
    ///   `#[plexus_macros::method(public)]` — compile error otherwise.
    /// - `Optional` (default): no enforcement; RED-2 emits a compile warning
    ///   when auth is asymmetric across methods.
    /// - `Mixed`: like `Optional`, but suppresses the RED-2 warning —
    ///   explicit acknowledgment that the asymmetry is intentional.
    /// - `None`: no method may have `#[from_auth]` — compile error if any
    ///   method does. Affirmative declaration of a public activation.
    ///
    /// Parsed from `auth = "required" | "optional" | "mixed" | "none"`.
    ///
    /// R-1 (joint AP-1): `None` means the activation never declared a
    /// posture — enforcement treats that as `Optional` (unchanged), but the
    /// IR emission stays silent so posture-silent activations produce
    /// byte-identical schemas to pre-R-1 (AP-1 acceptance criterion #2).
    /// `Some(p)` is emitted into every generated `MethodSchema.auth_posture`.
    pub auth_posture: Option<AuthPosture>,
    /// MACRO-2: emit the typed client alongside the server side.
    ///
    /// Opt-in (`client` as a bare flag) rather than automatic, because the
    /// emitted client links against `plexus-client`; turning it on for
    /// everyone would break every existing consumer that has not added the
    /// dependency. Same additive rule AUTHZ-CRED-MACRO-3 used for
    /// `plexus-auth-core`.
    pub client: bool,
    /// MACRO-12: `typed_params` — a method parameter typed literally
    /// `String`, `&str`, `Option<String>`, `Option<&str>` or `Vec<String>`
    /// is a compile error on that parameter. Off by default for 0.6.
    pub typed_params: bool,
    /// Span of the `client` flag, so a missing `plexus-client` dependency
    /// points at the flag that asked for it.
    pub client_span: Option<proc_macro2::Span>,
    /// MACRO-2: a `cfg` predicate under which the **server** half of the
    /// expansion is compiled — the impl block, the method enum, the
    /// `Activation` impl, the jsonrpsee trait, the dependency shim.
    ///
    /// This is what makes an activation crate reachable from wasm32. With
    /// `server_cfg = "feature = \"server\""`, a `--no-default-features`
    /// build of the activation's crate emits *only* the typed client, which
    /// depends on nothing but `plexus-client` and the activation's own
    /// event and parameter types. The consumer says one dependency line
    /// (`tickets-api = { version = "..", default-features = false }`) and
    /// gets a client that compiles for the browser.
    ///
    /// The predicate is any `cfg` meta: `feature = "server"`,
    /// `not(target_arch = "wasm32")`, `all(..)`. Only the macro's own output
    /// is gated — the author still gates their own struct definition and
    /// server-only imports, as they would for any optional dependency.
    pub server_cfg: Option<String>,
    /// Span of `server_cfg`, for diagnostics.
    pub server_cfg_span: Option<proc_macro2::Span>,
    /// AUTH-3: default roles, `roles(viewer = ["get", …], editor = [viewer,
    /// "create", …])` — each an explicit list of this activation's methods,
    /// or roles declared before it. Validated in `generate_all` against the
    /// methods; emitted as `PluginSchema.roles` (flattened to grants).
    pub roles: Vec<RoleDecl>,
}

/// AUTH-3: one `name = [entry, …]` of `roles(...)`.
pub struct RoleDecl {
    pub name: syn::Ident,
    pub entries: Vec<RoleEntry>,
}

/// AUTH-3: a role's entry — a method of the activation (`"get"`) or an
/// earlier role (`viewer`).
pub enum RoleEntry {
    Method(syn::LitStr),
    Role(syn::Ident),
}

impl Parse for RoleDecl {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: syn::Ident = input.parse()?;
        input.parse::<Token![=]>()?;
        let content;
        syn::bracketed!(content in input);
        let mut entries = Vec::new();
        while !content.is_empty() {
            if content.peek(syn::LitStr) {
                entries.push(RoleEntry::Method(content.parse()?));
            } else if content.peek(syn::Ident) {
                entries.push(RoleEntry::Role(content.parse()?));
            } else {
                return Err(content.error(
                    "a role lists methods as strings (\"get\") and earlier roles by name (viewer)",
                ));
            }
            if content.is_empty() {
                break;
            }
            content.parse::<Token![,]>()?;
        }
        Ok(RoleDecl { name, entries })
    }
}

/// RED-6: declared auth enforcement posture for an activation.
/// See `HubMethodsAttrs::auth_posture` for semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AuthPosture {
    Required,
    #[default]
    Optional,
    Mixed,
    None,
}

impl Parse for HubMethodsAttrs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut namespace: Option<String> = None;
        let mut trait_attr: Option<syn::LitStr> = None;
        let mut trait_span: Option<proc_macro2::Span> = None;
        let mut methods_marked = false;
        let mut version: Option<String> = None;
        let mut description = None;
        let mut long_description = None;
        let mut crate_path: Option<String> = None;
        let mut resolve_handle = false;
        let mut hub = false;
        let mut hub_span: Option<proc_macro2::Span> = None;
        let mut plugin_id = None;
        let mut namespace_fn = None;
        let mut request_type: Option<syn::Type> = None;
        let mut children: Vec<syn::Ident> = Vec::new();
        let mut children_span: Option<proc_macro2::Span> = None;
        let mut required_fields: Vec<syn::Ident> = Vec::new();
        let mut required_fields_span: Option<proc_macro2::Span> = None;
        // R-1: `None` = posture never declared (enforced as Optional, not
        // emitted); `Some(p)` = declared and emitted.
        let mut auth_posture: Option<AuthPosture> = None;
        // MACRO-2: opt-in typed-client emission.
        let mut client = false;
        let mut typed_params = false;
        let mut client_span: Option<proc_macro2::Span> = None;
        let mut server_cfg: Option<String> = None;
        let mut server_cfg_span: Option<proc_macro2::Span> = None;
        // AUTH-3: default roles.
        let mut roles: Vec<RoleDecl> = Vec::new();

        if !input.is_empty() {
            // MACRO-13: `trait` is a keyword, which a `Meta` path refuses;
            // a top-level `trait` key is renamed before the parse.
            let tokens: proc_macro2::TokenStream = input.parse()?;
            let tokens: proc_macro2::TokenStream = tokens
                .into_iter()
                .map(|tt| match tt {
                    proc_macro2::TokenTree::Ident(id) if id == "trait" => {
                        proc_macro2::TokenTree::Ident(syn::Ident::new(TRAIT_KEY, id.span()))
                    }
                    other => other,
                })
                .collect();
            let metas = syn::parse::Parser::parse2(
                Punctuated::<Meta, Token![,]>::parse_terminated,
                tokens,
            )?;

            for meta in metas {
                match meta {
                    Meta::NameValue(MetaNameValue { path, value, .. }) => {
                        // Handle `request = SomeType` — value is a path/type expression,
                        // not a string literal. We parse the Expr and convert to a Type.
                        if path.is_ident("request") {
                            // The value after `=` is an expression (e.g. Expr::Path for `TestRequest`).
                            // Expr::Path can be directly reinterpreted as a Type::Path.
                            let ty: syn::Type = expr_to_type(&value).ok_or_else(|| {
                                syn::Error::new_spanned(&path, "request = <Type>: expected a type path (e.g. request = MyRequest or request = ())")
                            })?;
                            request_type = Some(ty);
                            continue;
                        }

                        // MACRO-13: `methods = marked` (or `"marked"`), `methods = all`.
                        if path.is_ident("methods") {
                            let word = match &value {
                                Expr::Path(p) if p.path.get_ident().is_some() => {
                                    p.path.get_ident().unwrap().to_string()
                                }
                                Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) => s.value(),
                                _ => String::new(),
                            };
                            methods_marked = match word.as_str() {
                                "marked" => true,
                                "all" => false,
                                _ => {
                                    return Err(syn::Error::new_spanned(
                                        &value,
                                        "methods = marked (only #[plexus_macros::method]s are on the wire) \
                                         or methods = all (every `pub async fn` on `&self` returning \
                                         `impl Stream<Item = E>`, the default)",
                                    ))
                                }
                            };
                            continue;
                        }

                        if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                            if path.is_ident(TRAIT_KEY) {
                                // MACRO-13: `trait = "Bar"` names the trait and the client.
                                if syn::parse_str::<syn::Ident>(&s.value()).is_err() {
                                    return Err(syn::Error::new(
                                        s.span(),
                                        format!("trait = \"{}\" must be an identifier, e.g. trait = \"Driver\"", s.value()),
                                    ));
                                }
                                trait_span = Some(path.span());
                                trait_attr = Some(s);
                            } else if path.is_ident("namespace") {
                                namespace = Some(s.value());
                            } else if path.is_ident("version") {
                                version = Some(s.value());
                            } else if path.is_ident("description") {
                                let desc = s.value();
                                // Validate word count
                                let word_count = desc.split_whitespace().count();
                                if word_count > MAX_DESCRIPTION_WORDS {
                                    return Err(syn::Error::new(
                                        s.span(),
                                        format!(
                                            "description must be {} words or fewer (found {} words). \
                                            Use long_description for detailed text.",
                                            MAX_DESCRIPTION_WORDS, word_count
                                        ),
                                    ));
                                }
                                description = Some(desc);
                            } else if path.is_ident("long_description") {
                                long_description = Some(s.value());
                            } else if path.is_ident("crate_path") {
                                crate_path = Some(s.value());
                            } else if path.is_ident("plugin_id") {
                                // Validate UUID format
                                let id_str = s.value();
                                if uuid::Uuid::parse_str(&id_str).is_err() {
                                    return Err(syn::Error::new(
                                        s.span(),
                                        format!("plugin_id must be a valid UUID, got: {}", id_str),
                                    ));
                                }
                                plugin_id = Some(id_str);
                            } else if path.is_ident("namespace_fn") {
                                namespace_fn = Some(s.value());
                            } else if path.is_ident("server_cfg") {
                                // MACRO-2: cfg predicate gating the server half.
                                server_cfg = Some(s.value());
                                server_cfg_span = Some(s.span());
                            } else if path.is_ident("auth") {
                                // RED-6: declared auth enforcement posture.
                                // See HubMethodsAttrs::auth_posture for semantics.
                                let v = s.value();
                                auth_posture = match v.as_str() {
                                    "required" => Some(AuthPosture::Required),
                                    "optional" => Some(AuthPosture::Optional),
                                    "mixed"    => Some(AuthPosture::Mixed),
                                    "none"     => Some(AuthPosture::None),
                                    other => return Err(syn::Error::new(
                                        s.span(),
                                        format!(
                                            "auth must be one of \"required\", \"optional\", \"mixed\", \"none\"; got {:?}",
                                            other,
                                        ),
                                    )),
                                };
                            }
                        }
                    }
                    Meta::Path(path) => {
                        // Handle bare flags like `resolve_handle`, `hub`
                        if path.is_ident("resolve_handle") {
                            resolve_handle = true;
                        } else if path.is_ident("hub") {
                            hub = true;
                            hub_span = Some(path.span());
                        } else if path.is_ident(TRAIT_KEY) {
                            // MACRO-13 (`always`): the trait is emitted for
                            // every activation; a bare `trait` asks nothing.
                            return Err(syn::Error::new(
                                path.span(),
                                "the trait is always emitted, named from `impl FooActivation`'s \
                                 stem; write `trait = \"Name\"` to name it otherwise",
                            ));
                        } else if path.is_ident("client") {
                            // MACRO-2: also emit the typed client.
                            client = true;
                            client_span = Some(path.span());
                        } else if path.is_ident("typed_params") {
                            // MACRO-12: refuse bare string parameters.
                            typed_params = true;
                        }
                    }
                    Meta::List(list) => {
                        // children = [field_a, field_b, ...]
                        if list.path.is_ident("children") {
                            let parser = Punctuated::<syn::Ident, Token![,]>::parse_terminated;
                            let idents = syn::parse::Parser::parse2(parser, list.tokens.clone())?;
                            children = idents.into_iter().collect();
                            children_span = Some(list.path.span());
                        }
                        // REQ-10: required = [field_a, field_b, ...] — activation-level
                        // lock list. Methods may not drop these with `request = ()`.
                        else if list.path.is_ident("roles") {
                            // AUTH-3: roles(viewer = ["get"], editor = [viewer, "create"])
                            let parser = Punctuated::<RoleDecl, Token![,]>::parse_terminated;
                            let decls = syn::parse::Parser::parse2(parser, list.tokens.clone())?;
                            roles.extend(decls);
                        }
                        else if list.path.is_ident("required") {
                            let parser = Punctuated::<syn::Ident, Token![,]>::parse_terminated;
                            let idents = syn::parse::Parser::parse2(parser, list.tokens.clone())?;
                            required_fields = idents.into_iter().collect();
                            required_fields_span = Some(list.path.span());
                        }
                    }
                }
            }
        }

        // MACRO-13: a missing namespace is resolved (from the stem) or
        // refused in `generate_all`, which knows the type's name.
        if namespace.as_deref() == Some("") {
            return Err(syn::Error::new(input.span(), "namespace = \"\" names nothing"));
        }

        Ok(HubMethodsAttrs {
            namespace,
            trait_attr,
            trait_span,
            methods_marked,
            version,
            description,
            long_description,
            crate_path,
            resolve_handle,
            hub,
            hub_span,
            plugin_id,
            namespace_fn,
            request_type,
            children,
            children_span,
            required_fields,
            required_fields_span,
            auth_posture,
            client,
            typed_params,
            client_span,
            server_cfg,
            server_cfg_span,
            roles,
        })
    }
}

/// Parameter info with optional description
pub struct ParamInfo {
    pub name: syn::Ident,
    pub ty: Type,
    pub description: Option<String>,
    /// IR-5: parsed `#[deprecated(...)]` (+ optional
    /// `#[plexus_macros::removed_in]`) on this parameter in the method
    /// signature. Populated into `ParamSchema.deprecation` on the emitted
    /// `MethodSchema.params_meta` list.
    pub deprecation: Option<ParsedDeprecation>,
}

/// A parameter injected from the activation's extracted request struct.
/// Created by `#[activation_param]` on a method parameter.
#[derive(Debug, Clone)]
pub struct ActivationParamInfo {
    /// The parameter name in the method signature (must match a field in the request struct)
    pub param_name: syn::Ident,
    /// The declared type in the method (Rust enforces this matches the request struct field type)
    pub ty: Type,
}

/// The kind of child-dispatch a `#[child]`-annotated method participates in.
#[derive(Debug, Clone)]
pub enum ChildMethodKind {
    /// `fn NAME(&self) -> Child` — a named static child whose routing name
    /// is the method identifier.
    Static,
    /// `fn NAME(&self, name: &str) -> Option<Child>` — a fallback dispatcher
    /// that receives every name not matched by a static child.
    Dynamic,
}

/// MACRO-20: the forward policy a `#[child(forward = "...")]` names — what
/// the child's call context keeps of its caller's
/// (`ChildRouter::forward_policy_for`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChildForward {
    /// `"same_service"` — everything: principal stamp, session, ceiling
    /// (`plexus_core::plexus::SameService`). A static child's default.
    SameService,
    /// `"identity_only"` — the verified user id and session id only; the
    /// metadata (principal stamp, session key and expiry, ceiling) dropped
    /// (`IdentityOnly`). For a deputy that must not see the caller's session.
    IdentityOnly,
    /// `"pass_through"` — everything, named as an explicit pass-through.
    PassThrough,
    /// `"anonymous"` — nothing: the child runs as anonymous.
    Anonymous,
}

impl ChildForward {
    /// The spellings `forward = "..."` takes.
    pub const SPELLINGS: &'static str = "\"same_service\", \"identity_only\", \"pass_through\" or \"anonymous\"";

    fn parse(s: &str) -> Option<Self> {
        match s {
            "same_service" => Some(Self::SameService),
            "identity_only" => Some(Self::IdentityOnly),
            "pass_through" => Some(Self::PassThrough),
            "anonymous" => Some(Self::Anonymous),
            _ => None,
        }
    }
}

/// Information extracted from a `#[plexus_macros::child]`-annotated method.
#[derive(Debug, Clone)]
pub struct ChildMethodInfo {
    /// The function identifier (used as routing name for static children).
    pub fn_name: syn::Ident,
    /// Doc-comment-derived description. Currently unused for codegen but
    /// threaded through so future tickets (CHILD-4) can project it into
    /// child listings/schemas.
    #[allow(dead_code)]
    pub description: String,
    /// Whether this is a static (no-arg) or dynamic (name: &str) child method.
    pub kind: ChildMethodKind,
    /// Whether the method is `async fn` — the generated dispatcher awaits it.
    pub is_async: bool,
    /// CHILD-4: when `#[child(list = "METHOD")]` is present, the name of the
    /// sibling method that streams child names for `ChildRouter::list_children`.
    pub list_fn: Option<syn::Ident>,
    /// CHILD-4: when `#[child(search = "METHOD")]` is present, the name of the
    /// sibling method that streams child names matching a query for
    /// `ChildRouter::search_children`.
    pub search_fn: Option<syn::Ident>,
    /// IR-3: parsed `#[deprecated(...)]` + `#[plexus_macros::removed_in]` info
    /// folded into the emitted `MethodSchema.deprecation` field.
    pub deprecation: Option<ParsedDeprecation>,
    /// MACRO-20: `#[child(forward = "...")]` — how the child inherits its
    /// caller. `None` when not written: a static child is then
    /// [`ChildForward::SameService`], a dynamic one the framework's default
    /// (`IdentityOnly`).
    pub forward: Option<ChildForward>,
    /// MACRO-16: the declared return type — `Child` for a static child,
    /// `Option<Child>` for a dynamic one. The client codegen names the
    /// child's generated client from it.
    pub return_ty: syn::Type,
}

impl ChildMethodInfo {
    /// Build a `ChildMethodInfo` from an impl-block method. Validates the
    /// signature and returns a `syn::Error` with the phrase
    /// `child method signature` for any unsupported shape.
    pub fn from_fn(method: &ImplItemFn) -> syn::Result<Self> {
        let fn_name = method.sig.ident.clone();
        let is_async = method.sig.asyncness.is_some();
        let description = extract_doc_description(&method.attrs).unwrap_or_default();

        // CHILD-4: parse `list = "method"` / `search = "method"` args off the
        // `#[child(...)]` attribute. The attribute itself is the sole carrier
        // of these args — no other attribute recognizes them.
        let (list_fn, search_fn, forward) = parse_child_attr_args(&method.attrs)?;

        // IR-3: capture deprecation metadata from `#[deprecated(...)]` +
        // `#[plexus_macros::removed_in("X")]` on this child method.
        let deprecation = parse_deprecation_attrs(&method.attrs, method.sig.span())?;

        // Collect non-self typed parameters.
        let mut typed_params: Vec<&syn::PatType> = Vec::new();
        let mut has_receiver = false;
        for arg in &method.sig.inputs {
            match arg {
                FnArg::Receiver(_) => has_receiver = true,
                FnArg::Typed(pt) => typed_params.push(pt),
            }
        }

        if !has_receiver {
            return Err(syn::Error::new_spanned(
                &method.sig,
                "unsupported child method signature: a #[child] method must take `&self` \
                 (shapes: `fn NAME(&self) -> Child` or `fn NAME(&self, name: &str) -> Option<Child>`)",
            ));
        }

        let kind = match typed_params.len() {
            0 => ChildMethodKind::Static,
            1 => {
                // Must be a parameter of type `&str`.
                let pt = typed_params[0];
                if !is_str_ref(&pt.ty) {
                    return Err(syn::Error::new_spanned(
                        &pt.ty,
                        "unsupported child method signature: the single parameter of a dynamic \
                         #[child] method must be `name: &str` \
                         (shapes: `fn NAME(&self) -> Child` or `fn NAME(&self, name: &str) -> Option<Child>`)",
                    ));
                }
                ChildMethodKind::Dynamic
            }
            _ => {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "unsupported child method signature: #[child] methods accept either \
                     no extra arguments (static child) or a single `name: &str` argument \
                     (dynamic child)",
                ));
            }
        };

        // Require an explicit return type; the specific trait bounds on the
        // return value (`ChildRouter + Clone + Send + Sync + 'static`) are
        // enforced by the generated code, not here — that gives better
        // error messages pointing at the user's type.
        let return_ty = match &method.sig.output {
            ReturnType::Type(_, ty) => (**ty).clone(),
            ReturnType::Default => {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "unsupported child method signature: a #[child] method must declare a return type \
                     (either `-> Child` for a static child or `-> Option<Child>` for a dynamic child)",
                ));
            }
        };

        Ok(ChildMethodInfo {
            fn_name,
            description,
            kind,
            is_async,
            list_fn,
            search_fn,
            deprecation,
            forward,
            return_ty,
        })
    }
}

/// Parse the arguments of a `#[child(...)]` / `#[plexus_macros::child(...)]`
/// attribute. Supported args:
///
/// - `list = "method_name"` — links a sibling list method for CHILD-4
/// - `search = "method_name"` — links a sibling search method for CHILD-4
/// - `forward = "same_service" | "identity_only" | "pass_through" | "anonymous"`
///   — MACRO-20: how the child inherits its caller
///
/// If the attribute is bare (`#[child]`) every returned value is `None`.
/// Unknown args are rejected so typos surface early.
fn parse_child_attr_args(
    attrs: &[syn::Attribute],
) -> syn::Result<(Option<syn::Ident>, Option<syn::Ident>, Option<ChildForward>)> {
    let mut list_fn: Option<syn::Ident> = None;
    let mut search_fn: Option<syn::Ident> = None;
    let mut forward: Option<ChildForward> = None;

    for attr in attrs {
        let path = attr.path();
        let last = path.segments.last().map(|s| s.ident.to_string());
        if !matches!(last.as_deref(), Some("child")) {
            continue;
        }

        match &attr.meta {
            // Bare `#[child]` — no args, nothing to parse.
            Meta::Path(_) => {}
            // `#[child(list = "...", search = "...")]`
            Meta::List(list) => {
                let metas = list.parse_args_with(
                    Punctuated::<Meta, Token![,]>::parse_terminated,
                )?;
                for meta in metas {
                    match meta {
                        Meta::NameValue(MetaNameValue { path, value, .. }) => {
                            let ident_key = match path.get_ident() {
                                Some(id) => id.to_string(),
                                None => {
                                    return Err(syn::Error::new_spanned(
                                        &path,
                                        "unknown argument to #[plexus_macros::child]; \
                                         expected `list = \"method\"`, `search = \"method\"` or `forward = \"policy\"`",
                                    ));
                                }
                            };
                            let s = match value {
                                Expr::Lit(ExprLit { lit: Lit::Str(ref s), .. }) => s.clone(),
                                _ => {
                                    return Err(syn::Error::new_spanned(
                                        &value,
                                        format!(
                                            "#[plexus_macros::child({} = \"...\")] expects a string literal naming a sibling method",
                                            ident_key
                                        ),
                                    ));
                                }
                            };
                            if ident_key == "forward" {
                                if forward.is_some() {
                                    return Err(syn::Error::new_spanned(
                                        &s,
                                        "duplicate `forward = \"...\"` argument on #[plexus_macros::child]",
                                    ));
                                }
                                forward = Some(ChildForward::parse(&s.value()).ok_or_else(|| {
                                    syn::Error::new_spanned(
                                        &s,
                                        format!(
                                            "unknown forward policy \"{}\" on #[plexus_macros::child]; expected {}",
                                            s.value(),
                                            ChildForward::SPELLINGS
                                        ),
                                    )
                                })?);
                                continue;
                            }
                            let method_ident = syn::Ident::new(&s.value(), s.span());
                            match ident_key.as_str() {
                                "list" => {
                                    if list_fn.is_some() {
                                        return Err(syn::Error::new_spanned(
                                            &s,
                                            "duplicate `list = \"...\"` argument on #[plexus_macros::child]",
                                        ));
                                    }
                                    list_fn = Some(method_ident);
                                }
                                "search" => {
                                    if search_fn.is_some() {
                                        return Err(syn::Error::new_spanned(
                                            &s,
                                            "duplicate `search = \"...\"` argument on #[plexus_macros::child]",
                                        ));
                                    }
                                    search_fn = Some(method_ident);
                                }
                                other => {
                                    return Err(syn::Error::new_spanned(
                                        &path,
                                        format!(
                                            "unknown argument `{}` to #[plexus_macros::child]; \
                                             expected `list = \"method\"`, `search = \"method\"` or `forward = \"policy\"`",
                                            other
                                        ),
                                    ));
                                }
                            }
                        }
                        other => {
                            return Err(syn::Error::new_spanned(
                                other,
                                "unknown argument to #[plexus_macros::child]; \
                                 expected `list = \"method\"`, `search = \"method\"` or `forward = \"policy\"`",
                            ));
                        }
                    }
                }
            }
            Meta::NameValue(_) => {
                return Err(syn::Error::new_spanned(
                    attr,
                    "#[plexus_macros::child = ...] form is not supported; \
                     use `#[plexus_macros::child]` or `#[plexus_macros::child(list = \"...\", search = \"...\")]`",
                ));
            }
        }
    }

    Ok((list_fn, search_fn, forward))
}

/// The stream-return shape of a sibling `list` / `search` method referenced by
/// `#[child(list = "...")]` / `#[child(search = "...")]`.
#[derive(Debug, Clone, Copy)]
pub enum ListSearchReturnShape {
    /// `-> impl Stream<Item = String> [+ bounds...]`
    ImplStream,
    /// `-> BoxStream<'_, String>` (any lifetime; any path tail)
    BoxStream,
}

/// Information extracted from a sibling method referenced by
/// `#[child(list = "...")]` or `#[child(search = "...")]`.
#[derive(Debug, Clone)]
pub struct ListSearchMethodInfo {
    pub fn_name: syn::Ident,
    pub is_async: bool,
    #[allow(dead_code)]
    pub return_shape: ListSearchReturnShape,
}

/// Enum tagging which kind of list/search method signature we're validating.
#[derive(Debug, Clone, Copy)]
pub enum ListSearchKind {
    /// `(async) fn METHOD(&self) -> Stream<Item = String>` form.
    List,
    /// `(async) fn METHOD(&self, query: &str) -> Stream<Item = String>` form.
    Search,
}

/// Find a sibling method in `items` by name and validate that its signature
/// matches the expected `list` / `search` shape. Returns `ListSearchMethodInfo`
/// on success, or a `syn::Error` with one of:
///   - `"not found in impl"` when no method of that name exists.
///   - a signature-mismatch message when parameters / return type don't match.
pub fn find_and_validate_list_search_method(
    items: &[ImplItem],
    name: &syn::Ident,
    kind: ListSearchKind,
    attr_owner: &syn::Ident,
) -> syn::Result<ListSearchMethodInfo> {
    // Locate the named sibling method.
    let method: &ImplItemFn = items
        .iter()
        .find_map(|it| match it {
            ImplItem::Fn(f) if f.sig.ident == *name => Some(f),
            _ => None,
        })
        .ok_or_else(|| {
            syn::Error::new(
                name.span(),
                format!(
                    "method `{}` referenced by #[plexus_macros::child({} = \"{}\")] \
                     on `{}` not found in impl",
                    name,
                    match kind {
                        ListSearchKind::List => "list",
                        ListSearchKind::Search => "search",
                    },
                    name,
                    attr_owner,
                ),
            )
        })?;

    // Validate signature: `&self` + extra typed params.
    let mut has_receiver = false;
    let mut typed_params: Vec<&syn::PatType> = Vec::new();
    for arg in method.sig.inputs.iter() {
        match arg {
            FnArg::Receiver(_) => has_receiver = true,
            FnArg::Typed(pt) => typed_params.push(pt),
        }
    }
    if !has_receiver {
        return Err(syn::Error::new_spanned(
            &method.sig,
            format!(
                "child method signature mismatch: `{}` must take `&self` (expected shape: `(async) fn {}({}) -> impl Stream<Item = String>` or `-> BoxStream<'_, String>`)",
                name,
                name,
                match kind {
                    ListSearchKind::List => "&self",
                    ListSearchKind::Search => "&self, query: &str",
                },
            ),
        ));
    }
    match kind {
        ListSearchKind::List => {
            if !typed_params.is_empty() {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    format!(
                        "child method signature mismatch: list method `{}` must take only `&self` (got {} extra parameter{}); expected `(async) fn {}(&self) -> impl Stream<Item = String>` or `-> BoxStream<'_, String>`",
                        name,
                        typed_params.len(),
                        if typed_params.len() == 1 { "" } else { "s" },
                        name,
                    ),
                ));
            }
        }
        ListSearchKind::Search => {
            if typed_params.len() != 1 {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    format!(
                        "child method signature mismatch: search method `{}` must take `&self` and exactly one `query: &str` parameter (got {}); expected `(async) fn {}(&self, query: &str) -> impl Stream<Item = String>` or `-> BoxStream<'_, String>`",
                        name,
                        typed_params.len(),
                        name,
                    ),
                ));
            }
            if !is_str_ref(&typed_params[0].ty) {
                return Err(syn::Error::new_spanned(
                    &typed_params[0].ty,
                    format!(
                        "child method signature mismatch: the query parameter of search method `{}` must be `&str`",
                        name
                    ),
                ));
            }
        }
    }

    // Validate return type: accept either `impl Stream<Item = String> [+ bounds]`
    // or `BoxStream<'_, String>`.
    let return_ty = match &method.sig.output {
        ReturnType::Default => {
            return Err(syn::Error::new_spanned(
                &method.sig,
                format!(
                    "child method signature mismatch: `{}` must declare a return type of \
                     `impl Stream<Item = String>` or `BoxStream<'_, String>`",
                    name
                ),
            ));
        }
        ReturnType::Type(_, ty) => ty.as_ref(),
    };

    let return_shape = classify_string_stream_return(return_ty).ok_or_else(|| {
        syn::Error::new_spanned(
            return_ty,
            format!(
                "child method signature mismatch: `{}` must return `impl Stream<Item = String>` or `BoxStream<'_, String>`",
                name,
            ),
        )
    })?;

    Ok(ListSearchMethodInfo {
        fn_name: method.sig.ident.clone(),
        is_async: method.sig.asyncness.is_some(),
        return_shape,
    })
}

/// Classify a return type as one of the accepted `String`-stream shapes, or
/// `None` if neither. Recognized:
///   - `impl Stream<Item = String> [+ Bounds]` (any bound order)
///   - `BoxStream<'a, String>` / `BoxStream<'_, String>` (any path tail of
///     `BoxStream`, single or double angle-bracket form)
fn classify_string_stream_return(ty: &Type) -> Option<ListSearchReturnShape> {
    // Case 1: impl Stream<Item = String> [+ ...]
    if let Type::ImplTrait(impl_trait) = ty {
        for bound in &impl_trait.bounds {
            if let syn::TypeParamBound::Trait(tb) = bound {
                let last = tb.path.segments.last()?;
                if last.ident == "Stream" {
                    if let PathArguments::AngleBracketed(args) = &last.arguments {
                        for arg in &args.args {
                            if let GenericArgument::AssocType(at) = arg {
                                if at.ident == "Item" && type_is_string(&at.ty) {
                                    return Some(ListSearchReturnShape::ImplStream);
                                }
                            }
                        }
                    }
                }
            }
        }
        return None;
    }

    // Case 2: BoxStream<'_, String> — a path type whose last segment is
    // `BoxStream` with angle-bracketed args including `String` as the item.
    if let Type::Path(tp) = ty {
        let last = tp.path.segments.last()?;
        if last.ident == "BoxStream" {
            if let PathArguments::AngleBracketed(args) = &last.arguments {
                // Look for the `String` generic argument (second position,
                // after the lifetime — though we accept it wherever).
                for arg in &args.args {
                    if let GenericArgument::Type(inner) = arg {
                        if type_is_string(inner) {
                            return Some(ListSearchReturnShape::BoxStream);
                        }
                    }
                }
            }
        }
    }

    None
}

/// True if `ty` is plain `String` (no generics, any path tail of that name).
fn type_is_string(ty: &Type) -> bool {
    if let Type::Path(tp) = ty {
        if let Some(seg) = tp.path.segments.last() {
            return seg.ident == "String" && matches!(seg.arguments, PathArguments::None);
        }
    }
    false
}

/// True if `ty` is exactly `&str` (with any lifetime and no mutability).
fn is_str_ref(ty: &Type) -> bool {
    if let Type::Reference(r) = ty {
        if r.mutability.is_some() {
            return false;
        }
        if let Type::Path(tp) = &*r.elem {
            if let Some(seg) = tp.path.segments.last() {
                return seg.ident == "str" && tp.path.segments.len() == 1;
            }
        }
    }
    false
}

/// Extract `ParsedDeprecation` from an item's attributes by reading
/// `#[deprecated(...)]` and the companion `#[plexus_macros::removed_in("X")]`.
///
/// # Rules (per ticket IR-3)
///
/// | Attributes present | Result |
/// |---|---|
/// | None | `Ok(None)` |
/// | `#[deprecated]` (bare) | `Ok(Some(ParsedDeprecation { since: "", removed_in: "unspecified", message: "" }))` |
/// | `#[deprecated(since = "X", note = "Y")]` | `Ok(Some(ParsedDeprecation { since: "X", removed_in: "unspecified", message: "Y" }))` |
/// | `#[deprecated(since = "X", note = "Y")]` + `#[plexus_macros::removed_in("Z")]` | `Ok(Some(ParsedDeprecation { since: "X", removed_in: "Z", message: "Y" }))` |
/// | `#[deprecated(since = "X", note = "Y", removed_in = "Z")]` | `Ok(Some(ParsedDeprecation { since: "X", removed_in: "Z", message: "Y" }))` — rustc warns about the unknown key; we read it |
/// | `#[plexus_macros::removed_in("Z")]` alone | `Err(..)` — companion without `#[deprecated]` is a compile error |
///
/// The `item_span` argument drives the span of the "companion without
/// `#[deprecated]`" error.
pub fn parse_deprecation_attrs(
    attrs: &[syn::Attribute],
    item_span: proc_macro2::Span,
) -> syn::Result<Option<ParsedDeprecation>> {
    let deprecated_attr = attrs.iter().find(|a| a.path().is_ident("deprecated"));
    let removed_in_attr = attrs.iter().find(|a| {
        let segs = &a.path().segments;
        // Accept `#[removed_in(...)]` (imported directly) or the fully-qualified
        // `#[plexus_macros::removed_in(...)]` form.
        segs.last()
            .map(|s| s.ident == "removed_in")
            .unwrap_or(false)
    });

    // IR-5: the `#[plexus_macros::removed_in(..)]` proc macro, when applied
    // OUTSIDE `#[plexus_macros::activation]` on an impl block, expands FIRST
    // and consumes itself before the activation macro runs. To bridge the
    // gap, that proc macro also emits a `#[doc = "__plexus_removed_in:VERSION"]`
    // sentinel on the item. We scan for the sentinel as an equivalent
    // signal.
    let removed_in_from_sentinel: Option<String> = attrs
        .iter()
        .filter(|a| a.path().is_ident("doc"))
        .filter_map(|a| {
            if let Meta::NameValue(MetaNameValue { value, .. }) = &a.meta {
                if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                    let v = s.value();
                    if let Some(rest) = v.strip_prefix("__plexus_removed_in:") {
                        return Some(rest.to_string());
                    }
                }
            }
            None
        })
        .next();

    if deprecated_attr.is_none() && removed_in_attr.is_none() && removed_in_from_sentinel.is_none() {
        return Ok(None);
    }

    if deprecated_attr.is_none() {
        // companion attr present without its required partner
        let err_span = removed_in_attr
            .map(|a| a.span())
            .unwrap_or_else(proc_macro2::Span::call_site);
        return Err(syn::Error::new(
            err_span,
            "#[plexus_macros::removed_in(\"...\")] requires a companion \
             #[deprecated] attribute on the same item — `removed_in` by itself \
             has no meaning. Add `#[deprecated(since = \"...\", note = \"...\")]` \
             alongside, or remove the `#[removed_in]` attribute.",
        ));
    }

    // Parse the #[deprecated] attribute.
    let mut since = String::new();
    let mut message = String::new();
    let mut removed_in_from_deprecated: Option<String> = None;

    let deprecated_attr = deprecated_attr.unwrap();
    match &deprecated_attr.meta {
        // Bare `#[deprecated]` — no args.
        Meta::Path(_) => {}
        Meta::List(list) => {
            // Parse inner args. Each arg should be `key = "value"`.
            let inner: Punctuated<Meta, Token![,]> =
                list.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)?;
            for meta in inner {
                if let Meta::NameValue(MetaNameValue { path, value, .. }) = meta {
                    if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                        if path.is_ident("since") {
                            since = s.value();
                        } else if path.is_ident("note") {
                            message = s.value();
                        } else if path.is_ident("removed_in") {
                            // rustc emits a warning about this unrecognized key,
                            // but we honor the author's intent by reading it.
                            removed_in_from_deprecated = Some(s.value());
                        }
                        // Any other keys are ignored — rustc will warn separately.
                    }
                }
            }
        }
        Meta::NameValue(_) => {
            // `#[deprecated = "msg"]` is the short form — rustc treats `msg`
            // as the note. We honor the same contract.
            if let Meta::NameValue(MetaNameValue { value, .. }) = &deprecated_attr.meta {
                if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                    message = s.value();
                }
            }
        }
    }

    // Parse the companion `#[plexus_macros::removed_in("X")]` if present.
    let mut removed_in_from_companion: Option<String> = None;
    if let Some(attr) = removed_in_attr {
        match &attr.meta {
            Meta::List(list) => {
                // Expect a single string literal inside the parens.
                let s: syn::LitStr = syn::parse2(list.tokens.clone()).map_err(|_| {
                    syn::Error::new_spanned(
                        &list.tokens,
                        "#[plexus_macros::removed_in(\"...\")] expects a single string \
                         literal argument (e.g. #[plexus_macros::removed_in(\"0.7\")])",
                    )
                })?;
                removed_in_from_companion = Some(s.value());
            }
            Meta::NameValue(MetaNameValue { value, .. }) => {
                // `#[plexus_macros::removed_in = "0.7"]` form.
                if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                    removed_in_from_companion = Some(s.value());
                } else {
                    return Err(syn::Error::new_spanned(
                        value,
                        "#[plexus_macros::removed_in = \"...\"] expects a string literal",
                    ));
                }
            }
            Meta::Path(_) => {
                return Err(syn::Error::new(
                    attr.span(),
                    "#[plexus_macros::removed_in] requires an argument (e.g. \
                     #[plexus_macros::removed_in(\"0.7\")])",
                ));
            }
        }
    }

    // Precedence: companion attribute > sentinel from outer-macro expansion
    // > inside-deprecated key > "unspecified" fallback. The sentinel carries
    // the same author intent as the companion; we prefer the real attribute
    // if both are somehow present.
    let removed_in = removed_in_from_companion
        .or(removed_in_from_sentinel)
        .or(removed_in_from_deprecated)
        .unwrap_or_else(|| DEPRECATION_REMOVED_IN_UNSPECIFIED.to_string());

    let _ = item_span; // reserved for future span-derived diagnostics
    Ok(Some(ParsedDeprecation {
        since,
        removed_in,
        message,
    }))
}

/// Return `true` if this method has a `#[child]` / `#[plexus_macros::child]`
/// attribute. Used by the `#[activation]` driver to split child methods from
/// regular `#[method]` ones before per-method parsing.
pub fn has_child_attr(method: &ImplItemFn) -> bool {
    method.attrs.iter().any(|a| {
        let path = a.path();
        path.segments
            .last()
            .map(|s| s.ident == "child")
            .unwrap_or(false)
    })
}

/// Return `true` if this method has a `#[method]` / `#[hub_method]` /
/// `#[plexus_macros::method]` attribute.
pub fn has_method_attr(method: &ImplItemFn) -> bool {
    method.attrs.iter().any(|a| {
        let last = a.path().segments.last().map(|s| s.ident.to_string());
        matches!(last.as_deref(), Some("method") | Some("hub_method"))
    })
}

/// Information extracted from a #[hub_method] function
pub struct MethodInfo {
    pub fn_name: syn::Ident,
    pub method_name: String,
    pub description: String,
    pub params: Vec<ParamInfo>,
    /// Return type - reserved for future protocol schema generation
    #[allow(dead_code)]
    pub return_type: Type,
    pub stream_item_type: Option<Type>,
    /// Specific enum variants this method can return (empty = all variants)
    pub returns_variants: Vec<String>,
    /// True if method streams multiple events (from #[hub_method(streaming)])
    /// False (default) means method yields a single result
    pub streaming: bool,
    /// Bidirectional channel type (from attribute or inferred from parameter type)
    pub bidirectional: BidirType,
    /// HTTP method for REST endpoints (GET, POST, PUT, DELETE, PATCH)
    /// None defaults to POST
    pub http_method: Option<String>,
    /// True if method requires auth context (detected from `auth: &AuthContext`
    /// or `auth: Option<&AuthContext>` parameter, or `#[from_auth(...)]` use).
    ///
    /// AUTHZ-MACRO-OPTIONAL-AUTH-1: this stays true for both shapes; the
    /// distinction lives in `auth_optional` below. Codegen uses both flags
    /// together to decide between `auth.ok_or_else(...)?` (force) and a
    /// straight `auth` pass-through (optional).
    pub requires_auth: bool,
    /// True iff the method declared `auth: Option<&AuthContext>` (vs.
    /// `auth: &AuthContext`). Meaningful only when `requires_auth` is true.
    ///
    /// AUTHZ-MACRO-OPTIONAL-AUTH-1: when set, the dispatch wrapper passes the
    /// raw `Option<&AuthContext>` through to the handler instead of
    /// unwrapping it.
    pub auth_optional: bool,
    /// Parameters resolved from auth context via `#[from_auth(resolver)]`
    pub auth_resolvers: Vec<AuthResolver>,
    /// Parameters injected from the activation's request struct via `#[activation_param]`
    /// These are stripped from RPC schema and injected at dispatch time from `req.field_name`
    pub activation_params: Vec<ActivationParamInfo>,
    /// Per-method request override. `Some(Skip)` means `request = ()` was set on this method,
    /// which causes the dispatch wrapper to skip activation-level request extraction.
    pub request_override: Option<MethodRequestOverride>,
    /// RED-2: explicit-public flag (mirrored from `HubMethodAttrs::public`).
    /// `true` when `#[plexus_macros::method(public)]` is set; suppresses the
    /// mixed-auth diagnostic for this method.
    ///
    /// R-1: also emitted into the generated `MethodSchema.public` flag.
    pub public: bool,
    /// R-1 (AUTHZ-CORE-2): explicit required scopes (mirrored from
    /// `HubMethodAttrs::scopes`). Emitted into the generated
    /// `MethodSchema.requires_credential` via
    /// `RequiredCredential::from_method_scope(s)` (single) /
    /// `from_method_scopes` (conjunction). Empty = implicit
    /// `<activation>.<method>` rule; nothing is emitted (the registry
    /// resolves implicit scopes at build time, AUTHZ-CORE-4).
    pub scopes: Vec<String>,
    /// IR-3: parsed `#[deprecated(...)]` + `#[plexus_macros::removed_in]` info
    /// folded into the emitted `MethodSchema.deprecation` field.
    pub deprecation: Option<ParsedDeprecation>,
    /// AUTH-3: `target = "param"`, validated against `params`; emitted as
    /// `MethodSchema.target`.
    pub target: Option<String>,
    /// BIDIR-8: `answer_by`, checked; `None` for the default (`caller`),
    /// so the schema of a method without it is unchanged. Emitted as
    /// `MethodSchema.answer_by`.
    pub answer_by: Option<String>,
    /// AUTH-3: the `///` doc comment when an explicit `description = "..."`
    /// replaced it as the description — what it says beyond the
    /// description; emitted as `MethodSchema.long_description`.
    pub long_description: Option<String>,
    /// SYNAPSE-13: `group = "…"`; emitted as `MethodSchema.group`.
    pub group: Option<String>,
    /// SYNAPSE-13: `example(...)`s, checked against `params`; emitted as
    /// `MethodSchema.examples`.
    pub examples: Vec<ParsedExample>,
    /// SYNAPSE-13: `values(...)`, checked against `params`; emitted as
    /// `x-plexus-values` on each param's property.
    pub values: Vec<(String, Vec<String>)>,
    /// AUTH-2/AUTH-3: the method declares `reach: Reach` — the dispatch
    /// hands it `current_reach()` (the gate's answer); stripped from the
    /// RPC params like `auth`.
    pub takes_reach: bool,
}

/// AUTH-3: the doc comment's text beyond `description`: the comment with a
/// leading copy of the description (and the punctuation after it) removed;
/// `None` when nothing is left.
pub(crate) fn long_description_from(doc: &str, description: &str) -> Option<String> {
    let doc = doc.trim();
    let desc = description.trim();
    let rest = if !desc.is_empty() && doc.starts_with(desc) {
        doc[desc.len()..].trim_start_matches(|c: char| c == '.' || c == ':' || c == ';' || c.is_whitespace())
    } else {
        doc
    };
    let rest = rest.trim();
    if rest.is_empty() || rest == desc {
        None
    } else {
        Some(rest.to_string())
    }
}

/// AUTH-2: is `ty` the framework's `Reach` (by its last path segment, as
/// `AuthContext` is recognised)?
fn is_reach_type(ty: &Type) -> bool {
    if let Type::Path(tp) = ty {
        if let Some(last) = tp.path.segments.last() {
            return last.ident == "Reach" && matches!(last.arguments, syn::PathArguments::None);
        }
    }
    false
}

impl MethodInfo {
    /// Extract method info from an impl function with optional hub_method attrs
    pub fn from_fn(method: &ImplItemFn, hub_method_attrs: Option<&HubMethodAttrs>) -> syn::Result<Self> {
        let fn_name = method.sig.ident.clone();
        let method_name = hub_method_attrs
            .and_then(|a| a.name.clone())
            .unwrap_or_else(|| fn_name.to_string());

        // Resolve description with this precedence:
        //   1. Explicit `description = "..."` on #[plexus_macros::method(...)] wins.
        //   2. Otherwise fall back to `///` doc comments on the method, joined with '\n'
        //      and with common leading whitespace stripped (same rule as `cargo doc`).
        //   3. If neither is present, description is the empty string.
        // AUTH-3: when an explicit description replaces the doc comment, the
        // comment is kept as `long_description` (it used to be dropped).
        let (description, long_description) = match hub_method_attrs.and_then(|a| a.description.clone()) {
            Some(explicit) => {
                let long = extract_doc_description(&method.attrs)
                    .and_then(|doc| long_description_from(&doc, &explicit));
                (explicit, long)
            }
            None => (extract_doc_description(&method.attrs).unwrap_or_default(), None),
        };

        // Get param docs and returns_variants from hub_method attrs
        let param_docs = hub_method_attrs
            .map(|a| &a.param_docs)
            .cloned()
            .unwrap_or_default();
        let returns_variants = hub_method_attrs
            .map(|a| a.returns_variants.clone())
            .unwrap_or_default();
        let streaming = hub_method_attrs
            .map(|a| a.streaming)
            .unwrap_or(false);
        let http_method = hub_method_attrs
            .and_then(|a| a.http_method.clone());
        let request_override = hub_method_attrs
            .and_then(|a| a.request_override.clone());

        // Get bidirectional from attribute (may be overridden by parameter type inference)
        let mut bidirectional = hub_method_attrs
            .map(|a| a.bidirectional.clone())
            .unwrap_or(BidirType::None);

        // Track if method requires auth
        let mut requires_auth = false;
        // AUTHZ-MACRO-OPTIONAL-AUTH-1: track whether the user wrote
        // `auth: Option<&AuthContext>` (optional) vs `auth: &AuthContext`
        // (force-required). Defaults to false; gets flipped on only if the
        // optional shape is detected below.
        let mut auth_optional = false;
        let mut auth_resolvers: Vec<AuthResolver> = Vec::new();
        let mut activation_params: Vec<ActivationParamInfo> = Vec::new();

        // Extract parameters after &self
        let mut params = Vec::new();
        // AUTH-2: `reach: Reach`, and where it sits among the typed args.
        let mut takes_reach = false;
        let mut typed_index = 0usize;
        let mut auth_at: Option<usize> = None;
        for arg in &method.sig.inputs {
            if let FnArg::Typed(pat_type) = arg {
                let this_index = typed_index;
                typed_index += 1;
                if let Pat::Ident(ident) = &*pat_type.pat {
                    let name = ident.ident.clone();
                    let name_str = name.to_string();

                    // AUTH-2: `reach: Reach` is provided by the framework (the
                    // gate's answer). It must come first, or right after
                    // `auth`, because the dispatch passes the framework's
                    // arguments ahead of the RPC params.
                    if name_str == "reach" && is_reach_type(&pat_type.ty) {
                        let first = this_index == 0 || auth_at == Some(this_index - 1);
                        if !first {
                            return Err(syn::Error::new_spanned(
                                pat_type,
                                "`reach: Reach` must be the first parameter after `&self`, \
                                 or come right after `auth`",
                            ));
                        }
                        takes_reach = true;
                        continue;
                    }

                    // Check for #[activation_param] attribute first
                    // e.g. #[activation_param] auth_token: String
                    if let Some(err) = check_activation_param_attr(&pat_type.attrs)? {
                        return Err(err);
                    }
                    if has_activation_param_attr(&pat_type.attrs) {
                        activation_params.push(ActivationParamInfo {
                            param_name: name,
                            ty: (*pat_type.ty).clone(),
                        });
                        // Don't include in RPC params or schema
                        continue;
                    }

                    // Check for #[from_auth(resolver_expr)] attribute
                    // e.g. #[from_auth(self.db.validate_user)] user: ValidUser
                    if let Some(resolver) = extract_from_auth_attr(&pat_type.attrs) {
                        requires_auth = true;
                        auth_resolvers.push(AuthResolver {
                            param_name: name,
                            resolver_expr: resolver,
                        });
                        // Don't include in RPC params
                        continue;
                    }

                    // Check if this is an auth context parameter
                    // Detect auth: &AuthContext or auth: Option<&AuthContext>
                    if name_str == "auth" {
                        if let Some(shape) = classify_auth_context_type(&pat_type.ty) {
                            requires_auth = true;
                            // AUTHZ-MACRO-OPTIONAL-AUTH-1: remember which shape
                            // the user wrote so codegen emits the right
                            // unwrap/pass-through behavior.
                            auth_optional = matches!(shape, AuthParamShape::Optional);
                            auth_at = Some(this_index);
                            // Don't include auth in params (it's provided by framework)
                            continue;
                        }
                    }

                    // Check if this is a bidirectional context parameter
                    // Detect ctx: &BidirChannel<Req, Resp> or ctx: &StandardBidirChannel
                    if name_str == "ctx" || name_str == "context" {
                        if let Some(bidir_types) = extract_bidir_channel_types(&pat_type.ty) {
                            // Infer bidirectional type from parameter
                            bidirectional = bidir_types;
                            // Don't include ctx in params (it's provided by framework)
                            continue;
                        }
                    }

                    // Param description precedence:
                    //   1. Explicit `params(name = "...")` on the method attribute wins.
                    //   2. Otherwise fall back to `///` doc comments on the parameter
                    //      itself (e.g. `async fn foo(&self, /// the input message
                    //      message: String) -> ...`). Mirrors the function-level
                    //      doc-fallback already implemented above.
                    //   3. If neither is present, description is `None`.
                    let description = param_docs
                        .get(&name_str)
                        .cloned()
                        .or_else(|| extract_doc_description(&pat_type.attrs));
                    // IR-5: parse `#[deprecated(...)]` + optional
                    // `#[plexus_macros::removed_in("...")]` on the parameter.
                    let deprecation =
                        parse_deprecation_attrs(&pat_type.attrs, pat_type.span())?;
                    params.push(ParamInfo {
                        name,
                        ty: (*pat_type.ty).clone(),
                        description,
                        deprecation,
                    });
                }
            }
        }

        // Extract return type
        let return_type = match &method.sig.output {
            ReturnType::Default => {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "hub_method requires a return type",
                ))
            }
            ReturnType::Type(_, ty) => (**ty).clone(),
        };

        let stream_item_type = extract_stream_item_type(&return_type);

        // Check for PlexusStream return type - must use streaming pattern instead
        if is_result_plexus_stream(&return_type) {
            return Err(syn::Error::new_spanned(
                &method.sig.output,
                format!(
                    "Method `{}` returns Result<PlexusStream, _> which bypasses schema generation. \
                    Use the streaming pattern instead:\n\
                    - Return `impl Stream<Item = YourEvent>` from the method\n\
                    - Forward PlexusStreamItem variants into your event enum\n\
                    - Add `streaming` attribute if the method yields multiple events\n\
                    See plexus.call implementation for an example.",
                    fn_name
                ),
            ));
        }

        // IR-3: extract deprecation info from the method's attributes (before
        // codegen strips the `#[plexus_macros::removed_in]` companion).
        let deprecation = parse_deprecation_attrs(&method.attrs, method.sig.span())?;

        // RED-2: capture the `public` flag from the per-method attribute,
        // if present. Default false.
        let public = hub_method_attrs.map(|a| a.public).unwrap_or(false);

        // R-1: capture the explicit `scope = "..."` literals (already
        // grammar-validated at attribute-parse time).
        let scopes = hub_method_attrs
            .map(|a| a.scopes.clone())
            .unwrap_or_default();

        // AUTH-3: `target` must name one of the RPC params.
        let target = match hub_method_attrs.and_then(|a| a.target.as_ref()) {
            None => None,
            Some(lit) => {
                let wanted = lit.value();
                if !params.iter().any(|p: &ParamInfo| p.name == wanted.as_str()) {
                    let known: Vec<String> = params.iter().map(|p| p.name.to_string()).collect();
                    return Err(syn::Error::new(
                        lit.span(),
                        format!(
                            "target = \"{}\" names no parameter of `{}`; its parameters are: {}",
                            wanted,
                            fn_name,
                            if known.is_empty() { "(none)".to_string() } else { known.join(", ") },
                        ),
                    ));
                }
                Some(wanted)
            }
        };

        // BIDIR-8: `answer_by` is one of three spellings (plexus-auth-core's
        // `Answerer::parse` reads the same; the default is left unset).
        let answer_by = match hub_method_attrs.and_then(|a| a.answer_by.as_ref()) {
            None => None,
            Some(lit) => match answer_by_declared(&lit.value()) {
                Ok(declared) => declared,
                Err(()) => {
                    return Err(syn::Error::new(
                        lit.span(),
                        format!(
                            "answer_by = \"{}\" on `{}`: who may answer is one of `caller` (the default), \
                             `person`, or `grant:<activation.method>`",
                            lit.value(),
                            fn_name,
                        ),
                    ))
                }
            },
        };

        // SYNAPSE-13: values and examples name only the method's params.
        let known_params = || -> String {
            let known: Vec<String> = params.iter().map(|p: &ParamInfo| p.name.to_string()).collect();
            if known.is_empty() { "(none)".to_string() } else { known.join(", ") }
        };
        let mut values: Vec<(String, Vec<String>)> = Vec::new();
        for (ident, vals) in hub_method_attrs.map(|a| a.values.clone()).unwrap_or_default() {
            if !params.iter().any(|p: &ParamInfo| p.name == ident) {
                return Err(syn::Error::new(
                    ident.span(),
                    format!(
                        "values(...) names `{}`, no parameter of `{}`; its parameters are: {}",
                        ident, fn_name, known_params(),
                    ),
                ));
            }
            values.push((ident.to_string(), vals));
        }
        let examples = hub_method_attrs.map(|a| a.examples.clone()).unwrap_or_default();
        for ex in &examples {
            for key in &ex.keys {
                if !params.iter().any(|p: &ParamInfo| p.name == key.as_str()) {
                    return Err(syn::Error::new(
                        ex.span,
                        format!(
                            "example params name `{}`, no parameter of `{}`; its parameters are: {}",
                            key, fn_name, known_params(),
                        ),
                    ));
                }
            }
        }
        let group = hub_method_attrs.and_then(|a| a.group.clone());

        Ok(MethodInfo {
            fn_name,
            method_name,
            description,
            params,
            return_type,
            stream_item_type,
            returns_variants,
            streaming,
            bidirectional,
            http_method,
            requires_auth,
            auth_optional,
            auth_resolvers,
            activation_params,
            request_override,
            public,
            scopes,
            deprecation,
            target,
            answer_by,
            long_description,
            group,
            examples,
            values,
            takes_reach,
        })
    }
}

/// Convert a `syn::Expr` to a `syn::Type` for `request = Type` parsing.
///
/// Handles:
/// - `Expr::Path` (e.g. `TestRequest`, `my_mod::MyRequest`) → `Type::Path`
/// - `Expr::Tuple` with 0 elements (e.g. `()`) → `Type::Tuple` (unit type)
fn expr_to_type(expr: &Expr) -> Option<syn::Type> {
    match expr {
        Expr::Path(ExprPath { attrs: _, qself, path }) => {
            Some(syn::Type::Path(syn::TypePath {
                qself: qself.as_ref().map(|qs| syn::QSelf {
                    lt_token: qs.lt_token,
                    ty: qs.ty.clone(),
                    position: qs.position,
                    as_token: qs.as_token,
                    gt_token: qs.gt_token,
                }),
                path: path.clone(),
            }))
        }
        Expr::Tuple(ExprTuple { elems, .. }) if elems.is_empty() => {
            // `()` — unit type used for `request = ()` override
            Some(syn::parse_quote! { () })
        }
        _ => None,
    }
}

/// Check if a parameter has the `#[activation_param]` attribute.
/// Returns `true` if the bare `#[activation_param]` attribute is present.
fn has_activation_param_attr(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| attr.path().is_ident("activation_param"))
}

/// Validate that `#[activation_param]` takes no arguments.
/// Returns `Some(Err(...))` if the attribute is present but has arguments,
/// `None` if the attribute is absent or is correctly bare.
fn check_activation_param_attr(attrs: &[syn::Attribute]) -> syn::Result<Option<syn::Error>> {
    for attr in attrs {
        if attr.path().is_ident("activation_param") {
            // Make sure it's a bare path attribute, not #[activation_param(...)]
            if let syn::Meta::List(list) = &attr.meta {
                return Ok(Some(syn::Error::new_spanned(
                    list,
                    "activation_param takes no arguments — extraction is defined on the request struct, not the method",
                )));
            }
        }
    }
    Ok(None)
}

/// Extract the resolver expression from a `#[from_auth(expr)]` attribute.
/// Returns `Some(expr)` if the attribute is found, `None` otherwise.
///
/// Supports:
/// - `#[from_auth(self.db.validate_user)]`
/// - `#[from_auth(self.require_admin)]`
/// - Any arbitrary expression that will be called with `&AuthContext`
fn extract_from_auth_attr(attrs: &[syn::Attribute]) -> Option<syn::Expr> {
    for attr in attrs {
        if attr.path().is_ident("from_auth") {
            // Parse the inner expression from #[from_auth(expr)]
            let expr: syn::Expr = attr.parse_args().ok()?;
            return Some(expr);
        }
    }
    None
}

/// Classify an auth-context parameter type as either force-required
/// (`&AuthContext`) or optional (`Option<&AuthContext>`).
///
/// Returns `None` if `ty` is not an auth-context shape we recognize.
///
/// AUTHZ-MACRO-OPTIONAL-AUTH-1: split out from `is_auth_context_type` so that
/// downstream codegen can emit `auth.ok_or_else(...)?` for force-required
/// handlers and a plain `auth` pass-through for optional handlers.
pub(crate) fn classify_auth_context_type(ty: &Type) -> Option<AuthParamShape> {
    // Handle &AuthContext
    if let Type::Reference(type_ref) = ty {
        if let Type::Path(type_path) = &*type_ref.elem {
            if let Some(last_segment) = type_path.path.segments.last() {
                if last_segment.ident == "AuthContext" {
                    return Some(AuthParamShape::Required);
                }
            }
        }
    }

    // Handle Option<&AuthContext>
    if let Type::Path(type_path) = ty {
        if let Some(last_segment) = type_path.path.segments.last() {
            if last_segment.ident == "Option" {
                if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
                    if let Some(GenericArgument::Type(inner_ty)) = args.args.first() {
                        // Option<&AuthContext> — inner must be the reference form
                        if classify_auth_context_type(inner_ty)
                            == Some(AuthParamShape::Required)
                        {
                            return Some(AuthParamShape::Optional);
                        }
                    }
                }
            }
        }
    }

    None
}

/// Shape of the `auth: ...` parameter on a hub method.
///
/// `Required` means the user wrote `auth: &AuthContext` and missing context
/// should produce an `Unauthenticated` error. `Optional` means the user
/// wrote `auth: Option<&AuthContext>` and missing context should be passed
/// through as `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthParamShape {
    Required,
    Optional,
}

/// Extract BidirChannel type parameters from a type like &BidirChannel<Req, Resp>
/// Handles various forms:
/// - &BidirChannel<Req, Resp>
/// - &Arc<BidirChannel<Req, Resp>>
/// - &StandardBidirChannel
/// - &Arc<StandardBidirChannel>
/// Returns BidirType::Custom if custom types found, BidirType::Standard if StandardBidirChannel
fn extract_bidir_channel_types(ty: &Type) -> Option<BidirType> {
    // Handle &T
    let inner_ty = if let Type::Reference(type_ref) = ty {
        &*type_ref.elem
    } else {
        ty
    };

    if let Type::Path(type_path) = inner_ty {
        let last_segment = type_path.path.segments.last()?;

        // Check for Arc<...> wrapper
        if last_segment.ident == "Arc" {
            if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
                if let Some(GenericArgument::Type(inner)) = args.args.first() {
                    // Recursively check the inner type
                    return extract_bidir_from_path(inner);
                }
            }
            return None;
        }

        // Check direct type (no Arc)
        return extract_bidir_from_path(inner_ty);
    }

    None
}

/// Extract BidirType from a path type (BidirChannel or StandardBidirChannel)
fn extract_bidir_from_path(ty: &Type) -> Option<BidirType> {
    if let Type::Path(type_path) = ty {
        let last_segment = type_path.path.segments.last()?;

        // Check for StandardBidirChannel (type alias)
        if last_segment.ident == "StandardBidirChannel" {
            return Some(BidirType::Standard);
        }

        // Check for BidirChannel<Req, Resp>
        if last_segment.ident == "BidirChannel" {
            if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
                let args_vec: Vec<_> = args.args.iter().collect();
                if args_vec.len() == 2 {
                    // Extract Req and Resp type names
                    if let (GenericArgument::Type(req_ty), GenericArgument::Type(resp_ty)) =
                        (args_vec[0], args_vec[1])
                    {
                        let req_name = type_to_string(req_ty);
                        let resp_name = type_to_string(resp_ty);

                        // Check if it's StandardRequest/StandardResponse
                        if req_name == "StandardRequest" && resp_name == "StandardResponse" {
                            return Some(BidirType::Standard);
                        }

                        return Some(BidirType::Custom {
                            request: req_name,
                            response: resp_name,
                        });
                    }
                }
            }
        }
    }

    None
}

/// Convert a Type to its string representation (simple path types only)
fn type_to_string(ty: &Type) -> String {
    if let Type::Path(type_path) = ty {
        type_path
            .path
            .segments
            .iter()
            .map(|s| s.ident.to_string())
            .collect::<Vec<_>>()
            .join("::")
    } else {
        format!("{:?}", ty)
    }
}

/// Extract Item type from `impl Stream<Item = T>`
pub(crate) fn extract_stream_item_type(ty: &Type) -> Option<Type> {
    if let Type::ImplTrait(impl_trait) = ty {
        for bound in &impl_trait.bounds {
            if let syn::TypeParamBound::Trait(trait_bound) = bound {
                let last_segment = trait_bound.path.segments.last()?;
                if last_segment.ident == "Stream" {
                    if let PathArguments::AngleBracketed(args) = &last_segment.arguments {
                        for arg in &args.args {
                            if let GenericArgument::AssocType(assoc) = arg {
                                if assoc.ident == "Item" {
                                    return Some(assoc.ty.clone());
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    None
}

/// Extract the description from `///` doc comment attributes on an item.
///
/// In Rust's AST both `///` doc-comment sugar and the raw `#[doc = "..."]` form appear
/// as `#[doc = "..."]` attributes, so we read them uniformly here.
///
/// Returns:
/// - `Some(String)` with lines joined by `\n` and common leading whitespace stripped,
///   matching the standard `cargo doc` rule, when at least one `#[doc = "..."]`
///   attribute is present.
/// - `None` when no doc-comment attributes are present on the item. Callers should
///   treat this as "no default available" and fall back to whatever behavior the
///   absence of a description should yield (typically the empty string).
pub(crate) fn extract_doc_description(attrs: &[syn::Attribute]) -> Option<String> {
    let mut raw_lines: Vec<String> = Vec::new();
    for attr in attrs {
        if attr.path().is_ident("doc") {
            if let Meta::NameValue(MetaNameValue { value, .. }) = &attr.meta {
                if let Expr::Lit(ExprLit { lit: Lit::Str(s), .. }) = value {
                    // `///` sugar prepends a single leading space to the literal
                    // (e.g. `/// Foo` becomes `#[doc = " Foo"]`). The common-leading-
                    // whitespace strip below removes that uniformly. For multi-line
                    // raw `#[doc = "a\nb"]` forms, split on '\n' and treat each line
                    // independently so the strip rule applies per line, not per attr.
                    for line in s.value().split('\n') {
                        raw_lines.push(line.to_string());
                    }
                }
            }
        }
    }
    if raw_lines.is_empty() {
        return None;
    }
    Some(strip_common_leading_whitespace(&raw_lines))
}

/// Strip the common leading-whitespace prefix from every line (the `cargo doc` rule).
///
/// - Empty / whitespace-only lines are ignored when computing the common prefix and
///   emitted as empty strings in the output.
/// - The minimum count of leading whitespace characters across all non-empty lines
///   is the common prefix length; that many chars are removed from each non-empty line.
fn strip_common_leading_whitespace(lines: &[String]) -> String {
    let min_indent = lines
        .iter()
        .filter(|l| !l.trim().is_empty())
        .map(|l| l.chars().take_while(|c| c.is_whitespace()).count())
        .min()
        .unwrap_or(0);
    lines
        .iter()
        .map(|l| {
            if l.trim().is_empty() {
                String::new()
            } else {
                // Skip the first `min_indent` chars (all whitespace by construction).
                l.chars().skip(min_indent).collect::<String>()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Check if return type looks like Result<PlexusStream, _>
/// This is now rejected - methods should use the streaming pattern instead
fn is_result_plexus_stream(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            if segment.ident == "Result" {
                if let PathArguments::AngleBracketed(args) = &segment.arguments {
                    if let Some(GenericArgument::Type(first_type)) = args.args.first() {
                        // Check if first type arg is PlexusStream
                        if let Type::Path(inner_path) = first_type {
                            if let Some(inner_seg) = inner_path.path.segments.last() {
                                return inner_seg.ident == "PlexusStream";
                            }
                        }
                    }
                }
            }
        }
    }
    false
}


/// BIDIR-8: an `answer_by` declaration, as plexus-auth-core's
/// `Answerer::parse` reads it — `Ok(None)` for the default (`caller`),
/// `Ok(Some(spelling))` for `person` / `grant:<activation.method>`, `Err` for
/// anything else.
fn answer_by_declared(text: &str) -> Result<Option<String>, ()> {
    match text.trim() {
        "caller" => Ok(None),
        "person" => Ok(Some("person".into())),
        t => match t.strip_prefix("grant:") {
            Some(g) if g.contains('.') && !g.contains(char::is_whitespace) => Ok(Some(format!("grant:{g}"))),
            _ => Err(()),
        },
    }
}

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

    /// Drives `parse_deprecation_attrs` on an inline `removed_in` key inside
    /// `#[deprecated(...)]`. Stable rustc emits `E0541` for this form, so
    /// the happy-path integration test in `tests/ir3_role_and_deprecation_tests.rs`
    /// cannot exercise it end-to-end. This unit test runs the parser directly
    /// on a synthetic attribute — no rustc attribute-check is involved.
    #[test]
    fn parse_deprecation_reads_inline_removed_in_key() {
        let attrs: Vec<syn::Attribute> =
            vec![parse_quote! { #[deprecated(since = "0.5", note = "use bar", removed_in = "0.7")] }];
        let parsed = parse_deprecation_attrs(&attrs, Span::call_site())
            .expect("parser accepts unknown key")
            .expect("produces Some for a #[deprecated] attr");
        assert_eq!(parsed.since, "0.5");
        assert_eq!(parsed.removed_in, "0.7");
        assert_eq!(parsed.message, "use bar");
    }

    /// The companion `#[plexus_macros::removed_in(...)]` takes precedence over
    /// a `removed_in` key written inside `#[deprecated(...)]`.
    #[test]
    fn parse_deprecation_companion_overrides_inline_key() {
        let attrs: Vec<syn::Attribute> = vec![
            parse_quote! { #[deprecated(since = "0.5", note = "n", removed_in = "0.7")] },
            parse_quote! { #[plexus_macros::removed_in("0.9")] },
        ];
        let parsed = parse_deprecation_attrs(&attrs, Span::call_site()).unwrap().unwrap();
        assert_eq!(parsed.removed_in, "0.9");
    }

    /// `#[deprecated]` without `removed_in` (neither inline nor companion)
    /// yields the documented fallback string `"unspecified"`.
    #[test]
    fn parse_deprecation_fallback_is_unspecified() {
        let attrs: Vec<syn::Attribute> =
            vec![parse_quote! { #[deprecated(since = "0.5", note = "n")] }];
        let parsed = parse_deprecation_attrs(&attrs, Span::call_site()).unwrap().unwrap();
        assert_eq!(parsed.removed_in, DEPRECATION_REMOVED_IN_UNSPECIFIED);
    }

    /// Bare `#[deprecated]` (no args) yields empty-string defaults per the
    /// ticket's "Tests to add" item 3 variant.
    #[test]
    fn parse_deprecation_bare_emits_empty_since_and_message() {
        let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[deprecated] }];
        let parsed = parse_deprecation_attrs(&attrs, Span::call_site()).unwrap().unwrap();
        assert_eq!(parsed.since, "");
        assert_eq!(parsed.message, "");
        assert_eq!(parsed.removed_in, DEPRECATION_REMOVED_IN_UNSPECIFIED);
    }

    /// Companion attr without a paired `#[deprecated]` is a compile error.
    #[test]
    fn parse_deprecation_companion_without_deprecated_errors() {
        let attrs: Vec<syn::Attribute> =
            vec![parse_quote! { #[plexus_macros::removed_in("0.6")] }];
        let err = parse_deprecation_attrs(&attrs, Span::call_site())
            .expect_err("removed_in alone must error");
        let msg = err.to_string();
        assert!(
            msg.contains("#[deprecated]"),
            "error must name #[deprecated] as required companion; got: {}",
            msg
        );
    }

    /// No deprecation attrs → `Ok(None)`.
    #[test]
    fn parse_deprecation_no_attrs_yields_none() {
        let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[doc = "just a comment"] }];
        let parsed = parse_deprecation_attrs(&attrs, Span::call_site()).unwrap();
        assert!(parsed.is_none());
    }

    /// AUTHZ-MACRO-PARAM-DOC-1: `///` doc comment on a parameter is picked up
    /// as the param description when no explicit `params(name = "...")` entry
    /// exists on the method attribute.
    #[test]
    fn param_doc_comment_falls_back_when_params_attr_omits_entry() {
        let method: ImplItemFn = parse_quote! {
            async fn echo(
                &self,
                /// The message to echo back
                message: String,
            ) -> impl Stream<Item = MyEvent> + Send + 'static {
                stream! { yield MyEvent::Echo { message } }
            }
        };
        let info = MethodInfo::from_fn(&method, None).expect("parses cleanly");
        let param = info.params.iter().find(|p| p.name == "message").unwrap();
        assert_eq!(
            param.description.as_deref(),
            Some("The message to echo back"),
            "param doc comment should fall back into the description when no params(...) entry exists"
        );
    }

    /// AUTHZ-MACRO-PARAM-DOC-1: explicit `params(name = "...")` on the method
    /// attribute wins over a `///` doc comment on the parameter.
    #[test]
    fn explicit_params_attr_wins_over_param_doc_comment() {
        let method: ImplItemFn = parse_quote! {
            async fn echo(
                &self,
                /// IGNORED — explicit attr wins
                message: String,
            ) -> impl Stream<Item = MyEvent> + Send + 'static {
                stream! { yield MyEvent::Echo { message } }
            }
        };
        let attrs = HubMethodAttrs {
            name: None,
            description: None,
            param_docs: {
                let mut m = HashMap::new();
                m.insert("message".to_string(), "explicit description".to_string());
                m
            },
            returns_variants: vec![],
            streaming: false,
            bidirectional: BidirType::None,
            http_method: None,
            request_override: None,
            public: false,
            scopes: vec![],
            target: None,
            answer_by: None,
            group: None,
            examples: vec![],
            values: vec![],
        };
        let info = MethodInfo::from_fn(&method, Some(&attrs)).expect("parses cleanly");
        let param = info.params.iter().find(|p| p.name == "message").unwrap();
        assert_eq!(
            param.description.as_deref(),
            Some("explicit description"),
            "explicit params(...) entry must win over /// doc comment on the param"
        );
    }

    /// AUTHZ-MACRO-PARAM-DOC-1: parameter with neither explicit attr nor doc
    /// comment yields `description: None`.
    #[test]
    fn param_with_no_description_yields_none() {
        let method: ImplItemFn = parse_quote! {
            async fn echo(
                &self,
                message: String,
            ) -> impl Stream<Item = MyEvent> + Send + 'static {
                stream! { yield MyEvent::Echo { message } }
            }
        };
        let info = MethodInfo::from_fn(&method, None).expect("parses cleanly");
        let param = info.params.iter().find(|p| p.name == "message").unwrap();
        assert!(
            param.description.is_none(),
            "no description anywhere should yield None, got: {:?}",
            param.description
        );
    }

    /// R-1 (AUTHZ-CORE-2 AC #3): the compile-time scope-grammar check
    /// mirrors AUTHZ-CORE-4's `Scope::try_new` grammar.
    #[test]
    fn scope_literal_grammar_accepts_and_rejects() {
        // Accepted forms.
        for ok in [
            "facet.write",
            "cone.send_message",
            "a",
            "a.b.c",
            "a1.b_2",
            "cone.*",
            "a.b.*",
            "*",
        ] {
            assert!(
                validate_scope_literal(ok).is_ok(),
                "`{ok}` should satisfy the scope grammar"
            );
        }
        // Rejected forms.
        for bad in [
            "",
            "INVALID-CHARS",
            "Facet.write",
            "facet..write",
            ".facet",
            "facet.",
            "facet write",
            "1facet.write",
            "*.facet",      // wildcard must be trailing
            "facet.*.read", // wildcard must be trailing
            "**",
            "facet.wr*te",
        ] {
            assert!(
                validate_scope_literal(bad).is_err(),
                "`{bad}` should violate the scope grammar"
            );
        }
    }

    /// R-1: `scope = "..."` parses into `HubMethodAttrs::scopes` in
    /// declaration order; `public` + `scope` is rejected at parse time.
    #[test]
    fn method_attrs_parse_scopes_and_reject_public_scope_conflict() {
        let attrs: HubMethodAttrs =
            syn::parse_str("scope = \"x.y\", scope = \"x.z\"").expect("parses cleanly");
        assert_eq!(attrs.scopes, vec!["x.y".to_string(), "x.z".to_string()]);
        assert!(!attrs.public);

        let err = match syn::parse_str::<HubMethodAttrs>("public, scope = \"x.y\"") {
            Ok(_) => panic!("public + scope must be a parse error"),
            Err(e) => e,
        };
        assert!(
            err.to_string().contains("a public method has no required scope"),
            "unexpected error: {err}"
        );

        let err = match syn::parse_str::<HubMethodAttrs>("scope = \"BAD CHARS\"") {
            Ok(_) => panic!("invalid literal must be a parse error"),
            Err(e) => e,
        };
        assert!(
            err.to_string().contains("invalid scope literal"),
            "unexpected error: {err}"
        );
    }
}