plexus-macros 0.11.1

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
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
//! Attribute parsing for Plexus RPC macros

use std::collections::HashMap;
use quote::ToTokens;
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,
}

/// ASK-1: `bidirectional` is gone — the in-call question it declared, with
/// nothing in its place.
pub(crate) const BIDIRECTIONAL_REMOVED: &str =
    "`bidirectional` is removed (ASK-1): a method no longer asks its caller mid-call, and \
     Plexus has no in-call or protocol-wide confirmation. A method that needs its caller's \
     yes builds it from its own parameters (a `dry_run`, a plan id).";

/// 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),
}

/// RETURNS-36 (the owner, review #2): `#[method(streaming)]` is a deprecated
/// no-op where the signature agrees (a stream form), so a file that builds on
/// 0.7.0 builds on 0.8 unchanged; on a one-item form it is an error.
pub(crate) const STREAMING_DEPRECATED: &str =
    "`streaming` is deprecated: cardinality comes from the return type, which \
     already says this method yields many items. Remove `streaming`.";

/// RETURNS-8: `#[method(returns(..))]` is gone — it filtered the variants of
/// a shared event enum, and a method's own return type now says exactly what
/// it yields (RETURNS-1 decision 16).
pub(crate) const RETURNS_REMOVED: &str =
    "`returns(..)` is removed: a method's return type is its contract. Instead of \
     filtering a shared event enum's variants, give each method its own return type — \
     e.g. `-> Result<Ticket, GetError>` or `-> impl Stream<Item = ListItem>`.";

/// Parsed attributes for #[hub_method]
pub struct HubMethodAttrs {
    pub name: Option<String>,
    /// NEST-16: `uses("shop.items", …)` — the parent's methods this method
    /// calls, said by hand: added to what is inferred, and what lets the
    /// injected `parent` leave a call chain (passed on, stored, cloned).
    pub uses: Vec<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>,
    /// 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>,
    /// RETURNS-36: where `streaming` was written, if it was — a deprecated
    /// no-op, checked against the signature in [`MethodInfo::from_fn`].
    pub streaming: Option<proc_macro2::Span>,
    /// 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>,
    /// BIDIR-6: `input_window = N` and the opt-in ceilings of a method with
    /// an `Input`.
    pub input_ceiling: InputCeilingAttrs,
    /// 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>)>,
    /// KEEL-31: `everywhere` — the method acts on the whole service; the
    /// gate admits it only where its grant is held on `*`. Emitted as
    /// `MethodSchema.everywhere`.
    pub everywhere: bool,
}

/// BIDIR-6: what `#[method(...)]` says of a method's input half. `window`
/// is the credit it grants; the rest are limits it opts into.
#[derive(Debug, Clone, Default)]
pub struct InputCeilingAttrs {
    pub window: Option<syn::LitInt>,
    pub max_items: Option<syn::LitInt>,
    pub max_bytes: Option<syn::LitInt>,
    pub max_buffered: Option<syn::LitInt>,
}

impl InputCeilingAttrs {
    fn first(&self) -> Option<(&'static str, &syn::LitInt)> {
        [("input_window", &self.window), ("input_max_items", &self.max_items), ("input_max_bytes", &self.max_bytes), ("input_max_buffered", &self.max_buffered)]
            .into_iter()
            .find_map(|(n, v)| v.as_ref().map(|v| (n, v)))
    }
}

/// BIDIR-6: a method's `Input<T>` parameter.
#[derive(Debug, Clone)]
pub struct InputInfo {
    pub name: syn::Ident,
    /// `T`.
    pub item: Type,
    /// Where it sits among the RPC params.
    pub at: usize,
    pub description: Option<String>,
    pub ceiling: InputCeilingAttrs,
}

/// BIDIR-6: `T` of `Input<T>`, written by its last path segment, as
/// `AuthContext` and `Reach` are recognised.
fn input_item_type(ty: &Type) -> Option<Type> {
    let Type::Path(tp) = ty else { return None };
    let last = tp.path.segments.last()?;
    if last.ident != "Input" {
        return None;
    }
    let PathArguments::AngleBracketed(args) = &last.arguments else { return None };
    match args.args.iter().collect::<Vec<_>>().as_slice() {
        [GenericArgument::Type(item)] => Some(item.clone()),
        _ => None,
    }
}

/// BIDIR-6: does `Input<…>` appear anywhere in these tokens?
fn names_input(tokens: proc_macro2::TokenStream) -> bool {
    use proc_macro2::TokenTree;
    let tokens: Vec<TokenTree> = tokens.into_iter().collect();
    tokens.iter().enumerate().any(|(i, t)| match t {
        TokenTree::Ident(id) => id == "Input" && matches!(tokens.get(i + 1), Some(TokenTree::Punct(p)) if p.as_char() == '<'),
        TokenTree::Group(g) => names_input(g.stream()),
        _ => false,
    })
}

/// 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(())
}

/// KEEL-31: every word `#[plexus_macros::method(...)]` takes.
const METHOD_WORDS: &[&str] = &[
    "public", "everywhere", "streaming", "name", "description", "http_method", "target", "answer_by", "group",
    "scope", "request", "input_window", "input_max_items", "input_max_bytes", "input_max_buffered", "uses",
    "params", "example", "examples", "values",
];

/// KEEL-31: every word `#[plexus_macros::activation(...)]` takes.
const ACTIVATION_WORDS: &[&str] = &[
    "namespace", "trait", "version", "description", "long_description", "crate_path", "plugin_id", "namespace_fn",
    "server_cfg", "auth", "request", "parent", "methods", "served", "resolve_handle", "hub", "client",
    "typed_params", "children", "roles", "required",
];

/// KEEL-31: a word an attribute does not take is a compile error naming it
/// and the words it does take — never dropped, as an older macro dropped
/// `everywhere`.
fn unknown_word(path: &syn::Path, attr: &str, known: &[&str]) -> syn::Error {
    let word = path.get_ident().map(|i| i.to_string()).unwrap_or_else(|| quote::quote!(#path).to_string());
    let word = if word == TRAIT_KEY { "trait".to_string() } else { word };
    syn::Error::new_spanned(path, format!("unknown word `{word}` in {attr}; it takes: {}", known.join(", ")))
}

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 http_method = None;
        let mut request_override: Option<MethodRequestOverride> = None;
        let mut public = false;
        let mut streaming: Option<proc_macro2::Span> = None;
        // 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;
        // BIDIR-6: `input_window = N` and the opt-in ceilings.
        let mut input_ceiling = InputCeilingAttrs::default();
        // 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();
        let mut uses: Vec<String> = Vec::new();
        // KEEL-31: `everywhere`.
        let mut everywhere: Option<proc_macro2::Span> = None;

        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\
                                 See plexus.call implementation for an example.",
                            ));
                        } else if path.is_ident("streaming") {
                            // RETURNS-8: cardinality is read from the signature.
                            streaming = Some(path.span());
                        } else if path.is_ident("bidirectional") {
                            return Err(syn::Error::new_spanned(&path, BIDIRECTIONAL_REMOVED));
                        } 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());
                        } else if path.is_ident("everywhere") {
                            // KEEL-31: acts on the whole service — its grant
                            // is needed on `*`, the gate's rule.
                            everywhere = Some(path.span());
                        } else {
                            // KEEL-31: a word this macro does not know is an
                            // error, never dropped (`everywhere` on an older
                            // macro compiled to nothing).
                            return Err(unknown_word(&path, "#[plexus_macros::method]", METHOD_WORDS));
                        }
                    }
                    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("input_window")
                            || path.is_ident("input_max_items")
                            || path.is_ident("input_max_bytes")
                            || path.is_ident("input_max_buffered")
                        {
                            // BIDIR-6: the method's input half.
                            let Expr::Lit(ExprLit { lit: Lit::Int(n), .. }) = value else {
                                return Err(syn::Error::new_spanned(
                                    &path,
                                    "expects a whole number, e.g. #[plexus_macros::method(input_window = 256)]",
                                ));
                            };
                            let slot = if path.is_ident("input_window") {
                                &mut input_ceiling.window
                            } else if path.is_ident("input_max_items") {
                                &mut input_ceiling.max_items
                            } else if path.is_ident("input_max_bytes") {
                                &mut input_ceiling.max_bytes
                            } else {
                                &mut input_ceiling.max_buffered
                            };
                            *slot = Some(n);
                        } 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
                                }
                            }
                        } else if path.is_ident("streaming") {
                            // RETURNS-36: `streaming = true`, the deprecated
                            // no-op as its bare form (`= false` says nothing).
                            if !matches!(value, Expr::Lit(ExprLit { lit: Lit::Bool(ref b), .. }) if !b.value) {
                                streaming = Some(path.span());
                            }
                        } else {
                            return Err(unknown_word(&path, "#[plexus_macros::method]", METHOD_WORDS));
                        }
                    }
                    Meta::List(MetaList { path, tokens, .. }) => {
                        if path.is_ident("uses") {
                            // NEST-16: `uses("shop.items", "shop.ui.slots.list")`.
                            let parser = Punctuated::<syn::LitStr, Token![,]>::parse_terminated;
                            for lit in syn::parse::Parser::parse2(parser, tokens.clone())? {
                                let v = lit.value();
                                if v.is_empty() || v.starts_with('.') || v.ends_with('.') || !v.contains('.') {
                                    return Err(syn::Error::new(
                                        lit.span(),
                                        format!("uses(\"{v}\"): a method of the parent by its dotted path from the parent's root, e.g. \"shop.items\""),
                                    ));
                                }
                                uses.push(v);
                            }
                        } else 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") {
                            // RETURNS-8: a method's return type is its
                            // contract; there is no shared enum to filter.
                            return Err(syn::Error::new_spanned(&path, RETURNS_REMOVED));
                        } else if path.is_ident("bidirectional") {
                            return Err(syn::Error::new_spanned(&path, BIDIRECTIONAL_REMOVED));
                        } else {
                            return Err(unknown_word(&path, "#[plexus_macros::method]", METHOD_WORDS));
                        }
                    }
                }
            }
        }

        // 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 = ...`",
            ));
        }

        // KEEL-31: a method that acts on the whole service is neither open to
        // everyone nor located by a target.
        if let Some(span) = everywhere {
            if public {
                return Err(syn::Error::new(span, "a method that acts `everywhere` is not `public`: remove one"));
            }
            if target.is_some() {
                return Err(syn::Error::new(
                    span,
                    "a method that acts `everywhere` has no `target`: it is decided on `*`; remove one",
                ));
            }
        }

        Ok(HubMethodAttrs { uses, name, description, param_docs, http_method, request_override, public, scopes, streaming, target, answer_by, input_ceiling, group, examples, values, everywhere: everywhere.is_some() })
    }
}

/// 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 {
    /// NEST-16: `parent = ShopClient` — the client of the service this
    /// activation is written to be grafted onto; a method takes it as
    /// `parent: Parent<ShopClient>`.
    pub parent: Option<syn::Path>,
    /// `namespace = "..."`. MACRO-13: optional — when absent, the type's
    /// name (`impl Foo`, 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. RETURNS-47: without it no trait is emitted (but for a
    /// contract, which is its trait).
    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,
    /// KEEL-27: `served = written` — what an unmarked fn of the block is,
    /// read from how it is written (`codegen/infer.rs`): a `pub async fn`
    /// on `&self` a method, a `pub fn` on `&self` a mount (a slot when it
    /// takes `name: &str`), a `pub async fn` answering `Result<Box<dyn I>,
    /// PeerError>` a fallible mount, anything else a helper. The span is the
    /// key's, for diagnostics. `None`: the rule before KEEL-27.
    pub served_written: Option<proc_macro2::Span>,
    /// 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 served_written: Option<proc_macro2::Span> = None;
        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();
        let mut parent: Option<syn::Path> = None;

        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;
                        }

                        // NEST-16: `parent = ShopClient`, a path to a generated client.
                        if path.is_ident("parent") {
                            match &value {
                                Expr::Path(p) if p.qself.is_none() => parent = Some(p.path.clone()),
                                _ => {
                                    return Err(syn::Error::new_spanned(
                                        &value,
                                        "parent = <Client>: the parent's generated client, by its path (parent = ShopClient)",
                                    ))
                                }
                            }
                            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;
                        }

                        // IR-5: the legacy `children = [field, …]` (deprecated;
                        // a warning says so), as its list form `children(…)`.
                        if path.is_ident("children") {
                            let Expr::Array(arr) = &value else {
                                return Err(syn::Error::new_spanned(&value, "children = [field, …]: the fields that are child activations"));
                            };
                            for e in &arr.elems {
                                match e {
                                    Expr::Path(p) if p.path.get_ident().is_some() => children.push(p.path.get_ident().unwrap().clone()),
                                    other => return Err(syn::Error::new_spanned(other, "children = [field, …]: each a field's name")),
                                }
                            }
                            children_span = Some(path.span());
                            continue;
                        }

                        // KEEL-27: `served = written` (or `"written"`).
                        if path.is_ident("served") {
                            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(),
                            };
                            if word != "written" {
                                return Err(syn::Error::new_spanned(
                                    &value,
                                    "served = written: what each unmarked fn of the block is, read \
                                     from how it is written (a `pub async fn` a method, a `pub fn` a \
                                     mount, anything not `pub` a helper)",
                                ));
                            }
                            served_written = Some(path.span());
                            continue;
                        }

                        // KEEL-31: every other key takes a string; one this
                        // macro does not know is an error, never dropped.
                        const STRING_KEYS: &[&str] = &[
                            TRAIT_KEY, "namespace", "version", "description", "long_description", "crate_path",
                            "plugin_id", "namespace_fn", "server_cfg", "auth",
                        ];
                        if !STRING_KEYS.iter().any(|k| path.is_ident(k)) {
                            return Err(unknown_word(&path, "#[plexus_macros::activation]", ACTIVATION_WORDS));
                        }
                        let Expr::Lit(ExprLit { lit: Lit::Str(_), .. }) = &value else {
                            let key = if path.is_ident(TRAIT_KEY) { "trait".to_string() } else { path.get_ident().map(|i| i.to_string()).unwrap_or_default() };
                            return Err(syn::Error::new_spanned(&value, format!("{key} = … expects a string, e.g. {key} = \"…\"")));
                        };
                        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) {
                            // RETURNS-47: a trait only when named; a bare
                            // `trait` names none.
                            return Err(syn::Error::new(
                                path.span(),
                                "a trait is emitted only when named: write `trait = \"Name\"` \
                                 (or write the trait by hand and `impl Name for YourType`)",
                            ));
                        } 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;
                        } else {
                            return Err(unknown_word(&path, "#[plexus_macros::activation]", ACTIVATION_WORDS));
                        }
                    }
                    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());
                        }
                        else {
                            return Err(unknown_word(&list.path, "#[plexus_macros::activation]", ACTIVATION_WORDS));
                        }
                    }
                }
            }
        }

        // 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"));
        }
        // KEEL-27: two rules for the unmarked fns cannot both hold.
        if let (Some(span), true) = (served_written, methods_marked) {
            return Err(syn::Error::new(
                span,
                "served = written and methods = marked say opposite things of an unmarked fn: \
                 under `served = written` a `pub async fn` is a method, under `methods = marked` \
                 only a #[plexus_macros::method] is; write one",
            ));
        }

        Ok(HubMethodsAttrs {
            parent,
            namespace,
            trait_attr,
            trait_span,
            methods_marked,
            served_written,
            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>,
    /// RETURNS-46: `#[child(opaque)]` — the child's type has no client (a
    /// hand-written `ChildRouter`, an activation without one): the parent's
    /// client gets no accessor for it and its aggregate no variant. Routing
    /// is unchanged.
    pub opaque: bool,
    /// 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,
    /// NEST-7: `#[plexus_macros::peer]` — an activation returned by name,
    /// `Result<Box<dyn I>, PeerError>`: typed by `I`, or untyped (`Peer`).
    pub peer: Option<crate::codegen::peer::PeerShape>,
    /// NEST-7: for a peer slot with `list = …`, whether that sibling is
    /// `async` (set by the activation driver, which sees the siblings).
    pub list_is_async: bool,
    /// NEST-17: each `list = "…"` / `search = "…"` written as a string —
    /// the key and where — said as a deprecation warning (a path, `list =
    /// names`, is the form now).
    pub string_args: Vec<(String, proc_macro2::Span)>,
}

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 is_peer = method.attrs.iter().any(|a| a.path().segments.last().is_some_and(|s| s.ident == "peer"));
        Self::from_fn_as(method, is_peer)
    }

    /// KEEL-27: the same, with whether it is a fallible mount (a peer) said
    /// by the caller — by its `#[peer]` marker, or, unmarked under `served =
    /// written`, by its signature (`codegen/infer.rs`). An unmarked mount
    /// carries no options, so it is built exactly as a bare `#[child]` /
    /// `#[peer]` is.
    pub fn from_fn_as(method: &ImplItemFn, is_peer: bool) -> 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, opaque, string_args) = 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)",
                ));
            }
        };

        // NEST-7: a `#[peer]` is a dynamic slot whose function answers
        // `Result<Box<dyn I>, PeerError>`, awaited; it has no generated
        // client accessor (the peer's own client is its interface's).
        let (peer, opaque) = if is_peer {
            if !matches!(kind, ChildMethodKind::Dynamic) || !is_async {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "a #[plexus_macros::peer] method is `async fn NAME(&self, name: &str) -> \
                     Result<Box<dyn I>, PeerError>`",
                ));
            }
            let shape = crate::codegen::peer::peer_shape(&return_ty).map_err(|why| syn::Error::new_spanned(&return_ty, why))?;
            (Some(shape), true)
        } else {
            (None, opaque)
        };

        Ok(ChildMethodInfo {
            fn_name,
            description,
            kind,
            is_async,
            list_fn,
            search_fn,
            opaque,
            deprecation,
            forward,
            return_ty,
            peer,
            list_is_async: false,
            string_args,
        })
    }
}

/// Parse the arguments of a `#[child(...)]` / `#[plexus_macros::child(...)]`
/// (or `#[plexus_macros::peer(...)]`) attribute. Supported args:
///
/// - `list = method_name` — links a sibling list method (CHILD-4)
/// - `search = method_name` — links a sibling search method (CHILD-4)
/// - `forward = same_service | identity_only | pass_through | anonymous`
///   — MACRO-20: how the child inherits its caller
/// - `opaque` — RETURNS-46: the child has no typed client
///
/// NEST-17: `list` and `search` name a sibling method by its path; the
/// string forms (`list = "method"`) are still accepted for one release and
/// returned as `string_args`, which the activation says as a deprecation
/// warning. `forward` takes the policy as a bare word or a string.
///
/// If the attribute is bare (`#[child]`) every returned value is `None`.
/// Unknown args are rejected so typos surface early.
#[allow(clippy::type_complexity)]
fn parse_child_attr_args(
    attrs: &[syn::Attribute],
) -> syn::Result<(Option<syn::Ident>, Option<syn::Ident>, Option<ChildForward>, bool, Vec<(String, proc_macro2::Span)>)> {
    const EXPECTED: &str = "expected `list = method`, `search = method`, `forward = policy` or `opaque`";
    let mut list_fn: Option<syn::Ident> = None;
    let mut search_fn: Option<syn::Ident> = None;
    let mut forward: Option<ChildForward> = None;
    let mut opaque = false;
    let mut string_args: Vec<(String, proc_macro2::Span)> = Vec::new();

    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") | Some("peer")) {
            continue;
        }

        match &attr.meta {
            // Bare `#[child]` — no args, nothing to parse.
            Meta::Path(_) => {}
            // `#[child(list = names, search = find)]`
            Meta::List(list) => {
                let metas = list.parse_args_with(
                    Punctuated::<Meta, Token![,]>::parse_terminated,
                )?;
                for meta in metas {
                    match meta {
                        // RETURNS-46: `opaque` — the child has no client, so
                        // the parent's client and aggregate leave it out.
                        Meta::Path(ref p) if p.is_ident("opaque") => {
                            if opaque {
                                return Err(syn::Error::new_spanned(p, "duplicate `opaque` on #[plexus_macros::child]"));
                            }
                            opaque = true;
                        }
                        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,
                                        format!("unknown argument to #[plexus_macros::child]; {EXPECTED}"),
                                    ));
                                }
                            };
                            // NEST-17: a path (`names`), or — deprecated for
                            // `list` / `search` — a string (`"names"`).
                            let (word, span, was_string) = match value {
                                Expr::Lit(ExprLit { lit: Lit::Str(ref s), .. }) => (s.value(), s.span(), true),
                                Expr::Path(ref p) if p.qself.is_none() && p.path.get_ident().is_some() => {
                                    let id = p.path.get_ident().unwrap();
                                    (id.to_string(), id.span(), false)
                                }
                                _ => {
                                    return Err(syn::Error::new_spanned(
                                        &value,
                                        format!(
                                            "#[plexus_macros::child({ident_key} = …)] expects the name of a sibling method \
                                             (`{ident_key} = method`)",
                                        ),
                                    ));
                                }
                            };
                            if ident_key == "forward" {
                                if forward.is_some() {
                                    return Err(syn::Error::new(
                                        span,
                                        "duplicate `forward = …` argument on #[plexus_macros::child]",
                                    ));
                                }
                                forward = Some(ChildForward::parse(&word).ok_or_else(|| {
                                    syn::Error::new(
                                        span,
                                        format!(
                                            "unknown forward policy `{word}` on #[plexus_macros::child]; expected {}",
                                            ChildForward::SPELLINGS
                                        ),
                                    )
                                })?);
                                continue;
                            }
                            let method_ident = syn::parse_str::<syn::Ident>(&word)
                                .map(|mut i| {
                                    i.set_span(span);
                                    i
                                })
                                .map_err(|_| syn::Error::new(span, format!("`{word}` is not a method name")))?;
                            match ident_key.as_str() {
                                "list" => {
                                    if list_fn.is_some() {
                                        return Err(syn::Error::new(
                                            span,
                                            "duplicate `list = …` argument on #[plexus_macros::child]",
                                        ));
                                    }
                                    list_fn = Some(method_ident);
                                }
                                "search" => {
                                    if search_fn.is_some() {
                                        return Err(syn::Error::new(
                                            span,
                                            "duplicate `search = …` argument on #[plexus_macros::child]",
                                        ));
                                    }
                                    search_fn = Some(method_ident);
                                }
                                other => {
                                    return Err(syn::Error::new_spanned(
                                        &path,
                                        format!("unknown argument `{other}` to #[plexus_macros::child]; {EXPECTED}"),
                                    ));
                                }
                            }
                            if was_string {
                                string_args.push((ident_key, span));
                            }
                        }
                        other => {
                            let word = other.path().get_ident().map(|i| i.to_string()).unwrap_or_default();
                            return Err(syn::Error::new_spanned(
                                other,
                                format!("unknown word `{word}` in #[plexus_macros::child] / #[plexus_macros::peer]; {EXPECTED}"),
                            ));
                        }
                    }
                }
            }
            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 = method, search = method)]`",
                ));
            }
        }
    }

    Ok((list_fn, search_fn, forward, opaque, string_args))
}

/// 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).
pub(crate) 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" || s.ident == "peer")
            .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
/// NEST-16: a method's injected `parent: Parent<C>`.
#[derive(Clone)]
pub struct ParentParam {
    pub name: syn::Ident,
    /// Its place among the arguments the method is called with after the
    /// injected ones (the RPC params and an `Input`).
    pub at: usize,
    /// `C`, as the signature says it (the macro has already written its
    /// transport: `ShopClient<ParentTransport>`).
    pub client: Type,
    /// `Parent<C>`.
    pub ty: Type,
}

/// NEST-16: `C` of a `Parent<C>` type (by its last path segment).
pub(crate) fn parent_client_type(ty: &Type) -> Option<Type> {
    let Type::Path(tp) = ty else { return None };
    let last = tp.path.segments.last()?;
    if last.ident != "Parent" {
        return None;
    }
    let syn::PathArguments::AngleBracketed(args) = &last.arguments else { return None };
    match args.args.first()? {
        syn::GenericArgument::Type(t) if args.args.len() == 1 => Some(t.clone()),
        _ => None,
    }
}

pub struct MethodInfo {
    /// NEST-16: the injected `parent: Parent<C>` parameter, if any.
    pub parent: Option<ParentParam>,
    /// NEST-16: `uses(…)`, as written.
    pub uses: Vec<String>,
    /// NEST-16: the call chains on `parent` found in the body (each the
    /// names of its links, as the code wrote them), filled in by the
    /// activation's codegen.
    pub parent_chains: Vec<Vec<String>>,
    pub fn_name: syn::Ident,
    pub method_name: String,
    pub description: String,
    pub params: Vec<ParamInfo>,
    /// RETURNS-8: one item (`-> T`, `-> Result<T, E>`) or many (`-> impl
    /// Stream<Item = …>`), read from the return type.
    pub cardinality: Cardinality,
    /// RETURNS-36: the span of a `streaming` that agrees with the signature,
    /// for its deprecation warning.
    pub streaming_deprecated: Option<proc_macro2::Span>,
    /// RETURNS-8: `T` — the item minus its `Result` / `Progress` wrappers.
    pub ok_ty: Type,
    /// RETURNS-8: `E` when the item is a `Result<_, E>`; `None` when the method
    /// is infallible.
    pub err_ty: Option<Type>,
    /// RETURNS-8: `P` when the item is a `Progress<_, P>` (or `Progress<_>`,
    /// whose `P` is the default `Note`); `None` when the method reports no
    /// progress.
    pub progress_ty: Option<ProgressTy>,
    /// 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,
    /// KEEL-31: `everywhere` (mirrored from `HubMethodAttrs::everywhere`);
    /// emitted as `MethodSchema.everywhere`.
    pub everywhere: 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>,
    /// BIDIR-6: the method's `Input<T>` parameter: not in `params`, so the
    /// params object is the other parameters.
    pub input: Option<InputInfo>,
    /// 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,
    /// RETURNS-47: on `impl Trait for Type`, the verifier written on the
    /// method (`#[plexus_macros::from_auth(self.access.verify)]`): run on
    /// the call's signed-in caller before the body, its error the call's
    /// typed refusal, its value kept for `plexus_core::call::verified`.
    pub verifier: Option<syn::Expr>,
    /// RETURNS-47: on `impl Trait for Type`, the dispatch reads the caller
    /// from the call's context and refuses one not signed in, before the
    /// body, out of band (`auth = "required"` on a method not `public`, or
    /// any method with a verifier).
    pub caller_required: 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 from hub_method attrs
        let param_docs = hub_method_attrs
            .map(|a| &a.param_docs)
            .cloned()
            .unwrap_or_default();
        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());

        // 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;
        // BIDIR-6: the one `Input<T>`.
        let mut input: Option<InputInfo> = None;
        // NEST-16: the one `Parent<C>`.
        let mut parent: Option<ParentParam> = 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();

                    // NEST-16: the server passes what it injects first, so a
                    // `parent` comes after every other injected parameter.
                    if parent.is_some()
                        && ((name_str == "reach" && is_reach_type(&pat_type.ty))
                            || has_activation_param_attr(&pat_type.attrs)
                            || extract_from_auth_attr(&pat_type.attrs).is_some()
                            || (name_str == "auth" && classify_auth_context_type(&pat_type.ty).is_some()))
                    {
                        return Err(syn::Error::new_spanned(
                            pat_type,
                            "`parent: Parent<…>` comes after `auth`, `reach`, `#[from_auth]` and `#[activation_param]` parameters",
                        ));
                    }
                    if let Some(client) = parent_client_type(&pat_type.ty) {
                        if let Some(first) = &parent {
                            return Err(syn::Error::new_spanned(
                                pat_type,
                                format!("`{method_name}` takes a second `Parent` (the first is `{}`): a method takes at most one", first.name),
                            ));
                        }
                        let at = params.len() + usize::from(input.is_some());
                        parent = Some(ParentParam { name, at, client, ty: (*pat_type.ty).clone() });
                        continue;
                    }

                    // 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;
                        }
                    }

                    // BIDIR-6: `Input<T>` is the input half, not a param. At
                    // most one, at the top level: anywhere else there is no
                    // item for the macro to hand it.
                    if let Some(item) = input_item_type(&pat_type.ty) {
                        if let Some(first) = &input {
                            return Err(syn::Error::new_spanned(
                                pat_type,
                                format!("`{method_name}` declares a second `Input` (the first is `{}`): a method takes at most one", first.name),
                            ));
                        }
                        let description = param_docs.get(&name_str).cloned().or_else(|| extract_doc_description(&pat_type.attrs));
                        let ceiling = hub_method_attrs.map(|a| a.input_ceiling.clone()).unwrap_or_default();
                        input = Some(InputInfo { name, item, at: params.len(), description, ceiling });
                        continue;
                    }
                    if names_input(pat_type.ty.to_token_stream()) {
                        return Err(syn::Error::new_spanned(
                            &pat_type.ty,
                            format!("`{method_name}`: `Input` is a parameter of the method itself, by value: it cannot be nested in another type"),
                        ));
                    }

                    // 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,
                    });
                }
            }
        }

        // RETURNS-8: the return type is the method's whole contract —
        // cardinality, item, error and progress, read syntactically.
        let ReturnShape { cardinality, ok_ty, err_ty, progress_ty } =
            classify_return(&method.sig)?;

        // RETURNS-36: `streaming` agrees with a stream form (a deprecated
        // no-op, warned in codegen) and is an error on a one-item form.
        let streaming_deprecated = hub_method_attrs.and_then(|a| a.streaming);
        if let (Some(span), Cardinality::One) = (streaming_deprecated, cardinality) {
            let returns = match &method.sig.output {
                ReturnType::Type(_, ty) => quote::quote!(#ty).to_string(),
                ReturnType::Default => "()".to_string(),
            };
            return Err(syn::Error::new(
                span,
                format!(
                    "`streaming` says this method yields many items, but `-> {returns}` yields one. \
                     Remove `streaming` (cardinality comes from the return type), or return \
                     `impl Stream<Item = ...>`."
                ),
            ));
        }

        // 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);
        let everywhere = hub_method_attrs.is_some_and(|a| a.everywhere);

        // 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,
                        ),
                    ))
                }
            },
        };

        // BIDIR-6: the input half's attributes need an input half; a window
        // of nothing would grant nothing.
        let ceiling = hub_method_attrs.map(|a| a.input_ceiling.clone()).unwrap_or_default();
        if input.is_none() {
            if let Some((name, lit)) = ceiling.first() {
                return Err(syn::Error::new(lit.span(), format!("{name} on `{fn_name}`, which has no `Input` parameter")));
            }
        }
        if let Some(window) = &ceiling.window {
            if window.base10_parse::<u64>()? == 0 {
                return Err(syn::Error::new(window.span(), format!("input_window on `{fn_name}`: a window of 0 lets nothing in")));
            }
        }

        // 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 {
            parent,
            uses: hub_method_attrs.map(|a| a.uses.clone()).unwrap_or_default(),
            parent_chains: Vec::new(),
            fn_name,
            method_name,
            description,
            params,
            cardinality,
            streaming_deprecated,
            ok_ty,
            err_ty,
            progress_ty,
            http_method,
            requires_auth,
            auth_optional,
            auth_resolvers,
            activation_params,
            request_override,
            public,
            everywhere,
            scopes,
            deprecation,
            target,
            answer_by,
            input,
            long_description,
            group,
            examples,
            values,
            takes_reach,
            verifier: None,
            caller_required: false,
        })
    }
}

/// 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,
}


// ============================================================================
// RETURNS-8: the signature forms
// ============================================================================

/// Whether a method yields one item or many (RETURNS-1 decision 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Cardinality {
    /// `-> T` / `-> Result<T, E>`: exactly one item.
    One,
    /// `-> impl Stream<Item = …>`: zero or more items.
    Many,
}

/// The progress type `P` of a `Progress<T, P>` item.
#[derive(Debug, Clone)]
pub enum ProgressTy {
    /// `Progress<T>`: `P` is the default, `plexus_client::Note`. It has no
    /// path of its own in the signature, so each half of the expansion names
    /// it through the crate it links — the server through `plexus-core`'s
    /// re-export, a client through `plexus-client` (see [`ProgressTy::to_type`]).
    Note,
    /// `Progress<T, P>`: `P` as written.
    Declared(Type),
}

impl ProgressTy {
    /// `P` as a type, given the path of a crate that exports `Note` at
    /// `<vocabulary>::Note` (`::plexus_core::plexus` server-side,
    /// `::plexus_client` client-side).
    pub fn to_type(&self, vocabulary: &syn::Path) -> Type {
        match self {
            ProgressTy::Note => syn::parse_quote!(#vocabulary::Note),
            ProgressTy::Declared(ty) => ty.clone(),
        }
    }
}

/// A method's return type, taken apart (RETURNS-1 decisions 2, 3, 10).
pub struct ReturnShape {
    pub cardinality: Cardinality,
    pub ok_ty: Type,
    pub err_ty: Option<Type>,
    pub progress_ty: Option<ProgressTy>,
}

/// The six forms, as the error that names them lists them.
const SIX_FORMS: &str = "\
    -> T\n    \
    -> Result<T, E>\n    \
    -> impl Stream<Item = T>\n    \
    -> impl Stream<Item = Result<T, E>>\n    \
    -> impl Stream<Item = Progress<T, P>>\n    \
    -> impl Stream<Item = Result<Progress<T, P>, E>>";

fn not_a_form(span: impl quote::ToTokens, method: &syn::Ident) -> syn::Error {
    syn::Error::new_spanned(
        span,
        format!(
            "#[plexus_macros::method] `{method}`: the return type is not one of the six \
             signature forms:\n    {SIX_FORMS}\n\
             A boxed or named stream (`BoxStream`, `Pin<Box<dyn Stream>>`, `PlexusStream`) is \
             not recognised — return `impl Stream<Item = ...> + Send + 'static` instead. \
             `Result` (two type arguments) and `Progress` (one or two) are recognised by \
             name; an alias of either is a plain `T`."
        ),
    )
}

/// Read a method's signature form (RETURNS-1 pin 14: syntactic — the last
/// path segment `Result` with two type arguments, `Progress` with one or
/// two; `impl Stream<Item = X>` with any extra bounds).
pub fn classify_return(sig: &syn::Signature) -> syn::Result<ReturnShape> {
    let method = &sig.ident;
    let ty = match &sig.output {
        ReturnType::Default => return Err(not_a_form(sig, method)),
        ReturnType::Type(_, ty) => ungroup(ty),
    };

    let (item, cardinality) = match ty {
        Type::ImplTrait(it) => (
            impl_stream_item(it).ok_or_else(|| not_a_form(ty, method))?,
            Cardinality::Many,
        ),
        _ => (ty, Cardinality::One),
    };

    let (inner, err_ty) = match result_args(item) {
        Some((t, e)) => (t, Some(e)),
        None => (item, None),
    };
    let (ok_ty, progress_ty) = match progress_args(inner) {
        Some((t, p)) => (t, Some(p)),
        None => (inner, None),
    };

    if progress_ty.is_some() && cardinality == Cardinality::One {
        return Err(syn::Error::new_spanned(
            ty,
            format!(
                "#[plexus_macros::method] `{method}`: a method that reports progress yields \
                 many items — return `impl Stream<Item = Progress<T, P>>` (or \
                 `impl Stream<Item = Result<Progress<T, P>, E>>`). A one-item method \
                 cannot report progress."
            ),
        ));
    }

    for part in [Some(ok_ty), err_ty].into_iter().flatten() {
        if !is_plain_item(part) {
            return Err(not_a_form(part, method));
        }
    }
    if let Some(ProgressTy::Declared(p)) = &progress_ty {
        if !is_plain_item(p) {
            return Err(not_a_form(p, method));
        }
    }

    Ok(ReturnShape {
        cardinality,
        ok_ty: ok_ty.clone(),
        err_ty: err_ty.cloned(),
        progress_ty,
    })
}

/// `(T)` and invisible groups are the type inside them.
fn ungroup(ty: &Type) -> &Type {
    match ty {
        Type::Paren(p) => ungroup(&p.elem),
        Type::Group(g) => ungroup(&g.elem),
        other => other,
    }
}

/// `X` of `impl Stream<Item = X> [+ bounds]`; `None` for any other `impl`.
fn impl_stream_item(it: &syn::TypeImplTrait) -> Option<&Type> {
    it.bounds.iter().find_map(|bound| {
        let syn::TypeParamBound::Trait(tb) = bound else { return None };
        let last = tb.path.segments.last()?;
        if last.ident != "Stream" {
            return None;
        }
        let PathArguments::AngleBracketed(args) = &last.arguments else { return None };
        args.args.iter().find_map(|arg| match arg {
            GenericArgument::AssocType(at) if at.ident == "Item" => Some(ungroup(&at.ty)),
            _ => None,
        })
    })
}

/// The type arguments of a path type's last segment, if it is `name`.
fn type_args<'a>(ty: &'a Type, name: &str) -> Option<Vec<&'a Type>> {
    let Type::Path(tp) = ty else { return None };
    if tp.qself.is_some() {
        return None;
    }
    let last = tp.path.segments.last()?;
    if last.ident != name {
        return None;
    }
    let PathArguments::AngleBracketed(args) = &last.arguments else { return None };
    let tys: Vec<&Type> = args
        .args
        .iter()
        .filter_map(|a| match a {
            GenericArgument::Type(t) => Some(ungroup(t)),
            _ => None,
        })
        .collect();
    (tys.len() == args.args.len()).then_some(tys)
}

/// `(T, E)` of `Result<T, E>` — exactly two type arguments.
fn result_args(ty: &Type) -> Option<(&Type, &Type)> {
    match type_args(ty, "Result")?.as_slice() {
        [t, e] => Some((t, e)),
        _ => None,
    }
}

/// `(T, P)` of `Progress<T, P>` / `Progress<T>` (`P` = `Note`).
fn progress_args(ty: &Type) -> Option<(&Type, ProgressTy)> {
    match type_args(ty, "Progress")?.as_slice() {
        [t] => Some((t, ProgressTy::Note)),
        [t, p] => Some((t, ProgressTy::Declared((*p).clone()))),
        _ => None,
    }
}

/// `false` for a type that is a stream or an opaque trait rather than a
/// value: `impl Trait`, `dyn Trait`, `Box<dyn …>`, `Pin<…>`, and the named
/// stream types (`BoxStream`, `LocalBoxStream`, `PlexusStream`, `Stream`).
/// Any other type is a plain item the schema and the wire can carry.
fn is_plain_item(ty: &Type) -> bool {
    match ungroup(ty) {
        Type::ImplTrait(_) | Type::TraitObject(_) => false,
        Type::Path(tp) => {
            let Some(last) = tp.path.segments.last() else { return true };
            let name = last.ident.to_string();
            if matches!(
                name.as_str(),
                "BoxStream" | "LocalBoxStream" | "PlexusStream" | "Stream" | "Pin"
            ) {
                return false;
            }
            if name == "Box" {
                if let Some(args) = type_args(ty, "Box") {
                    return !args.iter().any(|t| matches!(t, Type::TraitObject(_)));
                }
            }
            true
        }
        _ => true,
    }
}

/// 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")
}

/// 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 {
            uses: vec![],
            name: None,
            description: None,
            param_docs: {
                let mut m = HashMap::new();
                m.insert("message".to_string(), "explicit description".to_string());
                m
            },
            http_method: None,
            request_override: None,
            public: false,
            scopes: vec![],
            streaming: None,
            target: None,
            answer_by: None,
            input_ceiling: InputCeilingAttrs::default(),
            group: None,
            examples: vec![],
            values: vec![],
            everywhere: false,
        };
        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}"
        );
    }

    // ------------------------------------------------------------------
    // RETURNS-8: the signature forms and the implicit namespace
    // ------------------------------------------------------------------

    fn shape(sig: syn::Signature) -> syn::Result<ReturnShape> {
        classify_return(&sig)
    }

    fn tokens(ty: &Type) -> String {
        quote::quote!(#ty).to_string()
    }

    /// The six forms, each with its cardinality, `T`, `E` and `P`.
    #[test]
    fn the_six_forms_are_read_from_the_signature() {
        let cases: Vec<(syn::Signature, Cardinality, &str, Option<&str>, Option<&str>)> = vec![
            (parse_quote! { async fn a(&self) -> Pong }, Cardinality::One, "Pong", None, None),
            (
                parse_quote! { async fn b(&self) -> Result<Thing, LookupError> },
                Cardinality::One,
                "Thing",
                Some("LookupError"),
                None,
            ),
            (
                parse_quote! { async fn c(&self) -> impl Stream<Item = Tick> + Send + 'static },
                Cardinality::Many,
                "Tick",
                None,
                None,
            ),
            (
                parse_quote! { async fn d(&self) -> impl Send + Stream<Item = std::result::Result<Row, ScanError>> },
                Cardinality::Many,
                "Row",
                Some("ScanError"),
                None,
            ),
            (
                parse_quote! { async fn e(&self) -> impl Stream<Item = Result<Progress<Loaded, LoadStep>, LoadError>> },
                Cardinality::Many,
                "Loaded",
                Some("LoadError"),
                Some("LoadStep"),
            ),
            (
                parse_quote! { async fn f(&self) -> impl Stream<Item = plexus_client::Progress<Warmed>> },
                Cardinality::Many,
                "Warmed",
                None,
                Some("Note"),
            ),
        ];
        let vocabulary: syn::Path = parse_quote!(v);
        for (sig, cardinality, ok, err, progress) in cases {
            let name = sig.ident.to_string();
            let s = shape(sig).unwrap_or_else(|e| panic!("{name}: {e}"));
            assert_eq!(s.cardinality, cardinality, "{name}");
            assert_eq!(tokens(&s.ok_ty), ok, "{name}");
            assert_eq!(s.err_ty.as_ref().map(tokens).as_deref(), err, "{name}");
            let p = s.progress_ty.map(|p| match p {
                ProgressTy::Note => "Note".to_string(),
                declared => tokens(&declared.to_type(&vocabulary)),
            });
            assert_eq!(p.as_deref(), progress, "{name}");
        }
    }

    /// Pin 14: recognition is by name and arity — `anyhow::Result<T>` (one
    /// argument) is a plain `T`.
    #[test]
    fn a_one_argument_result_alias_is_a_plain_item() {
        let s = shape(parse_quote! { async fn a(&self) -> anyhow::Result<Pong> }).unwrap();
        assert_eq!(s.cardinality, Cardinality::One);
        assert_eq!(tokens(&s.ok_ty), "anyhow :: Result < Pong >");
        assert!(s.err_ty.is_none());
    }

    #[test]
    fn other_return_types_name_the_six_forms() {
        let bad: Vec<syn::Signature> = vec![
            parse_quote! { async fn a(&self) -> BoxStream<'static, Tick> },
            parse_quote! { async fn a(&self) -> Pin<Box<dyn Stream<Item = Tick> + Send>> },
            parse_quote! { async fn a(&self) -> PlexusStream },
            parse_quote! { async fn a(&self) -> Result<PlexusStream, PlexusError> },
            parse_quote! { async fn a(&self) -> impl Future<Output = Tick> },
            parse_quote! { async fn a(&self) -> Box<dyn Stream<Item = Tick>> },
            parse_quote! { async fn a(&self) },
        ];
        for sig in bad {
            let msg = match shape(sig) {
                Ok(_) => panic!("must be rejected"),
                Err(e) => e.to_string(),
            };
            assert!(msg.contains("six signature forms"), "{msg}");
            assert!(msg.contains("-> impl Stream<Item = Result<Progress<T, P>, E>>"), "{msg}");
        }
    }

    #[test]
    fn progress_needs_a_stream() {
        for sig in [
            parse_quote! { async fn a(&self) -> Progress<Tick> },
            parse_quote! { async fn a(&self) -> Result<Progress<Tick, Step>, E> },
        ] {
            let sig: syn::Signature = sig;
            let msg = match shape(sig) {
                Ok(_) => panic!("must be rejected"),
                Err(e) => e.to_string(),
            };
            assert!(msg.contains("cannot report progress"), "{msg}");
        }
    }

    #[test]
    fn streaming_is_deprecated_and_returns_removed() {
        // RETURNS-36: `streaming` parses (a deprecated no-op where the
        // signature agrees; checked against it in `MethodInfo::from_fn`).
        assert!(syn::parse_str::<HubMethodAttrs>("streaming").is_ok(), "`streaming` parses");
        let err = match syn::parse_str::<HubMethodAttrs>("returns(Ok, Error)") {
            Ok(_) => panic!("`returns(..)` must be rejected"),
            Err(e) => e.to_string(),
        };
        assert!(err.contains("give each method its own return type"), "{err}");
    }

}