plexus-macros 0.10.0

Procedural macros for Plexus RPC activations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
//! Code generation for Plexus RPC macros

mod activation;
pub(crate) mod client;
mod contract;
mod method_enum;
pub(crate) mod peer;

use crate::parse::{
    extract_doc_description, find_and_validate_list_search_method, has_child_attr,
    has_method_attr, parse_deprecation_attrs, ChildMethodInfo, ChildMethodKind, HubMethodAttrs,
    HubMethodsAttrs, ListSearchKind, ListSearchMethodInfo, MethodInfo, ParsedDeprecation,
};
use proc_macro2::{Span, TokenStream};
use proc_macro_crate::{crate_name, FoundCrate};
use quote::{format_ident, quote};
use syn::{spanned::Spanned, FnArg, ImplItem, ItemImpl, Meta, Type};

/// Z2H-2: locate the `plexus-rpc` umbrella crate in the consumer's manifest.
///
/// Returns `Some(ident)` (rename-respecting) when the consuming crate depends
/// on `plexus-rpc`; `None` otherwise (including `FoundCrate::Itself`, which
/// only occurs for plexus-rpc's own examples/tests — those carry direct
/// dev-deps and take the direct-emission path).
pub(crate) fn umbrella_crate(err_span: Span) -> Option<syn::Ident> {
    match crate_name("plexus-rpc") {
        Ok(FoundCrate::Name(name)) => Some(syn::Ident::new(&name, err_span)),
        _ => None,
    }
}

/// Z2H-2: emit the per-expansion dependency shim module.
///
/// Every third-party name the activation macro emits (`async_trait`,
/// `futures`, `jsonrpsee`, `schemars`, `serde`, `serde_json`, `tokio`,
/// `uuid`) is referenced relatively through this module, so the umbrella /
/// direct decision is made ONCE here instead of at ~80 quote! sites:
///
/// - umbrella consumer (depends on `plexus-rpc`) → re-export from
///   `::plexus_rpc::__deps::*`; the consumer needs none of these crates in
///   its own Cargo.toml.
/// - direct consumer (today's sibling-checkout shape) → re-export from the
///   extern prelude, preserving pre-Z2H-2 semantics exactly.
///
/// The module ident is per-struct (`__plexus_deps_<Struct>`) so two
/// activations in one module don't collide.
pub(crate) fn deps_shim(shim_ident: &syn::Ident, err_span: Span) -> TokenStream {
    match umbrella_crate(err_span) {
        Some(umbrella) => quote! {
            #[doc(hidden)]
            #[allow(unused_imports, non_snake_case)]
            mod #shim_ident {
                pub use ::#umbrella::__deps::{
                    async_trait, futures, jsonrpsee, schemars, serde, serde_json, tokio, uuid,
                };
            }
        },
        None => quote! {
            #[doc(hidden)]
            #[allow(unused_imports, non_snake_case)]
            mod #shim_ident {
                pub use ::async_trait;
                pub use ::futures;
                pub use ::jsonrpsee;
                pub use ::schemars;
                pub use ::serde;
                pub use ::serde_json;
                pub use ::tokio;
                pub use ::uuid;
            }
        },
    }
}

/// Z2H-2: absolute path to `plexus-core` for derive-macro emission
/// (`#[derive(PlexusRequest)]`), which historically hardcoded
/// `::plexus_core::...`. Resolution is additive over that behavior: the only
/// case that changes is "no plexus-core dep but the plexus-rpc umbrella is
/// present", which now routes through `::<plexus_rpc>::core`.
pub(crate) fn derive_core_path(err_span: Span) -> syn::Path {
    match crate_name("plexus-core") {
        Ok(FoundCrate::Name(name)) => {
            let ident = syn::Ident::new(&name, err_span);
            syn::parse_quote!(::#ident)
        }
        // `Itself` only fires for plexus-core's own build/tests; integration
        // tests see the lib in the extern prelude, so the historical
        // hardcoded path keeps working there. Preserve it.
        Ok(FoundCrate::Itself) => syn::parse_quote!(::plexus_core),
        Err(_) => match umbrella_crate(err_span) {
            Some(umbrella) => syn::parse_quote!(::#umbrella::core),
            None => syn::parse_quote!(::plexus_core),
        },
    }
}

/// Z2H-2: absolute path to `serde_json` for derive-macro emission. Same
/// additive contract as [`derive_core_path`]: umbrella-only consumers route
/// through `::<plexus_rpc>::__deps::serde_json`; everyone else keeps the
/// historical `::serde_json`.
pub(crate) fn derive_serde_json_path(err_span: Span) -> syn::Path {
    match crate_name("serde_json") {
        Ok(FoundCrate::Name(name)) => {
            let ident = syn::Ident::new(&name, err_span);
            syn::parse_quote!(::#ident)
        }
        Ok(FoundCrate::Itself) => syn::parse_quote!(::serde_json),
        Err(_) => match umbrella_crate(err_span) {
            Some(umbrella) => syn::parse_quote!(::#umbrella::__deps::serde_json),
            None => syn::parse_quote!(::serde_json),
        },
    }
}

/// Resolve the `crate_path` to a syn::Path.
///
/// If the caller passed `crate_path = "..."` explicitly, parse that string.
/// Otherwise, call `proc_macro_crate::crate_name("plexus-core")` and emit the
/// correct path:
///   - `FoundCrate::Itself`    → `crate`  (code being compiled IS plexus-core)
///   - `FoundCrate::Name(n)`   → `::<n>`  (external; respects renaming)
///   - `Err` + umbrella        → `::<plexus_rpc>::core` (Z2H-2: the consumer
///                               depends only on the `plexus-rpc` umbrella)
///   - `Err`                   → a compile error naming the missing dependency
fn resolve_crate_path(explicit: Option<&str>, err_span: Span) -> syn::Result<syn::Path> {
    if let Some(s) = explicit {
        return syn::parse_str(s);
    }

    match crate_name("plexus-core") {
        Ok(FoundCrate::Itself) => syn::parse_str("crate"),
        Ok(FoundCrate::Name(name)) => {
            let ident = syn::Ident::new(&name, err_span);
            Ok(syn::parse_quote!(::#ident))
        }
        // Z2H-2: umbrella fallback — a consumer depending only on plexus-rpc
        // reaches plexus-core through the umbrella's re-export.
        Err(e) => match umbrella_crate(err_span) {
            Some(umbrella) => Ok(syn::parse_quote!(::#umbrella::core)),
            None => Err(syn::Error::new(
                err_span,
                format!(
                    "#[plexus_macros::activation] could not locate the `plexus-core` \
                     dependency in Cargo.toml ({e}). Add `plexus-core` (or the \
                     `plexus-rpc` umbrella) as a dependency, or pass \
                     `crate_path = \"...\"` explicitly to override."
                ),
            )),
        },
    }
}

/// Resolve the path to `plexus-auth-core` for AUTHZ-CRED-MACRO-3's
/// credentials-registry call site. Unlike `resolve_crate_path`, absence is
/// **not** an error — consuming crates that don't depend on
/// `plexus-auth-core` (e.g., plexus-substrate today) simply skip the
/// credentials wiring, leaving `MethodSchema.credentials` at its empty
/// default. This preserves behavior for all pre-AUTHZ-CRED-MACRO-3 callers
/// and lets new callers opt in by adding the dep.
///
/// Returns `Some(path)` when `plexus-auth-core` is reachable; `None`
/// otherwise. The path respects user renaming (e.g.,
/// `plexus_auth_core = { package = "plexus-auth-core" }`).
pub(crate) fn resolve_auth_core_path(err_span: Span) -> Option<syn::Path> {
    match crate_name("plexus-auth-core") {
        Ok(FoundCrate::Itself) => syn::parse_str("crate").ok(),
        Ok(FoundCrate::Name(name)) => {
            let ident = syn::Ident::new(&name, err_span);
            Some(syn::parse_quote!(::#ident))
        }
        // Z2H-2: umbrella fallback — plexus-rpc always bundles auth-core, so
        // an umbrella-only consumer gets the credentials wiring through the
        // re-export instead of silently skipping it.
        Err(_) => umbrella_crate(err_span)
            .map(|umbrella| syn::parse_quote!(::#umbrella::auth_core)),
    }
}

/// Generate all code from a #[hub_methods] impl block
pub fn generate_all(args: HubMethodsAttrs, mut input_impl: ItemImpl) -> syn::Result<TokenStream> {
    let crate_path: syn::Path =
        resolve_crate_path(args.crate_path.as_deref(), Span::call_site())?;

    // Get struct name (ident only, for enum naming)
    let struct_name = match &*input_impl.self_ty {
        Type::Path(type_path) => type_path
            .path
            .segments
            .last()
            .map(|s| s.ident.clone())
            .ok_or_else(|| syn::Error::new_spanned(&input_impl.self_ty, "Expected struct name"))?,
        _ => return Err(syn::Error::new_spanned(&input_impl.self_ty, "Expected struct type")),
    };

    // RETURNS-47: `impl Trait for Type` — the trait names the contract.
    let trait_impl: Option<syn::Path> = match &input_impl.trait_ {
        None => None,
        Some((Some(bang), _, _)) => {
            return Err(syn::Error::new_spanned(bang, "a negative impl cannot be an activation"))
        }
        Some((None, path, _)) => Some(path.clone()),
    };

    // MACRO-13: a bodiless method (`pub async fn f(&self) -> …;`) arrives as
    // verbatim tokens; give it a placeholder body and remember it.
    let bodiless = contract::take_bodiless(&mut input_impl);
    if let (Some(path), Some(f)) = (&trait_impl, bodiless.first()) {
        return Err(syn::Error::new(
            f.span(),
            format!(
                "`{f}` has no body, in `impl {} for {struct_name}`: a trait impl has every body; \
                 the contract is the trait itself",
                quote!(#path).to_string().replace(' ', "")
            ),
        ));
    }

    // MACRO-13 / RETURNS-47: the name rule — on `impl FooActivation` the
    // stem, on `impl Foo` the type's own name, with `trait = "…"` the trait's
    // name, on `impl Trait for Type` the trait's, names the namespace and the
    // client; a trait is emitted only when named, or for a contract.
    let names = contract::Names::resolve(&args, &struct_name, trait_impl.as_ref(), !bodiless.is_empty())?;
    let namespace = names.namespace.clone();

    // MACRO-13: under the name rule every `pub async fn` on `&self`
    // returning a signature form (RETURNS-8) is a wire method, unless the
    // activation says `methods = marked`.
    let all_public_methods = names.new_form && !args.methods_marked;

    // Extract all #[method] / #[hub_method] functions and all #[child] functions.
    let mut methods: Vec<MethodInfo> = Vec::new();
    let mut child_methods: Vec<ChildMethodInfo> = Vec::new();

    for item in &mut input_impl.items {
        if let ImplItem::Fn(method) = item {
            // CHILD-3: a method annotated with both `#[child]` and `#[method]`
            // is a user error — the two roles are mutually exclusive.
            if has_child_attr(method) && has_method_attr(method) {
                return Err(syn::Error::new_spanned(
                    &method.sig,
                    "#[plexus_macros::child] and #[plexus_macros::method] are mutually exclusive \
                     on the same function: a function is either an RPC method or a child router \
                     entry, not both",
                ));
            }

            // CHILD-3: collect + validate `#[child]` methods. These are NOT
            // exposed as RPC methods; they contribute only to ChildRouter
            // routing. Strip the attribute after parsing so the emitted impl
            // block doesn't still carry the (now-no-op) `#[child]` macro
            // invocation.
            if has_child_attr(method) {
                // RETURNS-47: a trait impl's children are GRAFT-1's (a graft
                // point typed by an interface); not taken here.
                if let Some(path) = &trait_impl {
                    return Err(syn::Error::new_spanned(
                        &method.sig.ident,
                        format!(
                            "#[plexus_macros::child] in `impl {} for {struct_name}`: a trait impl's children \
                             are not served yet (GRAFT-1); declare the child in an inherent \
                             `#[plexus_macros::activation] impl` instead",
                            quote!(#path).to_string().replace(' ', "")
                        ),
                    ));
                }
                child_methods.push(ChildMethodInfo::from_fn(method)?);
                // Strip #[child] and the companion #[plexus_macros::removed_in]
                // — they're both macro-only markers that rustc does not
                // otherwise recognize on free-standing methods.
                method.attrs.retain(|a| {
                    let last = a.path().segments.last().map(|s| s.ident.to_string());
                    !matches!(last.as_deref(), Some("child") | Some("peer") | Some("removed_in"))
                });
                continue;
            }

            // RETURNS-47: `#[plexus_macros::from_auth(expr)]` on a method of
            // `impl Trait for Type` — the trait's form of a `#[from_auth]`
            // parameter, which a trait's signature cannot carry.
            let verifier_idx = method.attrs.iter().position(|a| {
                a.path().segments.last().is_some_and(|s| s.ident == "from_auth")
            });
            let verifier: Option<syn::Expr> = match verifier_idx {
                None => None,
                Some(idx) => {
                    let attr = method.attrs.remove(idx);
                    if trait_impl.is_none() {
                        return Err(syn::Error::new_spanned(
                            &attr,
                            "#[from_auth(…)] on a method is the form for `impl Trait for Type`, whose \
                             signatures cannot carry it; on an inherent method, put it on the parameter \
                             (`#[from_auth(self.access.verify)] user: User`)",
                        ));
                    }
                    Some(attr.parse_args::<syn::Expr>()?)
                }
            };

            // Accept both the canonical #[method] / #[plexus_macros::method] and
            // the deprecated #[hub_method] / #[plexus_macros::hub_method] spellings.
            let hub_method_idx = method.attrs.iter().position(|attr| {
                let path = attr.path();
                let last = path.segments.last().map(|s| s.ident.to_string());
                matches!(last.as_deref(), Some("method") | Some("hub_method"))
            });

            if let Some(idx) = hub_method_idx {
                // Parse the attribute contents before removing
                let attr = method.attrs.remove(idx);
                let hub_method_attrs = match &attr.meta {
                    Meta::Path(_) => None, // #[hub_method] with no args
                    Meta::List(list) => {
                        Some(syn::parse2::<HubMethodAttrs>(list.tokens.clone())?)
                    }
                    Meta::NameValue(_) => None,
                };
                methods.push(MethodInfo::from_fn(method, hub_method_attrs.as_ref())?);
            } else if all_public_methods
                && (if trait_impl.is_some() {
                    // RETURNS-47: every `async fn` on `&self` of the trait.
                    contract::is_trait_wire_shape(method)
                } else {
                    contract::is_wire_shape(method)?
                })
            {
                // MACRO-13: unmarked, and on the wire by its shape.
                methods.push(MethodInfo::from_fn(method, None)?);
            } else {
                if let Some(v) = &verifier {
                    return Err(syn::Error::new_spanned(
                        v,
                        "#[from_auth(…)] on a method that is not on the wire: only a wire method has a caller to verify",
                    ));
                }
                continue;
            }
            if let Some(m) = methods.last_mut() {
                m.verifier = verifier;
            }

            {
                // Strip #[plexus_macros::removed_in(...)] companion — rustc
                // doesn't know what to do with it, and the macro has already
                // folded its value into the `MethodInfo.deprecation` struct.
                method.attrs.retain(|a| {
                    let last = a.path().segments.last().map(|s| s.ident.to_string());
                    !matches!(last.as_deref(), Some("removed_in"))
                });

                // Strip #[from_auth(...)], #[activation_param], IR-5's
                // #[deprecated] / #[plexus_macros::removed_in], AND
                // AUTHZ-MACRO-PARAM-DOC-1's `///` doc comments from
                // parameters so rustc doesn't complain about unknown /
                // unstable attributes on parameters when the emitted
                // function signature is re-rendered. The doc-comment
                // text has already been captured into
                // `ParamInfo.description` by `MethodInfo::from_fn`.
                for arg in &mut method.sig.inputs {
                    if let FnArg::Typed(pat_type) = arg {
                        pat_type.attrs.retain(|attr| {
                            let last =
                                attr.path().segments.last().map(|s| s.ident.to_string());
                            !attr.path().is_ident("from_auth")
                                && !attr.path().is_ident("activation_param")
                                && !attr.path().is_ident("doc")
                                && !matches!(
                                    last.as_deref(),
                                    Some("deprecated") | Some("removed_in")
                                )
                        });
                    }
                }
            }
        }
    }

    // MACRO-13: a bodiless activation is a contract — every wire method
    // bodiless, none bodied — and a bodiless method must be on the wire.
    let contract_mode = !bodiless.is_empty();
    if contract_mode {
        if let Some(f) = bodiless.iter().find(|b| !methods.iter().any(|m| &m.fn_name == *b)) {
            return Err(syn::Error::new(
                f.span(),
                format!(
                    "`{f}` has no body, and is not a wire method; only a wire method may be \
                     bodiless (a bodiless activation is a contract its implementor fills)"
                ),
            ));
        }
        if methods.iter().any(|m| !bodiless.contains(&m.fn_name)) {
            let first = &bodiless[0];
            return Err(syn::Error::new(
                first.span(),
                format!(
                    "`{first}` has no body, but other wire methods of this activation do: a \
                     contract has no bodies and a server has all of them. Give `{first}` a body, \
                     or remove the bodies of the others."
                ),
            ));
        }
    }
    // A contract is its trait; one written before MACRO-13 (its namespace
    // said, no trait named) has none to be.
    if contract_mode && names.trait_ident.is_none() {
        return Err(syn::Error::new(
            struct_name.span(),
            format!(
                "`{struct_name}` is bodiless, so it is a contract, and a contract is its trait; \
                 name it with `trait = \"…\"` in the attribute (or name the type \
                 `{struct_name}Activation`, whose trait is `{struct_name}`)."
            ),
        ));
    }
    // RETURNS-47 (owner, 2026-11-04, reversing MACRO-13's `always`): a
    // trait only when named (`trait = "…"`) or for a contract — each method
    // in it under its own return type (RETURNS-36).
    let trait_ident: Option<syn::Ident> = names.trait_ident.clone();
    let self_callable = contract::self_callable(&methods);
    if contract_mode && !self_callable {
        let m = methods.iter().find(|m| contract::injected(m).is_some()).unwrap();
        return Err(syn::Error::new(
            m.fn_name.span(),
            format!(
                "`{}` takes {}, which the server injects; a contract's methods are what its \
                 implementor is called with, so they take only what a caller passes.",
                m.fn_name,
                contract::injected(m).unwrap()
            ),
        ));
    }
    if contract_mode {
        contract::rewrite_contract_impl(
            &mut input_impl,
            &struct_name,
            trait_ident.as_ref().unwrap(),
            &methods,
        )?;
    }

    // Get full self type (with generics) and impl generics for trait impl
    let self_ty = &input_impl.self_ty;
    let (impl_generics, _, where_clause) = input_impl.generics.split_for_impl();

    // RED-3: reject `#[from_auth(...)]` on any method when the activation
    // has no `request = SomeType` declaration. Auth extraction requires
    // AuthContext to be populated by the activation-level PlexusRequest
    // extraction chain. Without `request = ...`, the resolver will
    // always receive `None` and every call 401s — ergonomics-bad, not
    // security-bad, but worth catching at compile time.
    if args.request_type.is_none() {
        if let Some(m) = methods.iter().find(|m| !m.auth_resolvers.is_empty()) {
            return Err(syn::Error::new(
                m.fn_name.span(),
                format!(
                    "RED-3: method `{}` uses `#[from_auth(...)]` but the activation \
                     declares no `request = SomeType`. Auth extraction requires a \
                     PlexusRequest struct to wire AuthContext through. Add \
                     `request = MyRequest` to `#[plexus::activation(...)]`, or remove \
                     the `#[from_auth]` annotation.",
                    m.method_name
                ),
            ));
        }
    }

    // AUTH-3: the activation's default roles, validated against its methods
    // and flattened to grants (`<namespace>.<method>`).
    let slot_names: Vec<String> = child_methods
        .iter()
        .filter(|c| matches!(c.kind, crate::parse::ChildMethodKind::Dynamic))
        .map(|c| c.fn_name.to_string())
        .collect();
    let declared_roles = resolve_roles(&args.roles, &methods, &namespace, &slot_names)?;

    // REQ-10: validate per-method request overrides against the activation's
    // `required = [...]` lock list. If the activation has any required fields
    // and a method uses `request = ()`, emit a compile error naming the
    // fields that would be dropped.
    if !args.required_fields.is_empty() {
        for m in &methods {
            if matches!(m.request_override, Some(crate::parse::MethodRequestOverride::Skip)) {
                let required_names: Vec<String> = args.required_fields
                    .iter()
                    .map(|i| i.to_string())
                    .collect();
                return Err(syn::Error::new(
                    m.fn_name.span(),
                    format!(
                        "REQ-10: method `{}` uses `request = ()` but activation's `required = [{}]` \
                         locks these fields. Either remove the method-level `request = ()` override \
                         or remove the activation's `required` list (or move the method to a \
                         different activation).",
                        m.method_name,
                        required_names.join(", ")
                    ),
                ));
            }
        }
    }

    // IR-5: capture activation-level `#[deprecated]` (+ optional
    // `#[plexus_macros::removed_in]`) from the impl block's attributes
    // BEFORE the IR-3 cleanup below strips the `#[removed_in]` companion.
    // Threads through to `activation::generate` which emits
    // `PluginSchema.deprecation` when populated.
    let activation_deprecation: Option<ParsedDeprecation> =
        parse_deprecation_attrs(&input_impl.attrs, input_impl.span())?;

    // IR-3/IR-5: strip any residual `#[plexus_macros::removed_in(...)]`
    // attribute that landed on a bare (non-#[method], non-#[child]) impl
    // item, or on the impl block itself — the companion attribute is
    // macro-only and rustc doesn't know how to handle it.
    //
    // Also strip the IR-5 `#[doc = "__plexus_removed_in:X"]` sentinel that
    // the outer-expansion path uses to bridge impl-block-level `#[removed_in]`
    // past its own premature expansion — the activation macro has already
    // folded it into `activation_deprecation` by now.
    input_impl.attrs.retain(|a| {
        let last = a.path().segments.last().map(|s| s.ident.to_string());
        if matches!(last.as_deref(), Some("removed_in")) {
            return false;
        }
        if a.path().is_ident("doc") {
            if let syn::Meta::NameValue(syn::MetaNameValue { value, .. }) = &a.meta {
                if let syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Str(s),
                    ..
                }) = value
                {
                    if s.value().starts_with("__plexus_removed_in:") {
                        return false;
                    }
                }
            }
        }
        true
    });
    for item in &mut input_impl.items {
        if let ImplItem::Fn(f) = item {
            f.attrs.retain(|a| {
                let last = a.path().segments.last().map(|s| s.ident.to_string());
                !matches!(last.as_deref(), Some("removed_in"))
            });
        }
    }

    // MACRO-12: `typed_params` refuses a bare string parameter, on the
    // parameter's own span. `MethodInfo::params` already excludes what the
    // server injects (`auth`, `reach`, `#[from_auth]`, `#[activation_param]`),
    // so those are exempt by construction.
    if args.typed_params {
        let mut errors: Option<syn::Error> = None;
        for m in &methods {
            for p in &m.params {
                if is_bare_string_type(&p.ty) {
                    let e = syn::Error::new_spanned(
                        &p.ty,
                        format!(
                            "`{}.{}`: a bare string parameter; give it a type (typed_params)",
                            m.method_name, p.name
                        ),
                    );
                    match &mut errors {
                        Some(all) => all.combine(e),
                        None => errors = Some(e),
                    }
                }
            }
        }
        if let Some(e) = errors {
            return Err(e);
        }
    }

    // CHILD-3: at most one dynamic `#[child]` method per impl.
    let dynamic_children: Vec<&ChildMethodInfo> = child_methods
        .iter()
        .filter(|c| matches!(c.kind, ChildMethodKind::Dynamic) && c.peer.is_none())
        .collect();
    if dynamic_children.len() > 1 {
        let names: Vec<String> = dynamic_children
            .iter()
            .map(|c| c.fn_name.to_string())
            .collect();
        return Err(syn::Error::new_spanned(
            &input_impl,
            format!(
                "at most one dynamic #[child] method is allowed per activation impl; \
                 found {}: {}",
                dynamic_children.len(),
                names.join(", ")
            ),
        ));
    }

    // CHILD-3: reject mixing the legacy `children = [...]` attribute with
    // the new `#[child]` method attribute on the same impl — the two
    // systems don't merge, and silently picking one would hide intent.
    if !child_methods.is_empty() && !args.children.is_empty() {
        return Err(syn::Error::new_spanned(
            &input_impl,
            "#[plexus_macros::child] methods cannot be combined with the legacy \
             `children = [...]` activation attribute on the same impl; choose one. \
             Remove `children = [...]` to migrate to the method-based syntax.",
        ));
    }

    // CHILD-4: resolve `list = "..."` / `search = "..."` args against the
    // same-impl sibling methods. Missing names produce `not found in impl`;
    // signature mismatches produce an error containing `signature mismatch`.
    let mut list_method: Option<ListSearchMethodInfo> = None;
    let mut search_method: Option<ListSearchMethodInfo> = None;
    // NEST-7: whether a peer slot's `list` sibling is `async`.
    for child in child_methods.iter_mut().filter(|c| c.peer.is_some()) {
        if let Some(list) = &child.list_fn {
            child.list_is_async = input_impl.items.iter().any(|i| matches!(i, ImplItem::Fn(f) if &f.sig.ident == list && f.sig.asyncness.is_some()));
        }
    }
    // NEST-7: a `#[peer]` slot's `list` / `search` are its role's alone
    // (siblings a caller calls), not the router's.
    for child in child_methods.iter().filter(|c| c.peer.is_none()) {
        if let Some(name) = &child.list_fn {
            let info = find_and_validate_list_search_method(
                &input_impl.items,
                name,
                ListSearchKind::List,
                &child.fn_name,
            )?;
            if list_method.is_some() {
                return Err(syn::Error::new(
                    name.span(),
                    format!(
                        "duplicate `list = \"{}\"` across #[plexus_macros::child] methods; \
                         at most one list method per activation impl",
                        name
                    ),
                ));
            }
            list_method = Some(info);
        }
        if let Some(name) = &child.search_fn {
            let info = find_and_validate_list_search_method(
                &input_impl.items,
                name,
                ListSearchKind::Search,
                &child.fn_name,
            )?;
            if search_method.is_some() {
                return Err(syn::Error::new(
                    name.span(),
                    format!(
                        "duplicate `search = \"{}\"` across #[plexus_macros::child] methods; \
                         at most one search method per activation impl",
                        name
                    ),
                ));
            }
            search_method = Some(info);
        }
    }

    if methods.is_empty() {
        return Err(syn::Error::new_spanned(
            &input_impl,
            "No #[plexus::method] functions found",
        ));
    }

    // CHILD-8: Mixing the explicit `hub` flag with `#[child]` methods is
    // ambiguous — both are mechanisms for declaring "this activation is a
    // hub". Require the user to pick exactly one.
    if args.hub && !child_methods.is_empty() {
        return Err(syn::Error::new_spanned(
            &input_impl,
            "#[plexus_macros::activation(hub, ...)] cannot be combined with #[plexus_macros::child] \
             methods — the macro infers hub-mode from the presence of #[child] methods. Remove the \
             'hub' flag or remove the #[child] methods.",
        ));
    }

    // CHILD-8: hub-mode is inferred from either the explicit `hub` flag OR
    // the presence of any `#[child]` method. Both sources feed into
    // `call_fallback` / `plugin_schema_body` codegen. The explicit flag is
    // also threaded through separately so `child_router_impl` can still
    // recognize the legacy Solar pattern (hand-written router + no `#[child]`).
    let effective_hub = args.hub || !child_methods.is_empty();
    let hub_explicit = args.hub;

    // CHILD-8: detect whether the impl already carries a `fn plugin_children(&self)`
    // so the macro doesn't shadow a user-written one when synthesizing. We scan
    // for an ImplItem::Fn named `plugin_children` whose first parameter is a
    // receiver (`&self`). Anything else (same name, different shape) is treated
    // as "not defined" for synthesis purposes — the user's item compiles as-is
    // and any collision surfaces as a regular Rust name-clash error.
    let impl_defines_plugin_children = input_impl.items.iter().any(|item| {
        if let ImplItem::Fn(f) = item {
            if f.sig.ident == "plugin_children" {
                return matches!(f.sig.inputs.first(), Some(FnArg::Receiver(_)));
            }
        }
        false
    });

    // CHILD-8: synthesize `plugin_children` when at least one `#[child]` method
    // is present and the impl doesn't already define one. Dynamic `#[child]`
    // methods are intentionally omitted — a finite `ChildSummary` list isn't
    // meaningful for an open-ended name set; dynamic children are discoverable
    // via `ChildRouter::list_children` at runtime when opted in.
    let synthesize_plugin_children =
        !child_methods.is_empty() && !impl_defines_plugin_children;

    // Resolve the activation description with this precedence:
    //   1. Explicit `description = "..."` on #[plexus_macros::activation(...)] wins.
    //   2. Otherwise fall back to `///` doc comments on the impl block, joined with
    //      '\n' and with common leading whitespace stripped (same rule as `cargo doc`).
    //   3. If neither is present, description is the empty string.
    let resolved_description: String = args
        .description
        .clone()
        .or_else(|| extract_doc_description(&input_impl.attrs))
        .unwrap_or_default();

    // IR-10: every `#[child]` method emits a `MethodSchema` entry unconditionally,
    // regardless of whether `plugin_children()` is hand-written or synthesized
    // (CHILD-8 inferred hub). IR-4 relaxed plexus-core's `validate_no_collisions`
    // to recognize that a static-child method and the derived `ChildSummary`
    // of the same name are the same thing by construction, not a collision.
    // Downstream consumers (synapse, hub-codegen, any IR reader) see the full
    // role-tagged method list.
    let schema_child_methods: Vec<ChildMethodInfo> = child_methods.clone();

    // Strip the `#[deprecated]` attribute from the impl block itself so the
    // emitted trait impl doesn't carry it (rustc accepts it but reports
    // false-positive "use of deprecated ..." warnings inside the generated
    // code). `#[plexus_macros::removed_in]` is already stripped earlier.
    input_impl.attrs.retain(|a| !a.path().is_ident("deprecated"));

    // IR-5: deprecation warnings for attribute args `hub` and `children = [...]`.
    let hub_deprecation_warning =
        hub_flag_deprecation_warning(args.hub, args.hub_span, &struct_name);
    let children_deprecation_warning = children_arg_deprecation_warning(
        !args.children.is_empty(),
        args.children_span,
        &struct_name,
    );

    // RED-6: enforce declared auth posture.
    //
    // - `auth = "required"`: every method must either use #[from_auth] OR
    //   carry #[plexus_macros::method(public)]. Compile error otherwise.
    // - `auth = "none"`: no method may use #[from_auth]. Compile error if any.
    // - `auth = "optional"` (default): no enforcement. RED-2 emits a warning
    //   when auth is asymmetric across methods in this activation.
    // - `auth = "mixed"`: like optional but suppresses the RED-2 warning
    //   (explicit acknowledgment of the asymmetry).
    //
    // AUTHZ-MACRO-OPTIONAL-AUTH-1 carve-out: a method whose signature is
    // `auth: Option<&AuthContext>` is an explicit opt-in to anonymous-friendly
    // handling. Under `auth = "required"` we downgrade the previous hard error
    // to a compile-time warning ("handler accepts anonymous but activation
    // requires auth") so the trak-style "anonymous read, authed write"
    // pattern is reachable.
    // R-1 (joint AP-1): enforcement treats an undeclared posture as
    // `Optional` (unchanged RED-6 semantics); only a DECLARED posture is
    // emitted into the generated MethodSchema entries (see
    // `method_enum::generate`).
    let effective_auth_posture = args.auth_posture.unwrap_or_default();
    // 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, typed — what a `#[from_auth]` parameter does on an
    // inherent method — for `auth = "required"` on every method not
    // `public`, and for every method with a verifier.
    if trait_impl.is_some() {
        let required = matches!(effective_auth_posture, crate::parse::AuthPosture::Required);
        for m in methods.iter_mut() {
            m.caller_required = m.verifier.is_some() || (required && !m.public);
        }
    }
    let mut required_posture_optional_auth_methods: Vec<&crate::parse::MethodInfo> = Vec::new();
    match effective_auth_posture {
        crate::parse::AuthPosture::Required => {
            for m in &methods {
                // RETURNS-47: a trait impl's signature cannot carry
                // `#[from_auth]`; its methods reach their caller through the
                // call's context (`plexus_core::call::caller()`), the gate
                // having decided first.
                if m.auth_resolvers.is_empty() && !m.public && trait_impl.is_none() {
                    if m.auth_optional {
                        required_posture_optional_auth_methods.push(m);
                        continue;
                    }
                    return Err(syn::Error::new(
                        m.fn_name.span(),
                        format!(
                            "RED-6: activation `{}` is `auth = \"required\"` but method \
                             `{}` has no #[from_auth(...)] and no \
                             #[plexus_macros::method(public)] acknowledgment. \
                             Either gate the method with #[from_auth(resolver)] \
                             or explicitly mark it public with \
                             #[plexus_macros::method(public)].",
                            struct_name, m.method_name,
                        ),
                    ));
                }
            }
        }
        crate::parse::AuthPosture::None => {
            for m in &methods {
                if !m.auth_resolvers.is_empty() {
                    return Err(syn::Error::new(
                        m.fn_name.span(),
                        format!(
                            "RED-6: activation `{}` is `auth = \"none\"` (affirmative public) \
                             but method `{}` uses #[from_auth(...)]. Remove the \
                             annotation or change the activation's auth posture.",
                            struct_name, m.method_name,
                        ),
                    ));
                }
            }
        }
        crate::parse::AuthPosture::Mixed | crate::parse::AuthPosture::Optional => {}
    }
    let required_posture_optional_auth_warning = required_posture_optional_auth_warning(
        &required_posture_optional_auth_methods,
        &struct_name,
    );

    // RED-2: warn when the activation has methods with #[from_auth] and other
    // methods without. Suppressed under `auth = "mixed"` (explicit) and the
    // two strict postures (where compile-time errors already cover the cases).
    let suppress_mixed_warning =
        !matches!(effective_auth_posture, crate::parse::AuthPosture::Optional);
    let mixed_auth_warning = mixed_auth_warning(&methods, suppress_mixed_warning, &struct_name);

    // AUTHZ-CRED-MACRO-3: resolve the optional `plexus-auth-core` path used by
    // the credentials-registry call site in `compute_method_schemas`. None
    // means the consuming crate doesn't depend on `plexus-auth-core` and so
    // the macro should emit empty credential metadata (preserving pre-ticket
    // behavior).
    let auth_core_path = resolve_auth_core_path(Span::call_site());

    // Z2H-2: per-expansion dependency shim. Every third-party name in the
    // emitted code resolves relatively through this module; whether it
    // re-exports `::plexus_rpc::__deps::*` (umbrella consumer) or the extern
    // prelude (direct consumer) is decided once in `deps_shim`.
    let deps = format_ident!("__plexus_deps_{}", struct_name);
    let deps_shim_mod = deps_shim(&deps, Span::call_site());

    // Generate pieces
    let method_enum = method_enum::generate(
        &struct_name,
        &methods,
        &schema_child_methods,
        &crate_path,
        auth_core_path.as_ref(),
        args.request_type.as_ref(),  // REQ-6: activation-level request type (for runtime merge)
        &deps,
        args.auth_posture, // R-1: declared posture (None = silent, pre-R-1 wire)
        &namespace,        // AUTH-3: each method's grant is `<namespace>.<method>`
    );
    let activation_impl = activation::generate(
        &struct_name,
        self_ty,
        &impl_generics,
        where_clause,
        &namespace,
        args.version.as_deref(),
        &resolved_description,
        args.long_description.as_deref(),
        &methods,
        &crate_path,
        args.resolve_handle,
        effective_hub,
        hub_explicit,
        synthesize_plugin_children,
        args.plugin_id.as_deref(),
        args.namespace_fn.as_deref(),
        args.request_type.as_ref(),
        &args.children,
        &child_methods,
        list_method.as_ref(),
        search_method.as_ref(),
        activation_deprecation.as_ref(),
        &deps,
        &declared_roles,
        args.typed_params, // MACRO-31: an unknown key is refused under it
        trait_impl.as_ref(), // RETURNS-47: methods called through the trait
    );

    // MACRO-2 / MACRO-13: the typed client. Under the name rule it is
    // emitted whenever the crate depends on plexus-client, and the `client`
    // flag is ignored with a warning; otherwise (an activation the rule does
    // not apply to) the flag asks for it, as before.
    let client_path: Option<syn::Path> = if names.new_form {
        client::resolve_client_path(Span::call_site()).ok()
    } else if args.client {
        let span = args.client_span.unwrap_or_else(Span::call_site);
        Some(client::resolve_client_path(span)?)
    } else {
        None
    };
    let client_flag_warning = if names.new_form && args.client {
        contract::client_flag_warning(args.client_span.unwrap_or_else(Span::call_site), &struct_name)
    } else if !names.new_form {
        // MACRO-13: an activation the name rule cannot name, written before
        // it, builds as it did and asks for the rename.
        contract::legacy_name_warning(&struct_name)
    } else {
        TokenStream::new()
    };
    let (client_impl, client_server_checks) = match &client_path {
        Some(path) => {
            let (mut client, checks) = client::generate(&names.client_ident, &namespace, &methods, &child_methods, path)?;
            // RETURNS-47: a parent's `#[child]` names its child's client from
            // the child type (`{stem}Client`, MACRO-16). Where this
            // activation's client is named otherwise — `impl Trait for Type`
            // (the trait's), `trait = "…"` — the type's name is an alias of
            // it, so the type can be a child.
            let type_name = struct_name.to_string();
            let by_type = format_ident!("{}Client", contract::stem_of(&type_name).unwrap_or(&type_name));
            if by_type != names.client_ident {
                let client_ident = &names.client_ident;
                let doc = format!("`{client_ident}`, by the name of the type it is the client of (`{struct_name}`): how a parent's `#[child]` names it.");
                client.extend(quote! {
                    #[doc = #doc]
                    pub type #by_type<T, L = #path::Root> = #client_ident<T, L>;
                });
            }
            // RETURNS-46: this activation has a client, which a parent's
            // `#[child]` checks for (in the server half, where the type is).
            let has_client = quote! {
                impl #impl_generics #path::HasClient for #self_ty #where_clause {}
            };
            (client, quote! { #has_client #checks })
        }
        None => (TokenStream::new(), TokenStream::new()),
    };

    // MACRO-2 / MACRO-13: the cfg the server half is gated on — `server_cfg`
    // when given; under the name rule, `feature = "server"` when the crate
    // declares that feature; otherwise none.
    let server_gate: Option<syn::Meta> = match &args.server_cfg {
        Some(pred) => {
            let span = args.server_cfg_span.unwrap_or_else(Span::call_site);
            if !names.new_form && !args.client {
                return Err(syn::Error::new(
                    span,
                    "#[plexus_macros::activation]: `server_cfg = \"...\"` suppresses the \
                     server half of the expansion, which only makes sense alongside the \
                     `client` flag — otherwise the attribute emits nothing at all under \
                     the negated predicate. Add `client`, or put your own `#[cfg]` on the \
                     module instead.",
                ));
            }
            Some(contract::parse_gate(pred, span)?)
        }
        None if names.new_form && contract::manifest_declares_server_feature() => {
            Some(syn::parse_quote!(feature = "server"))
        }
        None => None,
    };

    // MACRO-13: the trait, its implementations, and a contract's struct.
    let mut trait_server_items = TokenStream::new();
    let mut trait_items = TokenStream::new();
    if let Some(trait_ident) = &trait_ident {
        let boxes = contract::boxes(
            client_path.as_ref(),
            &crate_path,
            args.trait_span.unwrap_or_else(Span::call_site),
        )?;
        trait_items.extend(contract::trait_def(
            trait_ident,
            &struct_name,
            &resolved_description,
            &methods,
            &boxes,
            contract_mode,
            server_gate.as_ref(),
        ));
        if contract_mode {
            trait_server_items.extend(contract::contract_items(
                trait_ident,
                &struct_name,
                &methods,
                &boxes,
            ));
            // NEST-7: a contract every method of which answers one
            // `Result<T, E>` is a typed slot's interface: `{Trait}Peer`, its
            // `Contract`, and the client over a `PeerTransport` as both.
            if let (Some(cp), true) = (client_path.as_ref(), peer::peerable(&methods)) {
                let version_expr = match &args.version {
                    Some(v) => quote! { #v },
                    None => quote! { env!("CARGO_PKG_VERSION") },
                };
                trait_server_items.extend(peer::contract_peer_items(
                    trait_ident,
                    &struct_name,
                    &namespace,
                    &resolved_description,
                    &version_expr,
                    &methods,
                    &boxes.future,
                    &names.client_ident,
                    cp,
                    &crate_path,
                    &deps,
                ));
            }
        } else if self_callable {
            trait_server_items.extend(contract::activation_trait_impl(
                trait_ident,
                &struct_name,
                self_ty,
                &impl_generics,
                where_clause,
                &methods,
                &boxes,
                &deps,
            ));
        }
    }

    // MACRO-2: everything above this line is the SERVER half. When gated it
    // is emitted under that cfg, so a build that does not satisfy the
    // predicate gets the client (and the trait) and nothing else — which is
    // how an activation crate becomes reachable from wasm32.
    let server_half = quote! {
        #deps_shim_mod
        #trait_server_items
        #input_impl
        #method_enum
        #activation_impl
        #hub_deprecation_warning
        #children_deprecation_warning
        #mixed_auth_warning
        #required_posture_optional_auth_warning
        #client_server_checks
    };

    let server_half = match &server_gate {
        None => server_half,
        Some(meta) => cfg_gate(server_half, meta, Span::call_site())?,
    };

    let streaming_warnings = contract::streaming_warnings(&methods, &struct_name);

    Ok(quote! {
        #server_half
        #trait_items
        #client_impl
        #client_flag_warning
        #streaming_warnings
    })
}

/// AUTH-3: check `roles(...)` and flatten it: each role's entries are
/// methods of this activation (by their RPC name) or roles declared before
/// it; `admin` is built in and cannot be declared or listed. Returns each
/// role with its grants (`<namespace>.<method>`), in declaration order.
fn resolve_roles(
    decls: &[crate::parse::RoleDecl],
    methods: &[MethodInfo],
    namespace: &str,
    slots: &[String],
) -> syn::Result<Vec<(String, Vec<String>)>> {
    use crate::parse::RoleEntry;
    let mut out: Vec<(String, Vec<String>)> = Vec::new();
    for decl in decls {
        let name = decl.name.to_string();
        if name == "admin" {
            return Err(syn::Error::new(
                decl.name.span(),
                "`admin` is built in and holds every grant; it needs no list",
            ));
        }
        if out.iter().any(|(n, _)| *n == name) {
            return Err(syn::Error::new(decl.name.span(), format!("role `{name}` is declared twice")));
        }
        let mut grants: Vec<String> = Vec::new();
        let mut push = |g: String, grants: &mut Vec<String>| {
            if !grants.contains(&g) {
                grants.push(g);
            }
        };
        for entry in &decl.entries {
            match entry {
                // NEST-5: a slot grant — `"{planet}.info"` or
                // `"<namespace>.{planet}.info"`, `{planet}` a dynamic
                // `#[child]` of this activation — taken as the slot's grant
                // (`<namespace>.{planet}.info`; an untyped slot whole,
                // `<namespace>.{planet}`).
                RoleEntry::Method(lit) if lit.value().contains('{') => {
                    let v = lit.value();
                    let rel = v.strip_prefix(&format!("{namespace}.")).unwrap_or(&v).to_string();
                    let slot = rel
                        .strip_prefix('{')
                        .and_then(|r| r.split_once('}'))
                        .map(|(s, _)| s.to_string());
                    match slot {
                        Some(slot) if slots.contains(&slot) => push(format!("{namespace}.{rel}"), &mut grants),
                        _ => {
                            return Err(syn::Error::new(
                                lit.span(),
                                format!(
                                    "role `{name}` lists \"{v}\", a slot grant whose slot is not a dynamic \
                                     #[child] of this activation; its slots are: {}",
                                    if slots.is_empty() { "(none)".to_string() } else { slots.join(", ") }
                                ),
                            ))
                        }
                    }
                }
                RoleEntry::Method(lit) => {
                    let m = lit.value();
                    if !methods.iter().any(|mi| mi.method_name == m) {
                        let known: Vec<&str> = methods.iter().map(|mi| mi.method_name.as_str()).collect();
                        return Err(syn::Error::new(
                            lit.span(),
                            format!(
                                "role `{name}` lists \"{m}\", which is not a method of this activation; \
                                 its methods are: {}",
                                known.join(", ")
                            ),
                        ));
                    }
                    push(format!("{namespace}.{m}"), &mut grants);
                }
                RoleEntry::Role(ident) => {
                    let inc = ident.to_string();
                    let Some((_, included)) = out.iter().find(|(n, _)| *n == inc) else {
                        return Err(syn::Error::new(
                            ident.span(),
                            if inc == "admin" {
                                format!("role `{name}` cannot include `admin`, which holds every grant")
                            } else {
                                format!(
                                    "role `{name}` includes `{inc}`, which is not declared before it \
                                     (a role may include only roles listed earlier in `roles(...)`)"
                                )
                            },
                        ));
                    };
                    for g in included.clone() {
                        push(g, &mut grants);
                    }
                }
            }
        }
        out.push((name, grants));
    }
    Ok(out)
}

/// MACRO-2: put `#[cfg(<pred>)]` on every item of an emitted token stream.
///
/// `#[cfg]` attaches to *items*, not to token streams, so the aggregate is
/// re-parsed as a `syn::File` and each item is re-emitted with the attribute
/// prepended. The round trip is safe because the input is our own output —
/// already valid Rust, spans preserved by syn.
fn cfg_gate(items: TokenStream, meta: &syn::Meta, span: Span) -> syn::Result<TokenStream> {
    let file: syn::File = syn::parse2(items).map_err(|e| {
        syn::Error::new(
            span,
            format!("plexus-macros could not re-parse its own expansion to apply server_cfg ({e})"),
        )
    })?;

    let gated = file.items.into_iter().map(|item| {
        quote! {
            #[cfg(#meta)]
            #item
        }
    });

    Ok(quote! { #(#gated)* })
}

/// AUTHZ-MACRO-OPTIONAL-AUTH-1: emit a compile-time warning when an
/// activation declares `auth = "required"` and one of its methods uses the
/// optional-auth handler shape `auth: Option<&AuthContext>`.
///
/// The combination is legal — the optional shape was added precisely so an
/// activation can serve anonymous reads alongside authed writes — but it's
/// worth flagging because the activation's declared posture says "every
/// caller must authenticate." Uses the same dummy-deprecated-const trick as
/// the IR-5 / RED-2 warnings.
fn required_posture_optional_auth_warning(
    methods: &[&crate::parse::MethodInfo],
    struct_name: &syn::Ident,
) -> TokenStream {
    if methods.is_empty() {
        return TokenStream::new();
    }
    let names = methods
        .iter()
        .map(|m| m.method_name.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    let note = format!(
        "plexus-macros (AUTHZ-MACRO-OPTIONAL-AUTH-1): activation `{}` declares \
         `auth = \"required\"` but the following method(s) accept anonymous \
         callers via `auth: Option<&AuthContext>`: {}. The handlers will see \
         `None` when no auth context is attached. If this is intentional, \
         consider `auth = \"mixed\"` to silence this warning; otherwise \
         change the handler signature to `auth: &AuthContext` (or use \
         `#[from_auth(...)]`).",
        struct_name, names,
    );
    let span = methods
        .first()
        .map(|m| m.fn_name.span())
        .unwrap_or_else(|| struct_name.span());
    let const_name = format_ident!(
        "_PLEXUS_MACROS_REQUIRED_POSTURE_OPTIONAL_AUTH_WARNING_{}",
        struct_name,
        span = span,
    );
    let touch_fn_name = format_ident!(
        "_plexus_macros_touch_required_posture_optional_auth_warning_{}",
        struct_name,
        span = span,
    );
    quote::quote_spanned! { span =>
        #[doc(hidden)]
        #[allow(non_upper_case_globals, non_snake_case, dead_code)]
        #[deprecated(since = "0.5", note = #note)]
        const #const_name: () = ();

        #[doc(hidden)]
        #[allow(non_snake_case, dead_code)]
        fn #touch_fn_name() {
            let _ = #const_name;
        }
    }
}

/// IR-5: emit a compile-time deprecation warning when
/// `#[plexus_macros::activation(hub)]` is used. Generates a `#[deprecated]`
/// dummy const and a touch-site that fires rustc's `deprecated` lint
/// at the span of the flag. Stable-compatible alternative to
/// `proc_macro::Diagnostic`.
fn hub_flag_deprecation_warning(
    hub_is_set: bool,
    hub_span: Option<Span>,
    struct_name: &syn::Ident,
) -> TokenStream {
    if !hub_is_set {
        return TokenStream::new();
    }
    let span = hub_span.unwrap_or_else(|| struct_name.span());
    let const_name = format_ident!(
        "_PLEXUS_MACROS_DEPRECATED_HUB_FLAG_{}",
        struct_name,
        span = span
    );
    // The trick: declare the deprecated const at module scope, and touch it
    // from a same-module hidden function. Rustc's `deprecated` lint fires at
    // the touch site because the function body is NOT inside the const's
    // own initializer (where the lint is suppressed as a consistency rule).
    let touch_fn_name = format_ident!(
        "_plexus_macros_touch_deprecated_hub_flag_{}",
        struct_name,
        span = span
    );
    quote::quote_spanned! { span =>
        #[doc(hidden)]
        #[allow(non_upper_case_globals, non_snake_case, dead_code)]
        #[deprecated(
            since = "0.5",
            note = "plexus-macros: the 'hub' argument is deprecated; hub mode is inferred automatically from #[child]-tagged methods. This argument will be removed in plexus-macros 0.6."
        )]
        const #const_name: () = ();

        #[doc(hidden)]
        #[allow(non_snake_case, dead_code)]
        fn #touch_fn_name() {
            // Referencing the deprecated const here fires rustc's
            // `deprecated` lint, pointing at the span of the `hub` flag.
            let _ = #const_name;
        }
    }
}

/// IR-5: emit a compile-time deprecation warning when
/// `#[plexus_macros::activation(children = [...])]` is used. Companion to
/// `hub_flag_deprecation_warning`; uses the same dummy-const mechanism.
fn children_arg_deprecation_warning(
    children_is_set: bool,
    children_span: Option<Span>,
    struct_name: &syn::Ident,
) -> TokenStream {
    if !children_is_set {
        return TokenStream::new();
    }
    let span = children_span.unwrap_or_else(|| struct_name.span());
    let const_name = format_ident!(
        "_PLEXUS_MACROS_DEPRECATED_CHILDREN_ARG_{}",
        struct_name,
        span = span
    );
    let touch_fn_name = format_ident!(
        "_plexus_macros_touch_deprecated_children_arg_{}",
        struct_name,
        span = span
    );
    quote::quote_spanned! { span =>
        #[doc(hidden)]
        #[allow(non_upper_case_globals, non_snake_case, dead_code)]
        #[deprecated(
            since = "0.5",
            note = "plexus-macros: the 'children' attribute argument is deprecated; use #[plexus_macros::child] on the accessor method(s) instead. This argument will be removed in plexus-macros 0.6."
        )]
        const #const_name: () = ();

        #[doc(hidden)]
        #[allow(non_snake_case, dead_code)]
        fn #touch_fn_name() {
            let _ = #const_name;
        }
    }
}

/// RED-2: emit a compile-time warning when an activation has a mix of
/// methods that use `#[from_auth(...)]` and methods that don't. The
/// asymmetry is almost always a bug — a developer added a new method
/// to an auth'd activation and forgot the annotation.
///
/// Suppression mechanisms:
/// - Activation declares `auth_posture = "mixed"` (intentional)
/// - Each non-auth method carries `#[plexus_macros::method(public)]`
///
/// Uses the same dummy-deprecated-const pattern as the IR-5 warnings.
fn mixed_auth_warning(
    methods: &[crate::parse::MethodInfo],
    auth_posture_mixed: bool,
    struct_name: &syn::Ident,
) -> TokenStream {
    if auth_posture_mixed {
        return TokenStream::new();
    }
    let any_auth = methods.iter().any(|m| !m.auth_resolvers.is_empty());
    if !any_auth {
        return TokenStream::new();
    }
    let unauthed: Vec<&crate::parse::MethodInfo> = methods
        .iter()
        .filter(|m| m.auth_resolvers.is_empty() && !m.public)
        .collect();
    if unauthed.is_empty() {
        return TokenStream::new();
    }
    let names = unauthed
        .iter()
        .map(|m| m.method_name.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    let note = format!(
        "plexus-macros (RED-2): activation `{}` mixes auth and non-auth \
         methods. The following methods do NOT have `#[from_auth(...)]`: {}. \
         If this is intentional, add `auth_posture = \"mixed\"` to the \
         activation attribute, or `#[plexus_macros::method(public)]` to each \
         intentionally-public method. Otherwise, the missing methods will \
         dispatch unauthenticated.",
        struct_name,
        names,
    );
    let span = unauthed
        .first()
        .map(|m| m.fn_name.span())
        .unwrap_or_else(|| struct_name.span());
    let const_name = format_ident!(
        "_PLEXUS_MACROS_MIXED_AUTH_WARNING_{}",
        struct_name,
        span = span,
    );
    let touch_fn_name = format_ident!(
        "_plexus_macros_touch_mixed_auth_warning_{}",
        struct_name,
        span = span,
    );
    quote::quote_spanned! { span =>
        #[doc(hidden)]
        #[allow(non_upper_case_globals, non_snake_case, dead_code)]
        #[deprecated(since = "0.5", note = #note)]
        const #const_name: () = ();

        #[doc(hidden)]
        #[allow(non_snake_case, dead_code)]
        fn #touch_fn_name() {
            let _ = #const_name;
        }
    }
}

/// MACRO-12: `String`, `&str`, `Option<String>`, `Option<&str>` or
/// `Vec<String>`, written literally (a `String` may be spelled
/// `std::string::String`). An alias (`type Name = String`) is not seen
/// through — a known limit, recorded, not worked around.
fn is_bare_string_type(ty: &syn::Type) -> bool {
    fn is_string(ty: &syn::Type) -> bool {
        let syn::Type::Path(tp) = ty else { return false };
        if tp.qself.is_some() {
            return false;
        }
        let segs: Vec<String> = tp.path.segments.iter().map(|s| s.ident.to_string()).collect();
        let bare_last = tp.path.segments.last().is_some_and(|s| s.arguments.is_empty());
        bare_last
            && matches!(
                segs.iter().map(String::as_str).collect::<Vec<_>>().as_slice(),
                ["String"] | ["std", "string", "String"] | ["alloc", "string", "String"]
            )
    }
    fn is_str_ref(ty: &syn::Type) -> bool {
        match ty {
            syn::Type::Reference(r) => matches!(&*r.elem, syn::Type::Path(p) if p.qself.is_none() && p.path.is_ident("str")),
            _ => false,
        }
    }
    fn wrapped<'a>(ty: &'a syn::Type, wrapper: &str) -> Option<&'a syn::Type> {
        let syn::Type::Path(tp) = ty else { return None };
        let last = tp.path.segments.last()?;
        if tp.qself.is_some() || last.ident != wrapper {
            return None;
        }
        let syn::PathArguments::AngleBracketed(args) = &last.arguments else { return None };
        match args.args.first() {
            Some(syn::GenericArgument::Type(inner)) if args.args.len() == 1 => Some(inner),
            _ => None,
        }
    }
    if is_string(ty) || is_str_ref(ty) {
        return true;
    }
    if let Some(inner) = wrapped(ty, "Option") {
        return is_string(inner) || is_str_ref(inner);
    }
    if let Some(inner) = wrapped(ty, "Vec") {
        return is_string(inner);
    }
    false
}